Create a gist now

Instantly share code, notes, and snippets.

@megawac /cache Secret
Last active Aug 29, 2015

What would you like to do?
Twisted caching attempt
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 = ( + 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"
cache_control += ", private"
request.responseHeaders.setRawHeaders("cache-control", [cache_control])
return request
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(
#i18n engine
class LocalizationEngine(resource.Resource):
isLeaf = True
localePath = "static/lang/"
def __init__(self, prefix):
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)
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):
# apply_gzip(request)
return True
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment