def __init__(self, environ, *args, **kwargs):
"""Constructs a Request object from a WSGI environment.
:param environ:
A WSGI-compliant environment dictionary.
"""
if kwargs.get('charset') is None and not hasattr(webob, '__version__'):
# webob 0.9 didn't have a __version__ attribute and also defaulted
# to None rather than UTF-8 if no charset was provided. Providing a
# default charset is required for backwards compatibility.
match = _charset_re.search(environ.get('CONTENT_TYPE', ''))
if match:
self._request_charset = (
match.group(1).lower().strip().strip('"').strip())
kwargs['charset'] = 'utf-8'
super(Request, self).__init__(environ, *args, **kwargs)
self.registry = {}
python类Request()的实例源码
def __init__(self, request=None, response=None):
"""Initializes this request handler with the given WSGI application,
Request and Response.
When instantiated by ``webapp.WSGIApplication``, request and response
are not set on instantiation. Instead, initialize() is called right
after the handler is created to set them.
Also in webapp dispatching is done by the WSGI app, while webapp2
does it here to allow more flexibility in extended classes: handlers
can wrap :meth:`dispatch` to check for conditions before executing the
requested method and/or post-process the response.
.. note::
Parameters are optional only to support webapp's constructor which
doesn't take any arguments. Consider them as required.
:param request:
A :class:`Request` instance.
:param response:
A :class:`Response` instance.
"""
self.initialize(request, response)
def set_globals(self, app=None, request=None):
"""Registers the global variables for app and request.
If :mod:`webapp2_extras.local` is available, the app and request
class attributes are assigned to a proxy object that returns them
using thread-local, making the application thread-safe. This can also
be used in environments that don't support threading.
If :mod:`webapp2_extras.local` is not available, app and request will
be assigned directly as class attributes. This should only be used in
non-threaded environments (e.g., App Engine Python 2.5).
:param app:
A :class:`WSGIApplication` instance.
:param request:
A :class:`Request` instance.
"""
if _local is not None: # pragma: no cover
_local.app = app
_local.request = request
else: # pragma: no cover
WSGIApplication.app = WSGIApplication.active_instance = app
WSGIApplication.request = request
def __init__(self, environ):
"""Constructs a Request object from a WSGI environment.
If the charset isn't specified in the Content-Type header, defaults
to UTF-8.
Args:
environ: A WSGI-compliant environment dictionary.
"""
match = _CHARSET_RE.search(environ.get('CONTENT_TYPE', ''))
if match:
charset = match.group(1).lower()
else:
charset = 'utf-8'
webob.Request.__init__(self, environ, charset=charset,
unicode_errors= 'ignore', decode_param_names=True)
def __init__(self, environ):
"""Constructs a Request object from a WSGI environment.
If the charset isn't specified in the Content-Type header, defaults
to UTF-8.
Args:
environ: A WSGI-compliant environment dictionary.
"""
match = _CHARSET_RE.search(environ.get('CONTENT_TYPE', ''))
if match:
charset = match.group(1).lower()
else:
charset = 'utf-8'
webob.Request.__init__(self, environ, charset=charset,
unicode_errors= 'ignore', decode_param_names=True)
def rest_controller(cls):
def replacement(environ, start_response):
req = Request(environ)
try:
instance = cls(req, **req.urlvars)
action = req.urlvars.get('action')
if action:
action += '_' + req.method.lower()
else:
action = req.method.lower()
try:
method = getattr(instance, action)
except AttributeError:
raise exc.HTTPNotFound("No action %s" % action)
resp = method()
if isinstance(resp, type("")):
resp = Response(body=resp)
except exc.HTTPException as e:
resp = e
return resp(environ, start_response)
return replacement
def __init__(self, environ):
"""Constructs a Request object from a WSGI environment.
If the charset isn't specified in the Content-Type header, defaults
to UTF-8.
Args:
environ: A WSGI-compliant environment dictionary.
"""
match = _CHARSET_RE.search(environ.get('CONTENT_TYPE', ''))
if match:
charset = match.group(1).lower()
else:
charset = 'utf-8'
webob.Request.__init__(self, environ, charset=charset,
unicode_errors= 'ignore', decode_param_names=True)
def __call__(self, environ, start_response):
app = self.wrapped
request = Request(environ, charset='utf-8')
self.exception = None
self.traceback = None
try:
to_return = b''
for i in app(environ, start_response):
to_return += i
except:
to_return = b''
(_, self.exception, self.traceback) = sys.exc_info()
traceback_html = six.text_type(traceback.format_exc())
for i in HTTPInternalServerError(content_type=ascii_as_bytes_or_str('text/plain'), charset=ascii_as_bytes_or_str('utf-8'), unicode_body=traceback_html)(environ, start_response):
to_return += i
yield to_return
def __call__(self, environ, start_response):
"""Called by WSGI when a request comes in.
Args:
environ: A dict holding environment variables.
start_response: A WSGI callable (PEP333).
Returns:
Application response data as an iterable. It just returns
the return value of the inner WSGI app.
"""
req = Request(environ)
preferred_languages = list(req.accept_language)
if self.default_language not in preferred_languages:
preferred_languages.append(self.default_language)
translation = gettext.translation(
'messages', self.locale_path, fallback=True,
languages=preferred_languages, codeset='utf-8')
translation.install(unicode=True, names=['gettext', 'ngettext'])
environ['i18n_utils.active_translation'] = translation
environ['i18n_utils.preferred_languages'] = preferred_languages
return self.app(environ, start_response)
def __init__(self, environ):
"""Constructs a Request object from a WSGI environment.
If the charset isn't specified in the Content-Type header, defaults
to UTF-8.
Args:
environ: A WSGI-compliant environment dictionary.
"""
match = _CHARSET_RE.search(environ.get('CONTENT_TYPE', ''))
if match:
charset = match.group(1).lower()
else:
charset = 'utf-8'
webob.Request.__init__(self, environ, charset=charset,
unicode_errors= 'ignore', decode_param_names=True)
def __init__(self, environ, *args, **kwargs):
"""Constructs a Request object from a WSGI environment.
:param environ:
A WSGI-compliant environment dictionary.
"""
if kwargs.get('charset') is None and not hasattr(webob, '__version__'):
# webob 0.9 didn't have a __version__ attribute and also defaulted
# to None rather than UTF-8 if no charset was provided. Providing a
# default charset is required for backwards compatibility.
match = _charset_re.search(environ.get('CONTENT_TYPE', ''))
if match:
charset = match.group(1).lower().strip().strip('"').strip()
else:
charset = 'utf-8'
kwargs['charset'] = charset
super(Request, self).__init__(environ, *args, **kwargs)
self.registry = {}
def __init__(self, request=None, response=None):
"""Initializes this request handler with the given WSGI application,
Request and Response.
When instantiated by ``webapp.WSGIApplication``, request and response
are not set on instantiation. Instead, initialize() is called right
after the handler is created to set them.
Also in webapp dispatching is done by the WSGI app, while webapp2
does it here to allow more flexibility in extended classes: handlers
can wrap :meth:`dispatch` to check for conditions before executing the
requested method and/or post-process the response.
.. note::
Parameters are optional only to support webapp's constructor which
doesn't take any arguments. Consider them as required.
:param request:
A :class:`Request` instance.
:param response:
A :class:`Response` instance.
"""
self.initialize(request, response)
def set_globals(self, app=None, request=None):
"""Registers the global variables for app and request.
If :mod:`webapp2_extras.local` is available the app and request
class attributes are assigned to a proxy object that returns them
using thread-local, making the application thread-safe. This can also
be used in environments that don't support threading.
If :mod:`webapp2_extras.local` is not available app and request will
be assigned directly as class attributes. This should only be used in
non-threaded environments (e.g., App Engine Python 2.5).
:param app:
A :class:`WSGIApplication` instance.
:param request:
A :class:`Request` instance.
"""
if _local is not None: # pragma: no cover
_local.app = app
_local.request = request
else: # pragma: no cover
WSGIApplication.app = WSGIApplication.active_instance = app
WSGIApplication.request = request
def __init__(self, environ):
"""Constructs a Request object from a WSGI environment.
If the charset isn't specified in the Content-Type header, defaults
to UTF-8.
Args:
environ: A WSGI-compliant environment dictionary.
"""
match = _CHARSET_RE.search(environ.get('CONTENT_TYPE', ''))
if match:
charset = match.group(1).lower()
else:
charset = 'utf-8'
webob.Request.__init__(self, environ, charset=charset,
unicode_errors= 'ignore', decode_param_names=True)
xvp_proxy.py 文件源码
项目:Trusted-Platform-Module-nova
作者: BU-NU-CLOUD-SP16
项目源码
文件源码
阅读 32
收藏 0
点赞 0
评论 0
def proxy_connection(self, req, connect_info, start_response):
"""Spawn bi-directional vnc proxy."""
sockets = {}
t0 = utils.spawn(self.handshake, req, connect_info, sockets)
t0.wait()
if not sockets.get('client') or not sockets.get('server'):
LOG.info(_LI("Invalid request: %s"), req)
start_response('400 Invalid Request',
[('content-type', 'text/html')])
return "Invalid Request"
client = sockets['client']
server = sockets['server']
t1 = utils.spawn(self.one_way_proxy, client, server)
t2 = utils.spawn(self.one_way_proxy, server, client)
t1.wait()
t2.wait()
# Make sure our sockets are closed
server.close()
client.close()
xvp_proxy.py 文件源码
项目:Trusted-Platform-Module-nova
作者: BU-NU-CLOUD-SP16
项目源码
文件源码
阅读 29
收藏 0
点赞 0
评论 0
def __call__(self, environ, start_response):
try:
req = webob.Request(environ)
LOG.info(_LI("Request: %s"), req)
token = req.params.get('token')
if not token:
LOG.info(_LI("Request made with missing token: %s"), req)
start_response('400 Invalid Request',
[('content-type', 'text/html')])
return "Invalid Request"
ctxt = context.get_admin_context()
api = consoleauth_rpcapi.ConsoleAuthAPI()
connect_info = api.check_token(ctxt, token)
if not connect_info:
LOG.info(_LI("Request made with invalid token: %s"), req)
start_response('401 Not Authorized',
[('content-type', 'text/html')])
return "Not Authorized"
return self.proxy_connection(req, connect_info, start_response)
except Exception as e:
LOG.info(_LI("Unexpected error: %s"), e)
def __init__(self, environ, *args, **kwargs):
"""Constructs a Request object from a WSGI environment.
:param environ:
A WSGI-compliant environment dictionary.
"""
if kwargs.get('charset') is None and not hasattr(webob, '__version__'):
# webob 0.9 didn't have a __version__ attribute and also defaulted
# to None rather than UTF-8 if no charset was provided. Providing a
# default charset is required for backwards compatibility.
match = _charset_re.search(environ.get('CONTENT_TYPE', ''))
if match:
charset = match.group(1).lower().strip().strip('"').strip()
else:
charset = 'utf-8'
kwargs['charset'] = charset
super(Request, self).__init__(environ, *args, **kwargs)
self.registry = {}
def __init__(self, request=None, response=None):
"""Initializes this request handler with the given WSGI application,
Request and Response.
When instantiated by ``webapp.WSGIApplication``, request and response
are not set on instantiation. Instead, initialize() is called right
after the handler is created to set them.
Also in webapp dispatching is done by the WSGI app, while webapp2
does it here to allow more flexibility in extended classes: handlers
can wrap :meth:`dispatch` to check for conditions before executing the
requested method and/or post-process the response.
.. note::
Parameters are optional only to support webapp's constructor which
doesn't take any arguments. Consider them as required.
:param request:
A :class:`Request` instance.
:param response:
A :class:`Response` instance.
"""
self.initialize(request, response)
def set_globals(self, app=None, request=None):
"""Registers the global variables for app and request.
If :mod:`webapp2_extras.local` is available the app and request
class attributes are assigned to a proxy object that returns them
using thread-local, making the application thread-safe. This can also
be used in environments that don't support threading.
If :mod:`webapp2_extras.local` is not available app and request will
be assigned directly as class attributes. This should only be used in
non-threaded environments (e.g., App Engine Python 2.5).
:param app:
A :class:`WSGIApplication` instance.
:param request:
A :class:`Request` instance.
"""
if _local is not None: # pragma: no cover
_local.app = app
_local.request = request
else: # pragma: no cover
WSGIApplication.app = WSGIApplication.active_instance = app
WSGIApplication.request = request
def __call__(self, environ, start_response):
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(explanation='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)
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 __init__(self, *args, **kwargs):
super(Request, self).__init__(*args, **kwargs)
self._resource_cache = {}
def __init__(self, *args, **kwargs):
super(Request, self).__init__(*args, **kwargs)
self._resource_cache = {}
if not hasattr(self, 'api_version_request'):
self.api_version_request = api_version.APIVersionRequest()
def blank(cls, *args, **kwargs):
if args is not None:
if 'v1' in args[0]:
kwargs['base_url'] = 'http://localhost/v1'
use_admin_context = kwargs.pop('use_admin_context', False)
version = kwargs.pop('version', '1.0')
out = base.Request.blank(*args, **kwargs)
out.environ['cinder.context'] = FakeRequestContext(
fake.USER_ID,
fake.PROJECT_ID,
is_admin=use_admin_context)
out.api_version_request = Join(version)
return out
def blank(cls, path, environ=None, base_url=None,
headers=None, **kwargs): # pragma: no cover
"""Adds parameters compatible with WebOb > 1.2: POST and **kwargs."""
try:
request = super(Request, cls).blank(
path,
environ=environ,
base_url=base_url,
headers=headers,
**kwargs
)
if cls._request_charset and not cls._request_charset == 'utf-8':
return request.decode(cls._request_charset)
return request
except TypeError:
if not kwargs:
raise
data = kwargs.pop('POST', None)
if data is not None:
environ = environ or {}
environ['REQUEST_METHOD'] = 'POST'
if hasattr(data, 'items'):
data = list(data.items())
if not isinstance(data, str):
data = urlencode(data)
environ['wsgi.input'] = cStringIO(data)
environ['webob.is_body_seekable'] = True
environ['CONTENT_LENGTH'] = str(len(data))
environ['CONTENT_TYPE'] = 'application/x-www-form-urlencoded'
base = super(Request, cls).blank(path, environ=environ,
base_url=base_url, headers=headers)
if kwargs:
obj = cls(base.environ, **kwargs)
obj.headers.update(base.headers)
return obj
else:
return base
def initialize(self, request, response):
"""Initializes this request handler with the given WSGI application,
Request and Response.
:param request:
A :class:`Request` instance.
:param response:
A :class:`Response` instance.
"""
self.request = request
self.response = response
self.app = WSGIApplication.active_instance
def match(self, request):
"""Matches all routes against a request object.
The first one that matches is returned.
:param request:
A :class:`Request` instance.
:returns:
A tuple ``(route, args, kwargs)`` if a route matched, or None.
"""
raise NotImplementedError()
def default_matcher(self, request):
"""Matches all routes against a request object.
The first one that matches is returned.
:param request:
A :class:`Request` instance.
:returns:
A tuple ``(route, args, kwargs)`` if a route matched, or None.
:raises:
``exc.HTTPNotFound`` if no route matched or
``exc.HTTPMethodNotAllowed`` if a route matched but the HTTP
method was not allowed.
"""
method_not_allowed = False
for route in self.match_routes:
try:
match = route.match(request)
if match:
return match
except exc.HTTPMethodNotAllowed:
method_not_allowed = True
if method_not_allowed:
raise exc.HTTPMethodNotAllowed()
raise exc.HTTPNotFound()
def default_builder(self, request, name, args, kwargs):
"""Returns a URI for a named :class:`Route`.
:param request:
The current :class:`Request` object.
:param name:
The route name.
:param args:
Tuple of positional arguments to build the URI. All positional
variables defined in the route must be passed and must conform
to the format set in the route. Extra arguments are ignored.
:param kwargs:
Dictionary of keyword arguments to build the URI. All variables
not set in the route default values must be passed and must
conform to the format set in the route. Extra keywords are
appended as a query string.
A few keywords have special meaning:
- **_full**: If True, builds an absolute URI.
- **_scheme**: URI scheme, e.g., `http` or `https`. If defined,
an absolute URI is always returned.
- **_netloc**: Network location, e.g., `www.google.com`. If
defined, an absolute URI is always returned.
- **_fragment**: If set, appends a fragment (or "anchor") to the
generated URI.
:returns:
An absolute or relative URI.
"""
route = self.build_routes.get(name)
if route is None:
raise KeyError('Route named %r is not defined.' % name)
return route.build(request, args, kwargs)
def default_dispatcher(self, request, response):
"""Dispatches a handler.
:param request:
A :class:`Request` instance.
:param response:
A :class:`Response` instance.
:raises:
``exc.HTTPNotFound`` if no route matched or
``exc.HTTPMethodNotAllowed`` if a route matched but the HTTP
method was not allowed.
:returns:
The returned value from the handler.
"""
route, args, kwargs = rv = self.match(request)
request.route, request.route_args, request.route_kwargs = rv
if route.handler_adapter is None:
handler = route.handler
if isinstance(handler, six.string_types):
if handler not in self.handlers:
self.handlers[handler] = handler = import_string(handler)
else:
handler = self.handlers[handler]
route.handler_adapter = self.adapt(handler)
return route.handler_adapter(request, response)
def handle_exception(self, request, response, e):
"""Handles a uncaught exception occurred in :meth:`__call__`.
Uncaught exceptions can be handled by error handlers registered in
:attr:`error_handlers`. This is a dictionary that maps HTTP status
codes to callables that will handle the corresponding error code.
If the exception is not an ``HTTPException``, the status code 500
is used.
The error handlers receive (request, response, exception) and can be
a callable or a string in dotted notation to be lazily imported.
If no error handler is found, the exception is re-raised.
Based on idea from `Flask`_.
:param request:
A :class:`Request` instance.
:param response:
A :class:`Response` instance.
:param e:
The uncaught exception.
:returns:
The returned value from the error handler.
"""
if isinstance(e, HTTPException):
code = e.code
else:
code = 500
handler = self.error_handlers.get(code)
if handler:
if isinstance(handler, six.string_types):
self.error_handlers[code] = handler = import_string(handler)
return handler(request, response, e)
else:
# Re-raise it to be caught by the WSGI app.
raise