P
P
pcdesign2015-01-21 20:13:14
memcached
pcdesign, 2015-01-21 20:13:14

How to make friends in Flask two modules: Flask-Mobility and Flask-Cache?

Flask has two great modules:
Flask-Cache - caches by placing a rendered page in the memcache.
Flask-Mobility - Gives out a mobile version for mobile devices.

Here is the actual code:

from flask import Flask, render_template
from flask.ext.cache import Cache                                                
from flask.ext.mobility import Mobility                                          
from flask.ext.mobility.decorators import mobile_template   

app = Flask(__name__)                                                            
Mobility(app)  
cache = Cache(app, config={'CACHE_TYPE': 'memcached',                            
                          "CACHE_MEMCACHED_SERVERS": ['192.168.1.100:11211']})


@app.route('/')                                                                  
@cache.cached(50)                                                             
@mobile_template('{mobile/}index.html')     
def index(template):                                                             
    return render_template(template) 

if __name__ == '__main__':                                                       
    app.run()


Caches, but as he pleases.
Then the mobile version will be cached and returned to ordinary desktop browsers.
And then vice versa.

How to make it correctly cache two versions for both mobile and desktop?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Rostislav Grigoriev, 2015-01-21
@pcdesign

The decorator @cache.cacheddoesn't know anything about the decorator @mobile_template.
As one option, you can create your own function to generate a prefix for the key.

def mobile_key_prefix():
    return '%s/%s' % (is_mobile(request), request.path)

@cache.cached(timeout=50, key_prefix=mobile_key_prefix)

Here I have specified a function is_mobile(request)- it should return correspondingly different strings for mobile and for desktops. So the key will be different and the correct data will be displayed.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question