-
Notifications
You must be signed in to change notification settings - Fork 4
/
main.py
executable file
·46 lines (40 loc) · 1.63 KB
/
main.py
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
from django.utils import simplejson
from google.appengine.api import memcache
from google.appengine.api import urlfetch
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util, template
def _request(url, cache_ttl=3600, force=False):
request_cache_key = 'request:%s' % url
failure_cache_key = 'failure:%s' % url
resp = memcache.get(request_cache_key)
if force or not resp:
try:
resp = simplejson.loads(urlfetch.fetch(url).content[11:-3])
memcache.set(request_cache_key, resp, cache_ttl)
memcache.set(failure_cache_key, resp, cache_ttl*10)
except (ValueError, urlfetch.DownloadError), e:
# Not valid JSON or request timeout
resp = memcache.get(failure_cache_key)
if not resp:
resp = {}
return resp
class MainHandler(webapp.RequestHandler):
def get(self):
self.response.out.write(template.render('templates/index.html', {}))
class ContentHandler(webapp.RequestHandler):
def get(self, page):
skip_cache = self.request.get('cache') == '0'
try:
page = _request('https://shdh.pbworks.com/api_v2/op/GetPage/page/%s' % page, force=skip_cache)
if page['folder'] != 'Website':
raise LookupError()
self.response.out.write(template.render('templates/content.html', locals()))
except LookupError:
self.error(404)
def main():
application = webapp.WSGIApplication([
('/', MainHandler),
('/(.+)', ContentHandler), ], debug=True)
util.run_wsgi_app(application)
if __name__ == '__main__':
main()