Skip to content

Instantly share code, notes, and snippets.

@pchampin
Created September 25, 2014 12:13
Show Gist options
  • Save pchampin/c3a317567efc9d802563 to your computer and use it in GitHub Desktop.
Save pchampin/c3a317567efc9d802563 to your computer and use it in GitHub Desktop.
HTTP response generator
#!/usr/bin/env python
"""
This simple service is aimed at web application developers. It allows them to
specify in the URL the HTTP response they want to get, in order to test the
behaviour of client codes.
The PATH_INFO is the desired status code, optionnally followed by a custom
message, e.g.:
/200
/404%20This%20is%20not%20the%20page%20you%20are%20looking%20for
Additionnal QUERY_STRING parameters can be used to add custom HTTP headers,
for example:
/303?location=http://example.org/
/401?www-authenticate=basic+realm=toto/
Note that, unless they are explicitly provided, the following headers will be
set with default values:
content-type: text/plain
access-control-allow-origin: *
location: /200 (only when the status code is 3xx)
"""
from urlparse import parse_qs
from httplib import responses
def application(environ, start_response):
path_info = environ['PATH_INFO']
if path_info in ('', '/'):
start_response("200 Ok", [
("content-type", "text/plain"),
])
return [__doc__]
try:
status_int = int(path_info[1:4])
status_str = path_info[1:]
body = 'This is {PATH_INFO}\n'.format(**environ)
except ValueError:
status_int = -1
if not (100 <= status_int <= 599):
status_str = "404 Not found"
body = ('You should require a valid HTTP code, '
'e.g. {SCRIPT_NAME}/200\n').format(**environ)
elif len(status_str) == 3:
status_str = "{} {}".format(status_str, responses[status_int])
custom_headers = parse_qs(environ['QUERY_STRING'])
headers = [
(key, val)
for key, vals in custom_headers.items()
for val in vals
]
if 'content-type' not in custom_headers:
headers.append(('content-type', 'text/plain'))
if 'access-control-allow-origin' not in custom_headers:
headers.append(('access-control-allow-origin', '*'))
if status_int % 100 == 3:
if 'location' not in custom_headers:
headers.append(('location', '{SCRIPT_NAME}/200'.format(**environ)))
start_response(status_str, headers)
return [body]
if __name__ == "__main__":
from wsgiref.simple_server import make_server
httpd = make_server("localhost", 12345, application)
httpd.serve_forever()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment