Created
September 13, 2012 12:01
-
-
Save creotiv/3713891 to your computer and use it in GitHub Desktop.
Django browser detection middleware
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import re | |
""" | |
Detect browser and it's version. | |
Now it works only for few moct common browsers. Full list of browsers and | |
theire user-agent you can find here: http://www.useragentstring.com/pages/useragentstring.php | |
Version: 0.1 | |
Author: Andrey Nikishaev | |
Site: http://creotiv.in.ua/ | |
""" | |
class BrowserDetectionMiddleware(object): | |
def __init__(self): | |
self.data_browser = [ | |
{ | |
'subString': "Chrome", | |
'identity': "Chrome", | |
'versionSearch': "Chrome/" | |
}, | |
{ | |
'subString': "Apple", | |
'identity': "Safari", | |
'versionSearch': "Version/" | |
}, | |
{ # For Netscape >= 9.0 | |
'subString': "Navigator", | |
'identity': "Netscape", | |
'versionSearch': "Navigator/" | |
}, | |
{ # For Netscape 7.0-9.0 | |
'subString': "Netscape", | |
'identity': "Netscape", | |
'versionSearch': "Netscape/" | |
}, | |
{ # For Netscape 6.x | |
'subString': "Netscape6", | |
'identity': "Netscape", | |
'versionSearch': "Netscape6/" | |
}, | |
{ | |
'subString': "Opera Mini", | |
'identity': "Opera Mini", | |
'versionSearch': "Opera Mini/" | |
}, | |
{ | |
'subString': "Opera", | |
'identity': "Opera", | |
'versionSearch': "Version/" | |
}, | |
{ | |
'subString': "Firefox", | |
'identity': "Firefox", | |
'versionSearch': "Firefox/" | |
}, | |
{ | |
'subString': "MSIE", | |
'identity': "Explorer", | |
'versionSearch': "MSIE " | |
}, | |
{ | |
'subString': "Konqueror", | |
'identity': "Konqueror", | |
'versionSearch': "Konqueror/" | |
}, | |
{ | |
'subString': "SeaMonkey", | |
'identity': "SeaMonkey", | |
'versionSearch': "SeaMonkey/" | |
}, | |
{ | |
'subString': "Gecko", | |
'identity': "Mozilla", | |
'versionSearch': "rv:" | |
}, | |
] | |
def process_request(self, request): | |
request.browser_name = None | |
request.browser_version = None | |
for b in self.data_browser: | |
if b['subString'] in request.META['HTTP_USER_AGENT']: | |
request.browser_name = b['identity'] | |
if b.has_key('versionSearch'): | |
f = re.compile(b['versionSearch']+'([0-9\.]+)',re.M) | |
m = f.search(request.META['HTTP_USER_AGENT']) | |
if m: | |
request.browser_version = m.group(1) | |
break; | |
def process_view(self, request, view_func, view_args, view_kwargs): | |
pass | |
def process_response(self, request, response): | |
return response | |
def process_exception(self, request, exception): | |
pass |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment