Skip to content

Instantly share code, notes, and snippets.

@hirusha-adi
Forked from thaiphuong5/detect.py
Last active April 28, 2023 09:28
Show Gist options
  • Save hirusha-adi/a3347503abef096555d2ce794bcde4e3 to your computer and use it in GitHub Desktop.
Save hirusha-adi/a3347503abef096555d2ce794bcde4e3 to your computer and use it in GitHub Desktop.
Flask browser detection

Check weather the user request is from a mobile phone or a computer and perform actions accordingly with flask and python3

from flask import request, render_template
import re

browser = request.user_agent.browser
version = request.user_agent.version and int(request.user_agent.version.split('.')[0])
platform = request.user_agent.platform
uas = request.user_agent.string

if browser and version:
    if (browser == 'msie' and version < 9) \
    or (browser == 'firefox' and version < 4) \
    or (platform == 'android' and browser == 'safari' and version < 534) \
    or (platform == 'iphone' and browser == 'safari' and version < 7000) \
    or ((platform == 'macos' or platform == 'windows') and browser == 'safari' and not re.search('Mobile', uas) and version < 534) \
    or (re.search('iPad', uas) and browser == 'safari' and version < 7000) \
    or (platform == 'windows' and re.search('Windows Phone OS', uas)) \
    or (browser == 'opera') \
    or (re.search('BlackBerry', uas)):
        return render_template('unsupported.html')

or simply

phones = ["iphone", "android", "blackberry"]
ua = request.headers.get("User-Agent").lower()
if any(phone in ua for phone in phones):
    ismobile = True
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment