More on favatars, and the urlparse module

Bit more detail on how I implemented the favatars stuff, perhaps. The template that defines how a comment is output looks like this:

`<div id="au$cmt_time" class="onecomment">`
`<img class="favatar" alt="whatever" src="http://www.kryogenix.org/favatars/$cmt_link">`
`<h4>$cmt_author_and_link</h4>`
`$cmt_description`
`<a href="#au$cmt_time">#</a>`
`</div>`

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:

RewriteRule   ^favatars/(.*)            /pyblosxom/favatar.cgi?url=$1
I'm currently available for hire, to help you plan, architect, and build new systems, and for technical writing and articles. You can take a look at some projects I've worked on and some of my writing. If you'd like to talk about your upcoming project, do get in touch.

More in the discussion (powered by webmentions)

  • (no mentions, yet.)