Created
October 15, 2019 20:01
-
-
Save tbhaxor/560cfdf4cdfd5e6cd683b554b04ab4e8 to your computer and use it in GitHub Desktop.
Flask redis / memcaching in python
This file contains 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
from flask import Flask, jsonify | |
from requests import get as request | |
from flask_caching import Cache | |
BASE = """https://jsonplaceholder.typicode.com/users/{id}""" | |
# creating application | |
app = Flask(__name__) | |
conf = {'CACHE_TYPE': 'redis'} # or memcache | |
cache = Cache(app=app, config=conf) | |
# function to query db | |
def read_document(id: int) -> dict: | |
global BASE | |
resp = request(BASE.format(id=id)) | |
if resp.json(): | |
return (True, resp.json()) | |
return (False, resp.json()) | |
@app.route("/user/<int:id>") # implementing router | |
@cache.cached(timeout=30) # caching for 30 | |
def user(id): | |
status, body = read_document(id) | |
if not status: | |
return jsonify(success=False, message="Invalid ID"), 404 | |
return jsonify(body) | |
app.debug = True | |
app.run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment