Added a redirection restart.
[wrw.git] / wrw / resp.py
1 import dispatch, proto
2
3 __all__ = ["skeleton", "skelfor", "setskel", "usererror"]
4
5 class skeleton(object):
6     def page(self, title, content):
7         return """<?xml version="1.0" ?>
8 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
9 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US">
10 <head>
11 %s
12 </head>
13 <body>
14 %s
15 </body>
16 </html>""" % (self.head(title), content)
17
18     def head(self, title):
19         return """<title>%s</title>\n%s""" % (title, self.style())
20
21     def style(self):
22         return ""
23
24     def error(self, message, detail):
25         return self.page(message, """<h1>%s</h1>\n<p>%s</p>\n""" % (message, detail))
26
27     def message(self, message, detail):
28         return self.page(message, """<h1>%s</h1>\n<p>%s</p>\n""" % (message, detail))
29
30 defskel = skeleton()
31
32 def getskel(req):
33     return [defskel]
34 def skelfor(req):
35     return req.item(getskel)[0]
36 def setskel(req, skel):
37     req.item(getskel)[0] = skel
38
39 class usererror(dispatch.restart):
40     def __init__(self, message, detail):
41         super(usererror, self).__init__()
42         self.message = message
43         self.detail = detail
44
45     def handle(self, req):
46         return [skelfor(req).error(self.message, self.detail)]
47
48 class message(dispatch.restart):
49     def __init__(self, message, detail):
50         super(message, self).__init__()
51         self.message = message
52         self.detail = detail
53
54     def handle(self, req):
55         return [skelfor(req).message(self.message, self.detail)]
56
57 class httperror(usererror):
58     def __init__(self, status, message = None, detail = None):
59         if message is None:
60             message = proto.statusinfo[status][0]
61         if detail is None:
62             detail = proto.statusinfo[status][1]
63         super(httperror, self).__init__(message, detail)
64         self.status = status
65
66     def handle(self, req):
67         req.status(self.status, self.message)
68         return super(httperror, self).handle(req)
69
70 class notfound(httperror):
71     def __init__(self):
72         return super(notfound, self).__init__(404)
73
74 class redirect(dispatch.restart):
75     def __init__(self, url, status = 303):
76         super(redirect, self).__init__()
77         self.url = url
78         self.status = status
79
80     def handle(self, req):
81         req.status(self.status, "Redirect")
82         req.ohead["Location"] = proto.appendurl(proto.requrl(req), self.url)
83         return []