This post originated from an RSS feed registered with Web Buzz
by Stuart Langridge.
Original Post: More on favatars, and the urlparse module
Feed Title: as days pass by
Feed URL: http://feeds.feedburner.com/kryogenix
Feed Description: scratched tallies on the prison wall
The key bit in there is the <img class="favatar" alt=""
src="http://www.kryogenix.org/favatars/$cmt_link">.
http://www.kryogenix.org/favatars/*SOMETHING* goes to a Python CGI. You call it with a full URL, so http://www.kryogenix.org/favatars/http://simon.incutio.com/ will display either the favicon from Simon’s site or my “no icon” icon. This is made very easy by Python’s excellent urlparse module. You see, we need to get the favicon from the root of the server. To do this, just use urlparse.urljoin to join whatever URL you like with “/favicon.ico“. The key thing there is the / at the beginning. Watch:
>>> import urlparse
>>> urlparse.urljoin('http://www.kryogenix.org/','/favicon.ico')
'http://www.kryogenix.org/favicon.ico'
>>> urlparse.urljoin('http://www.kryogenix.org/days/','/favicon.ico')
'http://www.kryogenix.org/favicon.ico'
>>> urlparse.urljoin('http://www.kryogenix.org/days/something','/favicon.ico')
'http://www.kryogenix.org/favicon.ico'
>>> urlparse.urljoin('something that is not a URL','/favicon.ico')
'/favicon.ico'
>>> urlparse.urljoin('','/favicon.ico')
'/favicon.ico'
So, if you join the URL the punter left with “/favicon.ico“, then you get the URL for favicon.ico at the root of their domain. If they fill in something that isn’t a proper URL, like an email address, a mailto: with email address, blankness, or some bullshit, then you just get back “/favicon.ico“. The script checks, and, if the joined URL is “/favicon.ico“, it shows the “no icon” icon. If it isn’t, then it fetches the URL, transforms it to a 40×40 PNG, and streams that PNG for display. All nice and easy, thanks to the Python urlparse, urllib, StringIO, and Image libraries.
The code also caches icons so that it works faster. You can read the code for favatar.cgi if you would like more details; it won’t work directly for you without some tweaking. You’ll also want a line similar to this in your .htaccess file: