Created
October 15, 2019 19:41
-
-
Save tbhaxor/57d74a238e4546bcf4c5ac77681259e7 to your computer and use it in GitHub Desktop.
LRU Caching 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 functools import lru_cache | |
BASE = """https://jsonplaceholder.typicode.com/users/{id}""" | |
# creating application | |
app = Flask(__name__) | |
# 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 | |
@lru_cache() # implementing the lru cache | |
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