Merge branch 'master' into python3
[wrw.git] / wrw / resp.py
CommitLineData
3614ca83 1from . import dispatch, proto, env
dc7e5d54
FT
2
3__all__ = ["skeleton", "skelfor", "setskel", "usererror"]
4
5class 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
c3b08e88 18 def head(self, title):
dc7e5d54
FT
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
1f61bf31 30defskel = env.var(skeleton())
dc7e5d54
FT
31
32def getskel(req):
1f61bf31 33 return [defskel.val]
dc7e5d54
FT
34def skelfor(req):
35 return req.item(getskel)[0]
36def setskel(req, skel):
37 req.item(getskel)[0] = skel
38
39class usererror(dispatch.restart):
40 def __init__(self, message, detail):
c33f2d6c 41 super().__init__()
dc7e5d54
FT
42 self.message = message
43 self.detail = detail
44
45 def handle(self, req):
46 return [skelfor(req).error(self.message, self.detail)]
47
48class message(dispatch.restart):
49 def __init__(self, message, detail):
c33f2d6c 50 super().__init__()
dc7e5d54
FT
51 self.message = message
52 self.detail = detail
53
54 def handle(self, req):
55 return [skelfor(req).message(self.message, self.detail)]
56
57class 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]
c33f2d6c 63 super().__init__(message, detail)
dc7e5d54
FT
64 self.status = status
65
66 def handle(self, req):
67 req.status(self.status, self.message)
c33f2d6c 68 return super().handle(req)
dc7e5d54
FT
69
70class notfound(httperror):
71 def __init__(self):
c33f2d6c 72 return super().__init__(404)
4bd573f9
FT
73
74class redirect(dispatch.restart):
75 def __init__(self, url, status = 303):
c33f2d6c 76 super().__init__()
4bd573f9
FT
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 []