forked from pamelafox/meetupgator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
proxy.py
54 lines (44 loc) · 1.49 KB
/
proxy.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
47
48
49
50
51
52
53
54
#!/usr/bin/python2.7
#
# Copyright 2009 Google Inc.
# Licensed under the Apache License, Version 2.0:
# http://www.apache.org/licenses/LICENSE-2.0
import logging
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.api import urlfetch
from google.appengine.api import memcache
from django.utils import simplejson
class ProxyHandler(webapp.RequestHandler):
def get(self):
url = self.request.get('url')
logging.info(url)
# Check if the result is cached, fetch if not
json_str = memcache.get(url)
if not json_str:
logging.info('Fetching URL')
try:
result = urlfetch.fetch(url, deadline=10)
if result.status_code == 200:
json_str = result.content
logging.info('Caching')
memcache.set(url, json_str, 60)
else:
logging.info(result.status_code)
logging.info(result.content)
except:
logging.info('Error fetching URL')
# Output JSON result, and wrap in callback if provided
if json_str:
callback = self.request.get('callback')
self.response.headers['Content-Type'] = 'application/json'
if callback:
self.response.out.write(callback + '(' + json_str + ')')
else:
self.response.out.write(json_str)
def main():
application = webapp.WSGIApplication([(r'/proxy', ProxyHandler)],
debug=True)
run_wsgi_app(application)
if __name__ == '__main__':
main()