megawac / cache secret
Last active

Embed URL

HTTPS clone URL

SSH clone URL

You can clone with HTTPS or SSH.

Download Gist

Twisted caching attempt

View cache
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
from wsgiref.handlers import format_date_time as format_date
from datetime import date, timedelta
from time import mktime
 
'''
Sets the cache headers for a (static resource) request
'''
def cache(request, expires=30, public=True):
#set expires header
expiry = (date.today() + timedelta(expires)).timetuple()
request.responseHeaders.setRawHeaders("expires" , [format_date(mktime(expiry))])
#set cache control
cache_control = "max-age=" + str(int(60*60*24*expires))
if public:
cache_control += ", public"
else:
cache_control += ", private"
request.responseHeaders.setRawHeaders("cache-control", [cache_control])
 
return request
View cache
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
from twisted.web import resource, server, static, error as http_error
import os
 
import qwebirc.util.qjson as json
from qwebirc.util.caching import cache
 
def getJSON(path):
with open(path) as file:
return json.loads(file.read())
 
#i18n engine
class LocalizationEngine(resource.Resource):
isLeaf = True
localePath = "static/lang/"
 
def __init__(self, prefix):
pass
 
def render_GET(self, request):
return self.getLocale(request)
 
def getLocale(self, request):
"""
Request a localization and respond with json object of appropriate locale
"""
requested = request.args.get("locale") #?locale=fr
setLocales = request.getCookie("locale") #preferred locale (todo implement)?
locales = []
if requested:
locales = requested
elif setLocales:
locales = json.loads(setLocales)
else:
lang_header = request.headers.get("Accept-Language", "en") # for example en-US,en;q=0.8,es;q=0.6
locales = [locale.split(';')[0] for locale in lang_header.split(',')]
 
basePath = self.localePath + (request.args.get("path", [""])[0])
if not basePath.endswith("/"):
basePath += "/"
 
if not os.path.exists(basePath):
raise http_error.NoResource().render(request)
 
lang = getJSON(basePath + "base.json")
 
# reverse so specificity overrides
for locale in reversed(locales):
path = basePath + locale + ".json"
if os.path.exists(path):
lang.update(getJSON(path))
 
cache(request)
# apply_gzip(request)
request.write(json.dumps(lang))
request.finish()
return True
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.