This repository has been archived by the owner on Oct 3, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdemo.py
198 lines (178 loc) · 5.98 KB
/
demo.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
# from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from builtins import *
from future import standard_library
standard_library.install_aliases()
import re
import ssl
import sys
# import logging
# hnOUT = logging.StreamHandler(sys.stdout)
# pkglogger = logging.getLogger('mixnmatchttp')
# pkglogger.addHandler(hnOUT)
# pkglogger.setLevel(logging.DEBUG)
from http.server import HTTPServer
from mixnmatchttp.servers import ThreadingHTTPServer
from mixnmatchttp import endpoints
from mixnmatchttp.handlers import BaseHTTPRequestHandler, \
methodhandler
from mixnmatchttp.utils import DictNoClobber
class MyHandler(BaseHTTPRequestHandler):
_endpoints = endpoints.Endpoint(
foobar={}, # will use do_default handler
refreshme={
'$nargs': endpoints.ARGS_OPTIONAL,
},
parameter={
# this way /parameter will raise "missing arg"
'$nargs': 1,
# this way /parameter will be treated by the GET handler
# '$disabled': True,
'*': {
'$nargs': 1,
'special': {}, # will use do_parameter__special
},
},
debug={
# these are for when /debug is called
'$allowed_methods': {'GET', 'POST'},
'sub': { # will use do_*debug handler
# these are for when /debug/sub is called
'$nargs': endpoints.ARGS_ANY,
'$raw_args': True, # don't canonicalize rest of path
},
'*': {
'debug': {
'*': {
'$varname': 'debug2'
},
},
},
},
)
_template_pages = DictNoClobber(
simpletxt={
'data': '$CONTENT',
'type': 'text/html'
},
simplehtml={
'data': '''
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
$HEAD
<title>$TITLE</title>
</head>
<body>
$BODY
</body>
</html>
''',
'type': 'text/html'
},
)
_templates = DictNoClobber(
refresh={
'fields': {
'HEAD': ('<meta http-equiv="refresh" '
'content="${interval}">'),
'TITLE': 'Example',
'BODY': ('<h1>Example page, will refresh every '
'${interval}s.</h1>'),
},
'page': 'simplehtml',
},
debug={
'fields': {
'CONTENT': ('${info}You called endpoint $root, sub = '
'$sub, args = $args, params = $params'),
},
'page': 'simpletxt',
},
)
def do_refreshme(self):
interval = self.ep.args
if not interval:
interval = '30'
'''Handler for the endpoint /refreshme'''
page = self.page_from_template(self.templates['refresh'],
{'interval': interval})
self.render(page)
def do_parameter(self):
self.render({
'data': (
'{} = {}'.format(self.ep.params['parameter'],
self.ep.args)
).encode('utf-8'),
'type': 'text/plain'})
def do_parameter_special(self):
self.render({'data': b'A very special parameter!',
'type': 'text/plain'})
def do_debug(self):
'''Handler for non-POST to the endpoint /debug'''
# set a header just for this request
self.save_header('X-Debug', 'Foo')
page = self.page_from_template(
self.templates['debug'],
{'info': '', 'root': self.ep.root, 'sub': self.ep.sub,
'args': self.ep.args, 'params': self.ep.params})
self.render(page)
def do_POST_debug(self):
'''Handler for POST to the endpoint /debug'''
# set a header just for this request
self.save_header('X-Debug', 'Foo')
page = self.page_from_template(
self.templates['debug'],
{'info': 'POST! ',
'root': self.ep.root, 'sub': self.ep.sub,
'args': self.ep.args, 'params': self.ep.params})
self.render(page)
def do_default(self):
'''Default endpoints handler'''
page = self.page_from_template(
self.templates['debug'],
{'info': 'This is do_default. ',
'root': self.ep.root, 'sub': self.ep.sub,
'args': self.ep.args, 'params': self.ep.params})
self.render(page)
# Don't forget this decorator!
@methodhandler
def do_GET(self):
# Do something here, then call parent's undecorated method
super().do_GET.__wrapped__()
def denied(self):
'''Deny access to /forbidden'''
if re.match('^/forbidden(/|$)', self.pathname):
# return args are passed to
# BaseHTTPRequestHandler.send_error in that order; both
# messages are optional
return (403, None, 'Access denied')
return super().denied()
def no_cache(self):
'''Only allow caching of scripts'''
return (not self.pathname.endswith('.js')) or super().no_cache()
def send_custom_headers(self):
'''Send our custom headers'''
self.send_header('X-Foo', 'Foobar')
if __name__ == '__main__':
use_SSL = False
keyfile = '' # path to PEM key, if use_SSL is True
certfile = '' # path to PEM certificate, if use_SSL is True
srv_cls = HTTPServer
# srv_cls = ThreadingHTTPServer # if using multi-threading
address = '127.0.0.1'
port = 58080
httpd = srv_cls((address, port), MyHandler)
if use_SSL:
httpd.socket = ssl.wrap_socket(
httpd.socket,
keyfile=keyfile,
certfile=certfile,
server_side=True)
try:
httpd.serve_forever()
except KeyboardInterrupt:
httpd.server_close()