CoCalc Shared Fileswww / cgi-bin / mfd / Documents.pyOpen in CoCalc with one click!
Author: William A. Stein
1
__version__ = "$Revision: 1.4 $"[11:-4]
2
3
import HTML
4
import sys
5
from string import join
6
7
class Document:
8
9
generator = HTML.META(name="generator",
10
content="HyperText package (Python)")
11
DOCTYPE = HTML.DOCTYPE
12
body_element = HTML.BODY
13
14
def __init__(self, *content, **attrs):
15
from HTML import HEAD, HTML
16
self.doctype = self.DOCTYPE
17
self.body = apply(self.body_element, content, attrs)
18
self.head = HEAD(self.generator)
19
if hasattr(self, 'style'): self.head.append(self.style)
20
if hasattr(self, 'title'): self.head.append(self.title)
21
self.html = HTML(self.head, self.body)
22
self.setup()
23
24
def setup(self): pass
25
26
def append(self, *items): map(self.body.content.append, items)
27
28
def __str__(self, indent=0, perlevel=2):
29
return join([self.doctype.__str__(indent, perlevel),
30
self.html.__str__(indent, perlevel)], '')
31
32
def writeto(self, fp=sys.stdout, indent=0, perlevel=2):
33
self.doctype.writeto(fp, indent, perlevel)
34
self.html.writeto(fp, indent, perlevel)
35
36
37
class FramesetDocument(Document):
38
39
DOCTYPE = HTML.DOCTYPE_frameset
40
body_element = HTML.FRAMESET
41
42
43
class CGIMixIn:
44
45
def setup(self):
46
self.content_type = "text/html"
47
self.headers = []
48
self.nobody = 0
49
50
def _str_content_type(self):
51
return 'Content-Type: %s\r\n\r\n' % self.content_type
52
53
def __str__(self, indent=0, perlevel=2):
54
s = self.headers[:]
55
s.append(self._str_content_type())
56
if not self.nobody:
57
s.append(self.doctype.__str__(indent, perlevel))
58
s.append(self.html.__str__(indent, perlevel))
59
return join(s, '')
60
61
def writeto(self, fp=sys.stdout, indent=0, perlevel=2):
62
fp.writelines(self.headers)
63
fp.write(self._str_content_type())
64
if not self.nobody:
65
self.doctype.writeto(fp, indent, perlevel)
66
self.html.writeto(fp, indent, perlevel)
67
68
69
class HTTPMixIn(CGIMixIn):
70
71
def setup(self):
72
CGIMixIn.setup(self)
73
if not hasattr(self, 'response'):
74
self.response = (200, 'Output follows')
75
self.date = None
76
77
http_response_str = "%s %s %s\r\nServer: %s %s\r\nDate: %s\r\n"
78
79
def _str_http_response(self):
80
if hasattr(self, 'request'):
81
apply(self.request.log_request, self.response)
82
return self.http_response_str \
83
% (self.request.request_version,
84
self.response[0],
85
self.response[1],
86
self.request.server_version,
87
self.request.sys_version,
88
self.date)
89
else:
90
return self.http_response_str \
91
% ('HTTP/1.0',
92
self.response[0],
93
self.response[1],
94
"Dunno/0.0",
95
"BeatzMe/0.0",
96
self.date)
97
98
def __str__(self, indent=0, perlevel=2):
99
return join([self._str_http_response(),
100
CGIMixIn.__str__(self, indent, perlevel)], '')
101
102
def writeto(self, fp=sys.stdout, indent=0, perlevel=2):
103
fp.write(self._str_http_response())
104
CGIMixIn.writeto(self, fp, indent, perlevel)
105
106
107
108
109
110