Skip to content

Instantly share code, notes, and snippets.

@moriyoshi
Created May 11, 2010
Embed
What would you like to do?
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