Flask automatically switches template directories between PC and mobile

Requirements

I want the UserAgent to determine whether it is a PC or a smartphone and switch the root directory of the template without permission.

For example, prepare a template like this,

template/ja/pc/index.html
template/ja/sp/index.html
template/ja/fp/index.html

In view, I want to do this without being aware of the device. I want you to see the pc or sp automatically.

return render_template('index.html', form=form)

How are you guys doing

I searched for Flask snippets, but couldn't find a general solution. Please let me know if you have one.

There was an extension called Flask-Mobility, but this is a bit painful because I have to add decorators one by one. If that's the Python style, I wonder if that's the case ... After that, it seems that it is impossible to divide 3 or more such as PC, smartphone, feature phone. http://flask-mobility.readthedocs.org/en/latest/

Tried to make it

I tried Flask Extension to have something like this. I mean, it was a year ago when I made it.

You can use either Python 2 series or 3 series.

https://github.com/yasunori/flask-devices

Installation is done with pip.

pip install Flask-Devices

You can define any device group name, UserAgent regular expression, and corresponding template directory like this.

devices = Devices(app)
devices.add_pattern('mobile', 'iPhone|iPod|Android.*Mobile|Windows.*Phone|dream|blackberry|CUPCAKE|webOS|incognito|webmate', 'templates/sp')
devices.add_pattern('tablet', 'iPad|Android', 'templates/pc')
devices.add_pattern('hoge', 'hoge', 'templates/hoge')
devices.add_pattern('pc', '.*', 'templates/pc')

You only have to define this once and it will do the rest. The device to match is evaluated from top to bottom.

After that, you can get the device name on View or template, so you can use it when you change the process.

@app.route("/", methods=['GET', 'POST'])
def index():
    print(request.DEVICE) # mobile, tablet, hoge, pc
    if request.DEVICE == 'pc':
        # pc
    elif request.DEVICE == 'tablet':
        # tablet
{% if request.DEVICE == 'mobile' %}<strong>It's mobile now.<a href="">Do you want to see the PC version?</a></strong>{% endif %}

I personally use it conveniently.

As a caveat, when using from uWSGI Emperor etc., it may be necessary to specify the template directory with an absolute path.

That's it.

Recommended Posts

Flask automatically switches template directories between PC and mobile
Connection between flask and sqlite3
Differences between Windows and Linux directories
speed difference between wsgi, Bottle and Flask