Skip to content

Instantly share code, notes, and snippets.

@moriyoshi
Created May 11, 2010 10:13
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 moriyoshi/397149 to your computer and use it in GitHub Desktop.
Save moriyoshi/397149 to your computer and use it in GitHub Desktop.
application: to-data-uri
version: 0
runtime: python
api_version: 1
handlers:
- url: /.*
script: handler.py
from google.appengine.ext.webapp import WSGIApplication, RequestHandler
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.api.urlfetch import fetch
from base64 import b64encode
import re
def json_literal_escape(str):
retval = ""
for c in str:
c = ord(c)
if c == 34:
retval += "\\\""
elif c == 92:
retval += "\\\\"
elif c == 8:
retval += "\\b";
elif c == 9:
retval += "\\t";
elif c == 10:
retval += "\\n";
elif c == 11:
retval += "\\v";
elif c == 12:
retval += "\\f";
elif c == 13:
retval += "\\r";
elif c < 32:
retval += "\\u%04x" % c;
else:
retval += unichr(c)
return retval
def extract_mime_type(ct_header):
return re.sub("\s*;.*", "", ct_header)
class Default(RequestHandler):
def get(self):
url = self.request.get("url")
callback = self.request.get("callback")
try:
if callback == "":
raise Exception("callback is not given")
data = fetch(url, follow_redirects=True, deadline=2)
self.response.headers["Content-Type"] = "text/javascript"
self.response.out.write(u"%s({\"result\":\"%s\"})" % (
callback,
json_literal_escape(
u"data:%s;base64,%s" % (
extract_mime_type(data.headers["Content-Type"]),
b64encode(data.content)))))
except Exception, e:
self.response.set_status(500)
self.response.headers["Content-Type"] = "text/plain"
self.response.out.write(u"error: " + str(e))
if __name__ == "__main__":
run_wsgi_app(WSGIApplication([("/", Default)]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment