Bootstrap FreeKB - Flask - Determine if Mobile Device using Flask-Mobility
Flask - Determine if Mobile Device using Flask-Mobility

Updated:   |  Flask articles

Flask uses the MVC (Model View Controller) Framework. Just to make this as obvious as possible, I like my Flask apps to have the following.

  • Model -> models.py
  • View -> views.py
  • Controller -> __init__.py

Let's say your Flask app has the following files.

├── main.py
├── database (directory)
│   ├── example.db
├── my-project (directory)
│   ├── __init__.py
│   ├── views.py
│   ├── models.py
│   ├── templates (directory)
│   │   ├── base.html
│   │   ├── home.html
│   │   ├── results.html
│   └── static (directory)
│       └── custom.css

 

Flask-Mobility can be used to determine if users requesting your Flask application are on a Mobile device. First, use the pip install command to install the Flask-Mobility package.

pip install Flask-Mobility

 

Or, you can specify the version to install

pip install Flask-Mobility==1.1.0

 

Or, better yet, use a requirements.txt file.

Flask-Mobility==1.1.0

 

And then install the packages using the requirements.txt file.

pip install --requirement requirements.txt

 

In your view (views.py in this example), use from flask_mobility import Mobility to import Flask-Mobility.

from flask import Blueprint, render_template
from flask_mobility import Mobility

views = Blueprint('views', __name__)

@views.route('/')
def home():
    return render_template('home.html')

 

And here is how you can do something base on whether or not a user is on a Mobile device.

{% if request.MOBILE %}
  <p>I'm happy to see you are using a Mobile device</p>
{% else %}
  <p>Got an old school user here</p>
{% endif %}

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter a62371 in the box below so that we can be sure you are a human.