Skip to content

Instantly share code, notes, and snippets.

@ofen
Last active December 28, 2021 13:20
Show Gist options
  • Save ofen/9a915585f1a1dda5e1282908a22b68e0 to your computer and use it in GitHub Desktop.
Save ofen/9a915585f1a1dda5e1282908a22b68e0 to your computer and use it in GitHub Desktop.
Simple cache middleware for Bottle
from bottle import route, run, response, request
import datetime
import json
import requests
# Cache middleware
def cache(callback, ttl=datetime.timedelta(hours=1)):
cache = {}
def wrapper(*args, **kwargs):
key = request.path
now = datetime.datetime.now()
if key not in cache or now - cache[key][0] > ttl:
value = callback(*args, **kwargs)
cache[key] = (now, value)
return cache[key][1]
return wrapper
# Basic usage
@route('/api/v1/get_data')
@cache
def get_remote_api(env):
response.content_type = 'application/json; charset=utf-8'
# Fetching heavy JSON from remote site
data = requests.get('https://example.com/very_heavy.json').json()
# Process you JSON
# ...
return json.dumps(data)
run(host='0.0.0.0', port=8080)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment