Skip to main content

WSGI Middleware and web framework extensions for handling User-Agent. Thanks to woothee , UADetector supports various User-Agents. This library respects to k0kubun/rack-user_agent .

travis coveralls.io latest version license

Installation

$ pip install uadetector

Usage

WSGI middleware

This middleware provides a uadetector.useragent.UserAgent object to handling User-agents.

from wsgiref.simple_server import make_server

# import middleware
from uadetector import UADetector

def app(environ, start_response):
    start_response('200 OK', [('Content-Type', 'text/plain')])

    # get 'UserAgent' object from environ dict.
    ua = environ.get('uadetector.useragent')

    ua.user_agent       #=> "Mozilla/5.0 (Macintosh; ..."
    ua.device_type      #=> "pc"
    ua.os               #=> "Mac OSX"
    ua.browser          #=> "Chrome"
    ua.from_pc          #=> True
    ua.from_smartphone  #=> False

    return [ua.os.encode('utf-8')]

# Apply middleware
application = UADetector(app)

if __name__ == "__main__":
    with make_server('127.0.0.1', 8000, application) as server:
        print("Serving on port 8000...")
        server.serve_forever()

You can also replace the key of environ or the UserAgent class.

from uadetector.useragent import UserAgent

class MyUserAgent(UserAgent):
     # Write your custom codes.

# Apply middleware
application = UADetector(
   app,
   envorion_key='your.favorite.key'
   useragent_class='path.to.MyUserAgent'
)

See also WSGI example.

Web framework extensions

Some web frameworks provide a way to extend in a different way from WSGI Middleware. This library provide shortcuts according to that way.

Caution: I do not actively support individual frameworks. If you are worried, you should use WSGIMiddleware.

Django

You can use Django’s MIDDLEWARE.

# settings.py

MIDDLEWARE = [
   # Add UADetecorMiddleware
   'uadetector.django.middleware.UADetectorMiddleware',
   # ... omit ...
]
# views.py

def index_view(request):
    print(request.ua.from_smartphone) # => True or False
    # ... omit ...

Customize property name of request object and replace UserAgent class.

# settings.py

UADETECTOR_REQUEST_PROPERTY_NAME = 'agent' # => You can use "request.agent"
UADETECTOR_USERAGENT_CLASS = 'path.to.MyUserAgent'

See also Dajngo example.

Tips: Switch templates based on User-Agent (using django-variantmpl ).

Pyramid

You can use config.add_request_method.

from uadetector.pyramid import ua_prop


def index(request):
    print(request.ua.from_smartphone) # => True or False
    # ... omit ...


with Configurator() as config:
    config.add_route('index', '/')
    config.add_view(index, route_name='index')

    config.add_request_method(ua_prop(), name='ua', reify=True)
    # ... omit ...

Customize property name of request object and replace UserAgent class.

config.add_request_method(
    ua_prop('path.to.MyUserAgent'),
    name='agent',  # => You can use "request.agent"
    reify=True
)

See also Pyramid example.

Flask

You can use Flask Extension.

from flask import Flask, request
from uadetector.flask import UADetector

app = Flask(__name__)
UADetector(app)

@app.route('/')
def index():
    print(request.ua.from_smartphone) # => True or False
    # ... omit ...

Customize property name of request object and replace UserAgent class.

app = Flask(__name__)

app.config['UADETECTOR_USERAGENT_CLASS'] = 'path.to.MyUserAgent'
app.config['UADETECTOR_REQUEST_PROPERTY_NAME'] = 'agent' # => You can use "request.agent"

UADetector(app)

See also Flask example.

Tornado

You can use custom RequestHandler.

from uadetector.tornado.web import RequestHandler

class IndexHandler(RequestHandler):

    def get(self):
        print(self.request.ua.from_smartphone) # => True or False
        # ... omit ...

Customize property name of request object and replace UserAgent class.

from tornado.options import define
from uadetector.tornado.web import RequestHandler

define(
    'uadetector_request_property_name',
    default='agent', # => You can use "self.request.agent"
)
define(
    'uadetector_useragent_class',
    default='path.to.MyUserAgent'
)

class IndexHandler(RequestHandler):

See also Tornado example.

UserAgent

List of properties of uadetector.useragent.UserAgent object.

attrs

  • UserAgent.device_variant

  • UserAgent.device_type

  • UserAgent.os

  • UserAgent.os_version

  • UserAgent.browser

  • UserAgent.browser_version

  • UserAgent.browser_vendor

helpers

  • UserAgent.from_pc

  • UserAgent.from_smartphone

  • UserAgent.from_mobilephone

  • UserAgent.from_appliance

  • UserAgent.from_crawler

detectors

  • UserAgent.smartphone_version

  • UserAgent.from_iphone

  • UserAgent.from_ipad

  • UserAgent.from_ipod

  • UserAgent.from_android

  • UserAgent.from_android_tablet

  • UserAgent.from_windows_phone

  • UserAgent.from_ios

  • UserAgent.from_android_os

Tips

If you want a UserAgent object simply from the User-Agent string, Please use get_useruseragent.

from uadetector import get_useragent

ua_string = "Mozilla/5.0 (iPhone; CPU iPhone OS ..."

ua = get_useragent(ua_string)
us.from_smartphone # => True

# Use custom useragent class
ua = get_useragent(ua_string, useragent_class='path.to.MyUserAgent')

Support

Support latest 3 minor versions.

  • Python 3.4, 3.5, 3.6

  • Django 1.10, 1.11, 2.0

  • Pyramid 1.7, 1.8, 1.9

  • Flask 0.10, 0.11, 0.12

  • Tornado 4.5, 4.6, 4.7

License

MIT License

Authors

  • tell-k <ffk2005 at gmail.com>

History

0.1.3(Feb 20, 2018)

0.1.2(Feb 19, 2018)

  • First release

Metadata

Release files for uadetector 0.1.3

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for uadetector 0.1.3
File Size Uploaded
uadetector-0.1.3.tar.gz 16.3 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for uadetector 0.1.3
File Interpreter ABI Platform
uadetector-0.1.3-py3-none-any.whl Python 3 none any Details

Total release size: 29.4 kB

Release files / uadetector-0.1.3.tar.gz

Download URL uadetector-0.1.3.tar.gz
Size 16.3 kB
Tags Source
SHA-256 checksum
How to use checksums
90058ed9cde3da208ae37cf6781daf9dfbabebd6947d5549be83d91a5c687a0b
BLAKE2b-256 checksum
How to use checksums
36dc2a243a546e7b8e982f9a98cdaabc414c48853180c68039a4f5783feeb34f
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No

Release files / uadetector-0.1.3-py3-none-any.whl

Download URL uadetector-0.1.3-py3-none-any.whl
Size 13.1 kB
Tags Python 3
SHA-256 checksum
How to use checksums
ef127eaae91bdbed626563878890c18be3b65153ab3d648e1fd4d917848a7d2c
BLAKE2b-256 checksum
How to use checksums
54cfbc4833a8da4c8641a5414f5359352ef5e48af28f6848c95d0a55a906a175
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No

Release history Release notifications | RSS feed

This release

0.1.3 This release

2 release files

0.1.2

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page