Skip to content

Instantly share code, notes, and snippets.

@satyr
Created July 6, 2009 06:16
Show Gist options
  • Save satyr/141288 to your computer and use it in GitHub Desktop.
Save satyr/141288 to your computer and use it in GitHub Desktop.
# -*- encoding: utf-8 -*-
import wsgiref.handlers
from google.appengine.ext import webapp
#from google.appengine.api import urlfetch
class Form(webapp.RequestHandler):
def get(self):
self.response.out.write("""\
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<title>miscapis</title>
<h1>MiscAPIs</h1>
<h2>xpandurl</h2>
<form action="/xpandurl" method="get"><pre>
URL: <input name="url" size="80" >
callback: <input name="callback" size="20"><input type="submit"></pre></form>
<h2>webiconv</h2>
<form action="/webiconv" method="get"><pre>
URL: <input name="url" size="80">
charset: <input name="from" size="16"> -> <input name="to" size="16"
><input type="submit"></pre></form>
""")
class XpandURL(webapp.RequestHandler):
def get(self, path):
import urllib2, pprint
url = self.request.get('url') or urllib2.unquote(path)
clb = self.request.get('callback', None)
req = urllib2.Request(url)
req.get_method = lambda: 'HEAD'
loc = urllib2.urlopen(req).geturl().decode('utf-8')
if clb != None:
loc = clb +'("'+ (pprint.pformat("'"+ loc.replace('"', '\0'))
.replace(r'\x00', r'\"')[3:]) +')'
self.response.headers.add_header('Content-Type',
'text/plain;charset=utf-8')
self.response.out.write(loc)
class WebIConv(webapp.RequestHandler):
def get(self):
import urllib2
url = self.request.get('url', 'http://miscapis.appspot.com')
csf = self.request.get('from', '')
cst = self.request.get('to', '')
res = urllib2.urlopen(url)
body = res.read()
head = res.info()
if(body[0:3] == '\xef\xbb\xbf'): body = body[3:] # nuking BOM
mime = str((head['content-type'] or 'text/html') +'; charset='+ cst)
self.response.headers.add_header('Content-Type', mime)
self.response.out.write(body.decode(csf).encode(cst))
def main():
application = webapp.WSGIApplication([('/', Form),
(r'/webiconv|/iconvsite', WebIConv),
(r'/xpandurl/?(.*)', XpandURL)],
debug=True)
wsgiref.handlers.CGIHandler().run(application)
if __name__ == '__main__': main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment