2008-02-21 07:06:33 -05:00
|
|
|
#!/usr/bin/env python
|
|
|
|
"""
|
|
|
|
web.py - Web Facilities
|
|
|
|
Author: Sean B. Palmer, inamidst.com
|
|
|
|
About: http://inamidst.com/phenny/
|
|
|
|
"""
|
|
|
|
|
2010-11-06 08:52:35 -04:00
|
|
|
import re, urllib
|
|
|
|
from htmlentitydefs import name2codepoint
|
2008-02-21 07:06:33 -05:00
|
|
|
|
|
|
|
class Grab(urllib.URLopener):
|
|
|
|
def __init__(self, *args):
|
|
|
|
self.version = 'Mozilla/5.0 (Phenny)'
|
|
|
|
urllib.URLopener.__init__(self, *args)
|
|
|
|
def http_error_default(self, url, fp, errcode, errmsg, headers):
|
|
|
|
return urllib.addinfourl(fp, [headers, errcode], "http:" + url)
|
|
|
|
urllib._urlopener = Grab()
|
|
|
|
|
|
|
|
def get(uri):
|
2008-09-11 12:18:44 -04:00
|
|
|
if not uri.startswith('http'):
|
|
|
|
return
|
2008-02-21 07:06:33 -05:00
|
|
|
u = urllib.urlopen(uri)
|
|
|
|
bytes = u.read()
|
|
|
|
u.close()
|
|
|
|
return bytes
|
|
|
|
|
|
|
|
def head(uri):
|
2008-09-11 12:18:44 -04:00
|
|
|
if not uri.startswith('http'):
|
|
|
|
return
|
2008-02-21 07:06:33 -05:00
|
|
|
u = urllib.urlopen(uri)
|
|
|
|
info = u.info()
|
|
|
|
u.close()
|
|
|
|
return info
|
|
|
|
|
|
|
|
def post(uri, query):
|
2008-09-11 12:18:44 -04:00
|
|
|
if not uri.startswith('http'):
|
|
|
|
return
|
2008-02-21 07:06:33 -05:00
|
|
|
data = urllib.urlencode(query)
|
|
|
|
u = urllib.urlopen(uri, data)
|
|
|
|
bytes = u.read()
|
|
|
|
u.close()
|
|
|
|
return bytes
|
|
|
|
|
2010-11-06 08:52:35 -04:00
|
|
|
r_entity = re.compile(r'&([^;\s]+);')
|
|
|
|
|
|
|
|
def entity(match):
|
|
|
|
value = match.group(1).lower()
|
|
|
|
if value.startswith('#x'):
|
|
|
|
return unichr(int(value[2:], 16))
|
|
|
|
elif value.startswith('#'):
|
|
|
|
return unichr(int(value[1:]))
|
|
|
|
elif name2codepoint.has_key(value):
|
|
|
|
return unichr(name2codepoint[value])
|
|
|
|
return '[' + value + ']'
|
|
|
|
|
|
|
|
def decode(html):
|
|
|
|
return r_entity.sub(entity, html)
|
|
|
|
|
2010-11-13 06:55:04 -05:00
|
|
|
r_string = re.compile(r'("(\\.|[^"\\])*")')
|
|
|
|
r_json = re.compile(r'^[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]+$')
|
|
|
|
env = {'__builtins__': None, 'null': None, 'true': True, 'false': False}
|
|
|
|
|
|
|
|
def json(text):
|
|
|
|
"""Evaluate JSON text safely (we hope)."""
|
|
|
|
if r_json.match(r_string.sub('', text)):
|
|
|
|
text = r_string.sub(lambda m: 'u' + m.group(1), text)
|
|
|
|
return eval(text.strip(' \t\r\n'), env, {})
|
|
|
|
raise ValueError('Input must be serialised JSON.')
|
|
|
|
|
2008-02-21 07:06:33 -05:00
|
|
|
if __name__=="__main__":
|
|
|
|
main()
|