Skip to content

Instantly share code, notes, and snippets.

@megawac

megawac/cache Secret

Last active August 29, 2015 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save megawac/597e8827d4f57c6955fd to your computer and use it in GitHub Desktop.
Save megawac/597e8827d4f57c6955fd to your computer and use it in GitHub Desktop.
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 = (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
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