-
-
Save frankV/b7ab2e3abc75cc3644eb to your computer and use it in GitHub Desktop.
Example of caching API results w/ Flask-Restless and Flask-Cache
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import json | |
import hashlib | |
from flask import Flask, request | |
import flask.ext.sqlalchemy | |
import flask.ext.cache | |
import flask.ext.restless | |
from flask.ext.restless import ProcessingException | |
app = Flask(__name__) | |
app.config['DEBUG'] = True | |
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db' | |
app.config['CACHE_TYPE'] = 'redis' | |
app.config['CACHE_KEY_PREFIX'] = 'my_key' | |
db = flask.ext.sqlalchemy.SQLAlchemy(app) | |
cache = flask.ext.cache.Cache(app) | |
class Person(db.Model): | |
id = db.Column(db.Integer, primary_key=True) | |
db.create_all() | |
def get_cache_key(): | |
return hashlib.md5(request.path + request.query_string).hexdigest() | |
def cache_preprocessor(**kwargs): | |
key = get_cache_key() | |
if cache.get(key): | |
print('returning cached result') | |
raise ProcessingException(description=cache.get(key), code=200) | |
def cache_postprocessor(result, **kwargs): | |
cache.set(get_cache_key(), json.dumps(result)) | |
print('result cached.') | |
manager = flask.ext.restless.APIManager(app, flask_sqlalchemy_db=db) | |
manager.create_api(Person, | |
methods=['GET'], | |
preprocessors={'GET_MANY': [cache_preprocessor]}, | |
postprocessors={'GET_MANY': [cache_postprocessor]}) | |
app.run() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import requests | |
# first time is uncached: | |
print requests.get('http://localhost:5000/api/person').json() | |
# second time is cached: | |
print requests.get('http://localhost:5000/api/person').json() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment