Added a proto module with basic utilities without higher dependencies.
[wrw.git] / wrw / proto.py
1 statusinfo = {
2     400: ("Bad Request", "Your issued HTTP request is invalid."),
3     403: ("Forbidden", "You are not authorized to view the requested resource."),
4     404: ("Not Found", "The requested resource was not found."),
5     500: ("Server Error", "An internal error occurred.")
6     }
7
8 def httpdate(ts):
9     return time.strftime("%a, %d %b %Y %H:%M:%S +0000", time.gmtime(ts))
10
11 def phttpdate(dstr):
12     tz = dstr[-6:]
13     dstr = dstr[:-6]
14     if tz[0] != " " or (tz[1] != "+" and tz[1] != "-") or not tz[2:].isdigit():
15         return None
16     tz = int(tz[1:])
17     tz = (((tz / 100) * 60) + (tz % 100)) * 60
18     return time.mktime(time.strptime(dstr, "%a, %d %b %Y %H:%M:%S")) - tz - time.altzone
19
20 def htmlq(html):
21     ret = ""
22     for c in html:
23         if c == "&":
24             ret += "&"
25         elif c == "<":
26             ret += "&lt;"
27         elif c == ">":
28             ret += "&gt;"
29         else:
30             ret += c
31     return ret
32
33 def urlq(url):
34     ret = ""
35     for c in url:
36         if c == "&" or c == "=" or c == "#" or c == "?" or c == "/" or (ord(c) <= 32):
37             ret += "%%%02X" % ord(c)
38         else:
39             ret += c
40     return ret
41
42 def parstring(pars = {}, **augment):
43     buf = ""
44     for key in pars:
45         if key in augment:
46             val = augment[key]
47             del augment[key]
48         else:
49             val = pars[key]
50         if buf != "": buf += "&"
51         buf += urlq(key) + "=" + urlq(str(val))
52     for key in augment:
53         if buf != "": buf += "&"
54         buf += urlq(key) + "=" + urlq(str(augment[key]))
55     return buf