Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 OpenStack LLC # Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # Copyright 2010 OpenStack LLC. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License.
# Environment variable used to pass the request context
# Environment variable used to pass the request params
re.DOTALL)
"""Replace password with 'secret' in message.
:param message: The string which include security information. :param is_unicode: Is unicode string ? :param secret: substitution string default to "***". :returns: The string
For example: >>> mask_password('"password" : "aaaaa"') '"password" : "***"' >>> mask_password("'original_password' : 'aaaaa'") "'original_password' : '***'" >>> mask_password("u'original_password' : u'aaaaa'") "u'original_password' : u'***'" """ # Match the group 1,2 and replace all others with 'secret'
"""A thin wrapper that responds to `write` and logs."""
"""Base WSGI application wrapper. Subclasses need to implement __call__."""
def factory(cls, global_config, **local_config): """Used for paste app factories in paste.deploy config files.
Any local configuration (that is, values under the [app:APPNAME] section of the paste config) will be passed into the `__init__` method as kwargs.
A hypothetical configuration would look like:
[app:wadl] latest_version = 1.3 paste.app_factory = nova.api.fancy_api:Wadl.factory
which would result in a call to the `Wadl` class as
import nova.api.fancy_api fancy_api.Wadl(latest_version='1.3')
You could of course re-implement the `factory` method in subclasses, but using the kwarg passing it shouldn't be necessary.
""" return cls()
r"""Subclasses will probably want to implement __call__ like this:
@webob.dec.wsgify(RequestClass=Request) def __call__(self, req): # Any of the following objects work as responses:
# Option 1: simple string res = 'message\n'
# Option 2: a nicely formatted HTTP exception page res = exc.HTTPForbidden(detail='Nice try')
# Option 3: a webob Response object (in case you need to play with # headers, or you want to be treated like an iterable, or or or) res = Response(); res.app_iter = open('somefile')
# Option 4: any wsgi app to be run next res = self.application
# Option 5: you can get a Response object for a wsgi app, too, to # play with headers etc res = req.get_response(self.application)
# You can then just return your response... return res # ... or set req.response and return None. req.response = res
See the end of http://pythonpaste.org/webob/modules/dec.html for more info.
""" raise NotImplementedError('You must implement __call__')
def __call__(self, req):
# allow middleware up the stack to provide context & params context['REMOTE_USER'] = req.environ['REMOTE_USER'] del context['REMOTE_USER']
# TODO(termie): do some basic normalization on methods
# NOTE(vish): make sure we have no unicode keys for py2.6.
_('Authorization failed. %(exception)s from %(remote_addr)s') % {'exception': e, 'remote_addr': req.environ['REMOTE_ADDR']}) except Exception as e: LOG.exception(e) return render_exception(exception.UnexpectedError(exception=e))
return result return result
for (k, v) in d.iteritems()])
context=context, token_id=context['token_id'])
except AttributeError: LOG.debug('Invalid user') raise exception.Unauthorized()
except AttributeError: LOG.debug('Invalid tenant') raise exception.Unauthorized()
# NOTE(vish): this is pretty inefficient for role in creds.get('roles', [])] # Accept either is_admin or the admin role
"""Base WSGI middleware.
These classes require an application to be initialized that will be called next. By default the middleware will simply call its wrapped app, or you can override __call__ to customize its behavior.
"""
def factory(cls, global_config, **local_config): """Used for paste app factories in paste.deploy config files.
Any local configuration (that is, values under the [filter:APPNAME] section of the paste config) will be passed into the `__init__` method as kwargs.
A hypothetical configuration would look like:
[filter:analytics] redis_host = 127.0.0.1 paste.filter_factory = nova.api.analytics:Analytics.factory
which would result in a call to the `Analytics` class as
import nova.api.analytics analytics.Analytics(app_from_paste, redis_host='127.0.0.1')
You could of course re-implement the `factory` method in subclasses, but using the kwarg passing it shouldn't be necessary.
"""
"""Called on each request.
If this returns None, the next application down the stack will be executed. If it returns a response then that response will be returned and execution will stop here.
"""
"""Do whatever you'd like to the response, based on the request."""
def __call__(self, request): except Exception as e: LOG.exception(e) return render_exception(exception.UnexpectedError(exception=e))
"""Helper class for debugging a WSGI application.
Can be inserted into any WSGI application chain to get information about the request and response.
"""
def __call__(self, req): if LOG.isEnabledFor(logging.DEBUG): LOG.debug('%s %s %s', ('*' * 20), 'REQUEST ENVIRON', ('*' * 20)) for key, value in req.environ.items(): LOG.debug('%s = %s', key, mask_password(value, is_unicode=True)) LOG.debug('') LOG.debug('%s %s %s', ('*' * 20), 'REQUEST BODY', ('*' * 20)) for line in req.body_file: LOG.debug(mask_password(line)) LOG.debug('')
resp = req.get_response(self.application) if LOG.isEnabledFor(logging.DEBUG): LOG.debug('%s %s %s', ('*' * 20), 'RESPONSE HEADERS', ('*' * 20)) for (key, value) in resp.headers.iteritems(): LOG.debug('%s = %s', key, value) LOG.debug('')
resp.app_iter = self.print_generator(resp.app_iter)
return resp
def print_generator(app_iter): """Iterator that prints the contents of a wrapper string.""" LOG.debug('%s %s %s', ('*' * 20), 'RESPONSE BODY', ('*' * 20)) for part in app_iter: LOG.debug(part) yield part
"""WSGI middleware that maps incoming requests to WSGI apps."""
"""Create a router for the given routes.Mapper.
Each route in `mapper` must specify a 'controller', which is a WSGI app to call. You'll probably want to specify an 'action' as well and have your controller be an object that can route the request to the action-specific method.
Examples: mapper = routes.Mapper() sc = ServerController()
# Explicit mapping of one route to a controller+action mapper.connect(None, '/svrlist', controller=sc, action='list')
# Actions are all implicitly defined mapper.resource('server', 'servers', controller=sc)
# Pointing to an arbitrary WSGI app. You can specify the # {path_info:.*} parameter so the target app can be handed just that # section of the URL. mapper.connect(None, '/v1.0/{path_info:.*}', controller=BlogApp())
""" # if we're only running in debug, bump routes' internal logging up a # notch, as it's very spammy logging.getLogger('routes.middleware').setLevel(logging.INFO)
self.map)
def __call__(self, req): """Route the incoming request to a controller based on self.map.
If no match, return a 404.
"""
def _dispatch(req): """Dispatch the request to the appropriate controller.
Called by self._router after matching the incoming request to a route and putting the information into req.environ. Either returns 404 or the routed WSGI app's response.
""" exception.NotFound(_('The resource could not be found.')))
mapper = routes.Mapper() routers = []
"""Router that supports use by ComposingRouter."""
"""Add routes to given mapper.""" pass
"""A router that allows extensions to supplement or overwrite routes.
Expects to be subclassed. """
pass
def factory(cls, global_config, **local_config): """Used for paste app factories in paste.deploy config files.
Any local configuration (that is, values under the [filter:APPNAME] section of the paste config) will be passed into the `__init__` method as kwargs.
A hypothetical configuration would look like:
[filter:analytics] redis_host = 127.0.0.1 paste.filter_factory = nova.api.analytics:Analytics.factory
which would result in a call to the `Analytics` class as
import nova.api.analytics analytics.Analytics(app_from_paste, redis_host='127.0.0.1')
You could of course re-implement the `factory` method in subclasses, but using the kwarg passing it shouldn't be necessary.
"""
"""Forms a WSGI response."""
else:
status='%s %s' % status, headerlist=headers)
"""Forms a WSGI response based on the current error.""" 'code': error.code, 'title': error.title, 'message': str(error) }} body['error']['identity'] = error.authentication |