How to Serve up Mobile and Desktop Versions of your Website in Flask: A Quickstart Guide to Detecting User-Agents with Python, Flask, & request

While it’s currently fashionable in web development to use front-end frameworks such as Bootstrap to create “responsive” websites which can transform themselves entirely client-side to fit either a Desktop or mobile phone screen, sometimes it’s just easier to serve up a mobile or desktop version of your website depending on the user’s device. In this quick blog post I wanted share a quick snippet of Python/Flask code which you can use to serve up desktop and mobile versions of your website. In my opinion, this often makes more sense than trying to build some kind of transformer website. The transformer concept is kind of cool, and is definitely slick, it’s quite tedious and your end users probably won’t notice all of the effort you put into your responsive design anyway.

So without further ado: How to Serve Up a Mobile Friendly Version of your Website in Python with Flask

from flask import Flask, Response, render_template, request
app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def index():
user_agent = request.headers.get('User-Agent')
user_agent = user_agent.lower()
# In your templates directory, create a mobile version of your site (mobile.index.html).
# Likewise, add your desired desktop template as well (desktop.index.html).
if "iphone" in user_agent:
return render_template('mobile.index.html')
elif "android" in user_agent:
return render_template('mobile.index.html')
return render_template('desktop.index.html')