Created
April 28, 2013 22:44
-
-
Save kgaughan/5478718 to your computer and use it in GitHub Desktop.
A minimal WSGI application, with some minimal routing.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import re | |
from cgi import escape | |
def index(environ, start_response): | |
""" | |
This function will be mounted on "/" and display a link | |
to the hello world page. | |
""" | |
start_response('200 OK', [('Content-Type', 'text/plain')]) | |
return ['''Hello World Application | |
This is the Hello World application: | |
`continue <hello/>`_ | |
'''] | |
def hello(environ, start_response): | |
"""Like the example above, but it uses the name specified in the URL.""" | |
# get the name from the url if it was specified there. | |
args = environ['myapp.url_args'] | |
if args: | |
subject = escape(args[0]) | |
else: | |
subject = 'World' | |
start_response('200 OK', [('Content-Type', 'text/plain')]) | |
return ['''Hello %(subject)s''' % {'subject': subject}] | |
def not_found(environ, start_response): | |
"""Called if no URL matches.""" | |
start_response('404 Not Found', [('Content-Type', 'text/plain')]) | |
return ['Not Found'] | |
# map urls to functions | |
urls = [ | |
(r'^$', index), | |
(r'hello/?$', hello), | |
(r'hello/(.+)$', hello) | |
] | |
def application(environ, start_response): | |
""" | |
The main WSGI application. Dispatch the current request to | |
the functions from above and store the regular expression | |
captures in the WSGI environment as `myapp.url_args` so that | |
the functions from above can access the url placeholders. | |
If nothing matches call the `not_found` function. | |
""" | |
path = environ.get('PATH_INFO', '').lstrip('/') | |
for regex, callback in urls: | |
match = re.search(regex, path) | |
if match is not None: | |
environ['myapp.url_args'] = match.groups() | |
return callback(environ, start_response) | |
return not_found(environ, start_response) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment