mozhttpd 0.7.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
mozhttpd/__init__.py ADDED
@@ -0,0 +1,48 @@
1
+ # This Source Code Form is subject to the terms of the Mozilla Public
2
+ # License, v. 2.0. If a copy of the MPL was not distributed with this file,
3
+ # You can obtain one at http://mozilla.org/MPL/2.0/.
4
+
5
+ """
6
+ Mozhttpd is a simple http webserver written in python, designed expressly
7
+ for use in automated testing scenarios. It is designed to both serve static
8
+ content and provide simple web services.
9
+
10
+ The server is based on python standard library modules such as
11
+ SimpleHttpServer, urlparse, etc. The ThreadingMixIn is used to
12
+ serve each request on a discrete thread.
13
+
14
+ Some existing uses of mozhttpd include Peptest_, Eideticker_, and Talos_.
15
+
16
+ .. _Peptest: https://github.com/mozilla/peptest/
17
+
18
+ .. _Eideticker: https://github.com/mozilla/eideticker/
19
+
20
+ .. _Talos: http://hg.mozilla.org/build/
21
+
22
+ The following simple example creates a basic HTTP server which serves
23
+ content from the current directory, defines a single API endpoint
24
+ `/api/resource/<resourceid>` and then serves requests indefinitely:
25
+
26
+ ::
27
+
28
+ import mozhttpd
29
+
30
+ @mozhttpd.handlers.json_response
31
+ def resource_get(request, objid):
32
+ return (200, { 'id': objid,
33
+ 'query': request.query })
34
+
35
+
36
+ httpd = mozhttpd.MozHttpd(port=8080, docroot='.',
37
+ urlhandlers = [ { 'method': 'GET',
38
+ 'path': '/api/resources/([^/]+)/?',
39
+ 'function': resource_get } ])
40
+ print "Serving '%s' at %s:%s" % (httpd.docroot, httpd.host, httpd.port)
41
+ httpd.start(block=True)
42
+
43
+ """
44
+
45
+ from .handlers import json_response
46
+ from .mozhttpd import MozHttpd, Request, RequestHandler, main
47
+
48
+ __all__ = ["MozHttpd", "Request", "RequestHandler", "main", "json_response"]
mozhttpd/handlers.py ADDED
@@ -0,0 +1,20 @@
1
+ # This Source Code Form is subject to the terms of the Mozilla Public
2
+ # License, v. 2.0. If a copy of the MPL was not distributed with this file,
3
+ # You can obtain one at http://mozilla.org/MPL/2.0/.
4
+
5
+ import json
6
+
7
+
8
+ def json_response(func):
9
+ """Translates results of 'func' into a JSON response."""
10
+
11
+ def wrap(*a, **kw):
12
+ (code, data) = func(*a, **kw)
13
+ json_data = json.dumps(data)
14
+ return (
15
+ code,
16
+ {"Content-type": "application/json", "Content-Length": len(json_data)},
17
+ json_data,
18
+ )
19
+
20
+ return wrap
mozhttpd/mozhttpd.py ADDED
@@ -0,0 +1,352 @@
1
+ #!/usr/bin/env python
2
+
3
+ # This Source Code Form is subject to the terms of the Mozilla Public
4
+ # License, v. 2.0. If a copy of the MPL was not distributed with this file,
5
+ # You can obtain one at http://mozilla.org/MPL/2.0/.
6
+
7
+ import errno
8
+ import logging
9
+ import os
10
+ import posixpath
11
+ import re
12
+ import socket
13
+ import sys
14
+ import threading
15
+ import time
16
+ import traceback
17
+ from argparse import ArgumentDefaultsHelpFormatter, ArgumentParser
18
+ from http.server import HTTPServer, SimpleHTTPRequestHandler
19
+ from socketserver import ThreadingMixIn
20
+ from urllib.parse import unquote, urlsplit
21
+
22
+ import moznetwork
23
+
24
+
25
+ class EasyServer(ThreadingMixIn, HTTPServer):
26
+ allow_reuse_address = True
27
+ acceptable_errors = (errno.EPIPE, errno.ECONNABORTED)
28
+
29
+ def handle_error(self, request, client_address):
30
+ error = sys.exc_info()[1]
31
+
32
+ if (
33
+ isinstance(error, socket.error)
34
+ and isinstance(error.args, tuple)
35
+ and error.args[0] in self.acceptable_errors
36
+ ) or (isinstance(error, IOError) and error.errno in self.acceptable_errors):
37
+ pass # remote hang up before the result is sent
38
+ else:
39
+ logging.error(error)
40
+ # The error can be ambiguous just the short description is logged, so we
41
+ # dump a stack trace to discover its origin.
42
+ traceback.print_exc()
43
+
44
+
45
+ class Request:
46
+ """Details of a request."""
47
+
48
+ # attributes from urlsplit that this class also sets
49
+ uri_attrs = ("scheme", "netloc", "path", "query", "fragment")
50
+
51
+ def __init__(self, uri, headers, rfile=None):
52
+ self.uri = uri
53
+ self.headers = headers
54
+ parsed = urlsplit(uri)
55
+ for i, attr in enumerate(self.uri_attrs):
56
+ setattr(self, attr, parsed[i])
57
+ try:
58
+ body_len = int(self.headers.get("Content-length", 0))
59
+ except ValueError:
60
+ body_len = 0
61
+ if body_len and rfile:
62
+ self.body = rfile.read(body_len)
63
+ else:
64
+ self.body = None
65
+
66
+
67
+ class RequestHandler(SimpleHTTPRequestHandler):
68
+ docroot = os.getcwd() # current working directory at time of import
69
+ proxy_host_dirs = False
70
+ request_log = []
71
+ log_requests = False
72
+ request = None
73
+
74
+ def __init__(self, *args, **kwargs):
75
+ SimpleHTTPRequestHandler.__init__(self, *args, **kwargs)
76
+ self.extensions_map[".svg"] = "image/svg+xml"
77
+
78
+ def _try_handler(self, method):
79
+ if self.log_requests:
80
+ self.request_log.append({
81
+ "method": method,
82
+ "path": self.request.path,
83
+ "time": time.time(),
84
+ })
85
+
86
+ handlers = [
87
+ handler for handler in self.urlhandlers if handler["method"] == method
88
+ ]
89
+ for handler in handlers:
90
+ m = re.match(handler["path"], self.request.path)
91
+ if m:
92
+ (response_code, headerdict, data) = handler["function"](
93
+ self.request, *m.groups()
94
+ )
95
+ self.send_response(response_code)
96
+ for keyword, value in headerdict.items():
97
+ self.send_header(keyword, value)
98
+ self.end_headers()
99
+ if isinstance(data, str):
100
+ data = data.encode()
101
+ self.wfile.write(data)
102
+
103
+ return True
104
+
105
+ return False
106
+
107
+ def _find_path(self):
108
+ """Find the on-disk path to serve this request from,
109
+ using self.path_mappings and self.docroot.
110
+ Return (url_path, disk_path)."""
111
+ path_components = list(filter(None, self.request.path.split("/")))
112
+ for prefix, disk_path in self.path_mappings.items():
113
+ prefix_components = list(filter(None, prefix.split("/")))
114
+ if len(path_components) < len(prefix_components):
115
+ continue
116
+ if path_components[: len(prefix_components)] == prefix_components:
117
+ return ("/".join(path_components[len(prefix_components) :]), disk_path)
118
+ if self.docroot:
119
+ return self.request.path, self.docroot
120
+ return None
121
+
122
+ def parse_request(self):
123
+ retval = SimpleHTTPRequestHandler.parse_request(self)
124
+ self.request = Request(self.path, self.headers, self.rfile)
125
+ return retval
126
+
127
+ def do_GET(self):
128
+ if not self._try_handler("GET"):
129
+ res = self._find_path()
130
+ if res:
131
+ self.path, self.disk_root = res
132
+ # don't include query string and fragment, and prepend
133
+ # host directory if required.
134
+ if self.request.netloc and self.proxy_host_dirs:
135
+ self.path = "/" + self.request.netloc + self.path
136
+ SimpleHTTPRequestHandler.do_GET(self)
137
+ else:
138
+ self.send_response(404)
139
+ self.end_headers()
140
+ self.wfile.write(b"")
141
+
142
+ def do_POST(self):
143
+ # if we don't have a match, we always fall through to 404 (this may
144
+ # not be "technically" correct if we have a local file at the same
145
+ # path as the resource but... meh)
146
+ if not self._try_handler("POST"):
147
+ self.send_response(404)
148
+ self.end_headers()
149
+ self.wfile.write(b"")
150
+
151
+ def do_DEL(self):
152
+ # if we don't have a match, we always fall through to 404 (this may
153
+ # not be "technically" correct if we have a local file at the same
154
+ # path as the resource but... meh)
155
+ if not self._try_handler("DEL"):
156
+ self.send_response(404)
157
+ self.end_headers()
158
+ self.wfile.write(b"")
159
+
160
+ def translate_path(self, path):
161
+ # this is taken from SimpleHTTPRequestHandler.translate_path(),
162
+ # except we serve from self.docroot instead of os.getcwd(), and
163
+ # parse_request()/do_GET() have already stripped the query string and
164
+ # fragment and mangled the path for proxying, if required.
165
+ path = posixpath.normpath(unquote(self.path))
166
+ words = path.split("/")
167
+ words = list(filter(None, words))
168
+ path = self.disk_root
169
+ for word in words:
170
+ drive, word = os.path.splitdrive(word)
171
+ head, word = os.path.split(word)
172
+ if word in (os.curdir, os.pardir):
173
+ continue
174
+ path = os.path.join(path, word)
175
+ return path
176
+
177
+ # I found on my local network that calls to this were timing out
178
+ # I believe all of these calls are from log_message
179
+ def address_string(self):
180
+ return "a.b.c.d"
181
+
182
+ # This produces a LOT of noise
183
+ def log_message(self, format, *args):
184
+ pass
185
+
186
+
187
+ class MozHttpd:
188
+ """
189
+ :param host: Host from which to serve (default 127.0.0.1)
190
+ :param port: Port from which to serve (default 8888)
191
+ :param docroot: Server root (default os.getcwd())
192
+ :param urlhandlers: Handlers to specify behavior against method and path match (default None)
193
+ :param path_mappings: A dict mapping URL prefixes to additional on-disk paths.
194
+ :param proxy_host_dirs: Toggle proxy behavior (default False)
195
+ :param log_requests: Toggle logging behavior (default False)
196
+
197
+ Very basic HTTP server class. Takes a docroot (path on the filesystem)
198
+ and a set of urlhandler dictionaries of the form:
199
+
200
+ ::
201
+
202
+ {
203
+ 'method': HTTP method (string): GET, POST, or DEL,
204
+ 'path': PATH_INFO (regular expression string),
205
+ 'function': function of form fn(arg1, arg2, arg3, ..., request)
206
+ }
207
+
208
+ and serves HTTP. For each request, MozHttpd will either return a file
209
+ off the docroot, or dispatch to a handler function (if both path and
210
+ method match).
211
+
212
+ Note that one of docroot or urlhandlers may be None (in which case no
213
+ local files or handlers, respectively, will be used). If both docroot or
214
+ urlhandlers are None then MozHttpd will default to serving just the local
215
+ directory.
216
+
217
+ MozHttpd also handles proxy requests (i.e. with a full URI on the request
218
+ line). By default files are served from docroot according to the request
219
+ URI's path component, but if proxy_host_dirs is True, files are served
220
+ from <self.docroot>/<host>/.
221
+
222
+ For example, the request "GET http://foo.bar/dir/file.html" would
223
+ (assuming no handlers match) serve <docroot>/dir/file.html if
224
+ proxy_host_dirs is False, or <docroot>/foo.bar/dir/file.html if it is
225
+ True.
226
+ """
227
+
228
+ def __init__(
229
+ self,
230
+ host="127.0.0.1",
231
+ port=0,
232
+ docroot=None,
233
+ urlhandlers=None,
234
+ path_mappings=None,
235
+ proxy_host_dirs=False,
236
+ log_requests=False,
237
+ ):
238
+ self.host = host
239
+ self.port = int(port)
240
+ self.docroot = docroot
241
+ if not (urlhandlers or docroot or path_mappings):
242
+ self.docroot = os.getcwd()
243
+ self.proxy_host_dirs = proxy_host_dirs
244
+ self.httpd = None
245
+ self.urlhandlers = urlhandlers or []
246
+ self.path_mappings = path_mappings or {}
247
+ self.log_requests = log_requests
248
+ self.request_log = []
249
+
250
+ class RequestHandlerInstance(RequestHandler):
251
+ docroot = self.docroot
252
+ urlhandlers = self.urlhandlers
253
+ path_mappings = self.path_mappings
254
+ proxy_host_dirs = self.proxy_host_dirs
255
+ request_log = self.request_log
256
+ log_requests = self.log_requests
257
+
258
+ self.handler_class = RequestHandlerInstance
259
+
260
+ def start(self, block=False):
261
+ """
262
+ Starts the server.
263
+
264
+ If `block` is True, the call will not return. If `block` is False, the
265
+ server will be started on a separate thread that can be terminated by
266
+ a call to stop().
267
+ """
268
+ self.httpd = EasyServer((self.host, self.port), self.handler_class)
269
+ if block:
270
+ self.httpd.serve_forever()
271
+ else:
272
+ self.server = threading.Thread(target=self.httpd.serve_forever)
273
+ self.server.setDaemon(True) # don't hang on exit
274
+ self.server.start()
275
+
276
+ def stop(self):
277
+ """
278
+ Stops the server.
279
+
280
+ If the server is not running, this method has no effect.
281
+ """
282
+ if self.httpd:
283
+ # FIXME: There is no shutdown() method in Python 2.4...
284
+ try:
285
+ self.httpd.shutdown()
286
+ except AttributeError:
287
+ pass
288
+ self.httpd = None
289
+
290
+ def get_url(self, path="/"):
291
+ """
292
+ Returns a URL that can be used for accessing the server (e.g. http://192.168.1.3:4321/)
293
+
294
+ :param path: Path to append to URL (e.g. if path were /foobar.html you would get a URL like
295
+ http://192.168.1.3:4321/foobar.html). Default is `/`.
296
+ """
297
+ if not self.httpd:
298
+ return None
299
+
300
+ return "http://%s:%s%s" % (self.host, self.httpd.server_port, path)
301
+
302
+ __del__ = stop
303
+
304
+
305
+ def main(args=sys.argv[1:]):
306
+ # parse command line options
307
+ parser = ArgumentParser(
308
+ description="Basic python webserver.",
309
+ formatter_class=ArgumentDefaultsHelpFormatter,
310
+ )
311
+ parser.add_argument(
312
+ "-p",
313
+ "--port",
314
+ dest="port",
315
+ type=int,
316
+ default=8888,
317
+ help="port to run the server on",
318
+ )
319
+ parser.add_argument(
320
+ "-H", "--host", dest="host", default="127.0.0.1", help="host address"
321
+ )
322
+ parser.add_argument(
323
+ "-i",
324
+ "--external-ip",
325
+ action="store_true",
326
+ dest="external_ip",
327
+ default=False,
328
+ help="find and use external ip for host",
329
+ )
330
+ parser.add_argument(
331
+ "-d",
332
+ "--docroot",
333
+ dest="docroot",
334
+ default=os.getcwd(),
335
+ help="directory to serve files from",
336
+ )
337
+ args = parser.parse_args()
338
+
339
+ if args.external_ip:
340
+ host = moznetwork.get_lan_ip()
341
+ else:
342
+ host = args.host
343
+
344
+ # create the server
345
+ server = MozHttpd(host=host, port=args.port, docroot=args.docroot)
346
+
347
+ print("Serving '%s' at %s:%s" % (server.docroot, server.host, server.port))
348
+ server.start(block=True)
349
+
350
+
351
+ if __name__ == "__main__":
352
+ main()
@@ -0,0 +1,26 @@
1
+ Metadata-Version: 2.4
2
+ Name: mozhttpd
3
+ Version: 0.7.2
4
+ Summary: Python webserver intended for use with Mozilla testing
5
+ Home-page: https://wiki.mozilla.org/Auto-tools/Projects/Mozbase
6
+ Author: Mozilla Automation and Testing Team
7
+ Author-email: tools@lists.mozilla.org
8
+ License: MPL
9
+ Keywords: mozilla
10
+ Classifier: Programming Language :: Python
11
+ Classifier: Programming Language :: Python :: 3 :: Only
12
+ Requires-Python: >=3.9
13
+ Requires-Dist: moznetwork>=0.24
14
+ Requires-Dist: mozinfo>=1.0.0
15
+ Dynamic: author
16
+ Dynamic: author-email
17
+ Dynamic: classifier
18
+ Dynamic: description
19
+ Dynamic: home-page
20
+ Dynamic: keywords
21
+ Dynamic: license
22
+ Dynamic: requires-dist
23
+ Dynamic: requires-python
24
+ Dynamic: summary
25
+
26
+ see https://firefox-source-docs.mozilla.org/mozbase/index.html
@@ -0,0 +1,8 @@
1
+ mozhttpd/__init__.py,sha256=qljKhhIU4MxIoAGfAWYeR7H7_7m3oDissloWEam8674,1723
2
+ mozhttpd/handlers.py,sha256=ncMOFTMuu_3eaOxOukn9Tb-BuFDE-CmUJxZub8WqF8U,569
3
+ mozhttpd/mozhttpd.py,sha256=mV9VGNy36xn6a2G2oMtvfQGBOXGYCRt1J1Y9O_Qg4V4,12013
4
+ mozhttpd-0.7.2.dist-info/METADATA,sha256=DA8glTpUPgshhik7GuFkxGgfl5__UA3xv-ITk9bKPYI,739
5
+ mozhttpd-0.7.2.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
6
+ mozhttpd-0.7.2.dist-info/entry_points.txt,sha256=u-Fp56ydSR-wYuI8A8bN90HCDcGJPP9E8fYAF8cjIJw,43
7
+ mozhttpd-0.7.2.dist-info/top_level.txt,sha256=9Owz_S1XzGI97vmDmY5GfV_7sWF3GVFt7nhmPIUfkqI,9
8
+ mozhttpd-0.7.2.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ mozhttpd = mozhttpd:main
@@ -0,0 +1 @@
1
+ mozhttpd