[Welcome] [TitleIndex] [WordIndex

Problem

For some reason you need to produce different output depending on the HTTP client being used to view your site.

Solution

The guess_browser_version() method of the HTTPRequest class returns the name and version of the HTTP client.

browser, version = request.guess_browser_version()
if browser == "MSIE":
    return msie_page(request)
elif browser == "Mozilla":
    return mozilla_page(request)
else:
    return default_page(request)

Discussion

Alternatively, you can examine the User-Agent header and pick it apart with regular expressions. However, the header values are usually confusing -- every browser claims to be Mozilla, for example -- so you're likely to spend some time getting your regex patterns just right.

Do *not* assume that all users are using either Internet Explorer or Netscape/Mozilla, and deny access if the browser isn't one of those two. This is highly irritating to users of Konqueror, Opera, Safari, and it's easily avoidable by writing your application properly.

And of course, you should try to avoid the necessity for such browser-related hackery by writing straightforward HTML, not trying to have pixel-perfect displays on every conceivable browser, and avoiding overly complicated JavaScript -- but you already know that.


CategoryCookbook


2010-09-22 22:14