mozhttpd
— Serving up content to be consumed by the browser
Warning
The mozhttpd module is considered obsolete. For new code, please use wptserve which can do everything mozhttpd does and more.
mozhttpd
— Simple webserver
Mozhttpd is a simple http webserver written in python, designed expressly for use in automated testing scenarios. It is designed to both serve static content and provide simple web services.
The server is based on python standard library modules such as SimpleHttpServer, urlparse, etc. The ThreadingMixIn is used to serve each request on a discrete thread.
Some existing uses of mozhttpd include Peptest, Eideticker, and Talos.
The following simple example creates a basic HTTP server which serves content from the current directory, defines a single API endpoint /api/resource/<resourceid> and then serves requests indefinitely:
import mozhttpd
@mozhttpd.handlers.json_response
def resource_get(request, objid):
return (200, { 'id': objid,
'query': request.query })
httpd = mozhttpd.MozHttpd(port=8080, docroot='.',
urlhandlers = [ { 'method': 'GET',
'path': '/api/resources/([^/]+)/?',
'function': resource_get } ])
print "Serving '%s' at %s:%s" % (httpd.docroot, httpd.host, httpd.port)
httpd.start(block=True)
- class mozhttpd.MozHttpd(host='127.0.0.1', port=0, docroot=None, urlhandlers=None, path_mappings=None, proxy_host_dirs=False, log_requests=False)
- Parameters:
host – Host from which to serve (default 127.0.0.1)
port – Port from which to serve (default 8888)
docroot – Server root (default os.getcwd())
urlhandlers – Handlers to specify behavior against method and path match (default None)
path_mappings – A dict mapping URL prefixes to additional on-disk paths.
proxy_host_dirs – Toggle proxy behavior (default False)
log_requests – Toggle logging behavior (default False)
Very basic HTTP server class. Takes a docroot (path on the filesystem) and a set of urlhandler dictionaries of the form:
{ 'method': HTTP method (string): GET, POST, or DEL, 'path': PATH_INFO (regular expression string), 'function': function of form fn(arg1, arg2, arg3, ..., request) }
and serves HTTP. For each request, MozHttpd will either return a file off the docroot, or dispatch to a handler function (if both path and method match).
Note that one of docroot or urlhandlers may be None (in which case no local files or handlers, respectively, will be used). If both docroot or urlhandlers are None then MozHttpd will default to serving just the local directory.
MozHttpd also handles proxy requests (i.e. with a full URI on the request line). By default files are served from docroot according to the request URI’s path component, but if proxy_host_dirs is True, files are served from <self.docroot>/<host>/.
For example, the request “GET http://foo.bar/dir/file.html” would (assuming no handlers match) serve <docroot>/dir/file.html if proxy_host_dirs is False, or <docroot>/foo.bar/dir/file.html if it is True.
- get_url(path='/')
Returns a URL that can be used for accessing the server (e.g. http://192.168.1.3:4321/)
- Parameters:
path – Path to append to URL (e.g. if path were /foobar.html you would get a URL like http://192.168.1.3:4321/foobar.html). Default is /.
- start(block=False)
Starts the server.
If block is True, the call will not return. If block is False, the server will be started on a separate thread that can be terminated by a call to stop().
- stop()
Stops the server.
If the server is not running, this method has no effect.
- class mozhttpd.Request(uri, headers, rfile=None)
Details of a request.
- class mozhttpd.RequestHandler(*args, **kwargs)
- address_string()
Return the client address.
- do_GET()
Serve a GET request.
- log_message(format, *args)
Log an arbitrary message.
This is used by all other logging functions. Override it if you have specific logging wishes.
The first argument, FORMAT, is a format string for the message to be logged. If the format string contains any % escapes requiring parameters, they should be specified as subsequent arguments (it’s just like printf!).
The client ip and current date/time are prefixed to every message.
Unicode control characters are replaced with escaped hex before writing the output to stderr.
- parse_request()
Parse a request (internal).
The request should be stored in self.raw_requestline; the results are in self.command, self.path, self.request_version and self.headers.
Return True for success, False for failure; on failure, any relevant error response has already been sent back.
- translate_path(path)
Translate a /-separated PATH to the local filename syntax.
Components that mean special things to the local file system (e.g. drive or directory names) are ignored. (XXX They should probably be diagnosed.)
- mozhttpd.json_response(func)
Translates results of ‘func’ into a JSON response.
Interface
- class mozhttpd.MozHttpd(host='127.0.0.1', port=0, docroot=None, urlhandlers=None, path_mappings=None, proxy_host_dirs=False, log_requests=False)
- Parameters:
host – Host from which to serve (default 127.0.0.1)
port – Port from which to serve (default 8888)
docroot – Server root (default os.getcwd())
urlhandlers – Handlers to specify behavior against method and path match (default None)
path_mappings – A dict mapping URL prefixes to additional on-disk paths.
proxy_host_dirs – Toggle proxy behavior (default False)
log_requests – Toggle logging behavior (default False)
Very basic HTTP server class. Takes a docroot (path on the filesystem) and a set of urlhandler dictionaries of the form:
{ 'method': HTTP method (string): GET, POST, or DEL, 'path': PATH_INFO (regular expression string), 'function': function of form fn(arg1, arg2, arg3, ..., request) }
and serves HTTP. For each request, MozHttpd will either return a file off the docroot, or dispatch to a handler function (if both path and method match).
Note that one of docroot or urlhandlers may be None (in which case no local files or handlers, respectively, will be used). If both docroot or urlhandlers are None then MozHttpd will default to serving just the local directory.
MozHttpd also handles proxy requests (i.e. with a full URI on the request line). By default files are served from docroot according to the request URI’s path component, but if proxy_host_dirs is True, files are served from <self.docroot>/<host>/.
For example, the request “GET http://foo.bar/dir/file.html” would (assuming no handlers match) serve <docroot>/dir/file.html if proxy_host_dirs is False, or <docroot>/foo.bar/dir/file.html if it is True.
- get_url(path='/')
Returns a URL that can be used for accessing the server (e.g. http://192.168.1.3:4321/)
- Parameters:
path – Path to append to URL (e.g. if path were /foobar.html you would get a URL like http://192.168.1.3:4321/foobar.html). Default is /.
- start(block=False)
Starts the server.
If block is True, the call will not return. If block is False, the server will be started on a separate thread that can be terminated by a call to stop().
- stop()
Stops the server.
If the server is not running, this method has no effect.