Created
June 10, 2013 14:54
-
-
Save jperras/5749361 to your computer and use it in GitHub Desktop.
This file contains 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 | |
version_pattern = re.compile(r"/v(?P<version>[0-9a-z\-\+\.]+)", re.IGNORECASE) | |
class VersionedAPIMiddleware(object): | |
""" | |
Allows a Werkzeug/Flask application to have a versioned API. | |
This middleware will extract out the API version specification in a URL | |
segment and then forward the processing of the endpoint (sans version, in | |
the case of the URL segment), to the application along with an | |
environment variable indicating what the version requested was. | |
If no appropriate version could be parsed, then `None` is set as the | |
value of `API_VERSION`. | |
""" | |
def __init__(self, app): | |
self.app = app | |
def __call__(self, environ, start_response): | |
path = environ.get('PATH_INFO', '') | |
match = version_pattern.match(path) | |
if match: | |
environ['API_VERSION'] = match.group(1) | |
environ['PATH_INFO'] = re.sub(version_pattern, '', path, count=1) | |
else: | |
environ['API_VERSION'] = None | |
return self.app(environ, start_response) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment