Python webob.Request() Examples
The following are 30
code examples of webob.Request().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
webob
, or try the search function
.
Example #1
Source File: app.py From firefly with Apache License 2.0 | 6 votes |
def __init__(self, auth_token=None, allowed_origins=""): """Creates a firefly application. If the optional parameter auth_token is specified, the only the requests which provide that auth token in authorization header are allowed. The Cross Origin Request Sharing is disabled by default. To enable it, pass the allowed origins as allowed_origins. To allow all origins, set it to ``*``. :param auth_token: the auto_token for the application :param allowed_origins: allowed origins for cross-origin requests """ self.mapping = {} self.add_route('/', self.generate_index,internal=True) self.auth_token = auth_token self.allowed_origins = allowed_origins
Example #2
Source File: test_version_negotiation.py From senlin with Apache License 2.0 | 6 votes |
def test_accept_header_contains_simple_version(self, mock_vc): vnf = vn.VersionNegotiationFilter(None, None) self.patchobject(vnf, '_check_version_request') fake_vc = mock.Mock(return_value={'foo': 'bar'}) self.patchobject(vnf.versions_app, 'get_controller', return_value=fake_vc) major = 1 minor = 0 request = webob.Request({'PATH_INFO': ''}) request.headers['Accept'] = 'application/vnd.openstack.clustering-v1.0' response = vnf.process_request(request) self.assertEqual(major, request.environ['api.major']) self.assertEqual(minor, request.environ['api.minor']) self.assertEqual({'foo': 'bar'}, response)
Example #3
Source File: test_version_negotiation.py From senlin with Apache License 2.0 | 6 votes |
def test_no_URI_version_accept_with_invalid_MIME_type(self, mock_vc): vnf = vn.VersionNegotiationFilter(None, None) gvc = mock_vc.return_value gvc.get_controller = mock.Mock(side_effect=[None, None]) self.patchobject(vnf, '_check_version_request') request = webob.Request({'PATH_INFO': 'resource'}) request.headers['Accept'] = 'application/invalidMIMEType' response = vnf.process_request(request) self.assertIsInstance(response, webob.exc.HTTPNotFound) request.headers['Accept'] = '' response = vnf.process_request(request) self.assertEqual(gvc, response)
Example #4
Source File: i18n_utils.py From python-docs-samples with Apache License 2.0 | 6 votes |
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)
Example #5
Source File: test_version_negotiation.py From senlin with Apache License 2.0 | 6 votes |
def test_check_version_request_invalid_version(self, mock_vc): controller = mock.Mock() minv = vr.APIVersionRequest('1.0') maxv = vr.APIVersionRequest('1.100') controller.min_api_version = mock.Mock(return_value=minv) controller.max_api_version = mock.Mock(return_value=maxv) request = webob.Request({'PATH_INFO': 'resource'}) request.headers[wsgi.API_VERSION_KEY] = 'clustering 2.3' vnf = vn.VersionNegotiationFilter(None, None) ex = self.assertRaises(exception.InvalidGlobalAPIVersion, vnf._check_version_request, request, controller) expected = ("Version '2.3' is not supported by the API. Minimum is " "'%(min_ver)s' and maximum is '%(max_ver)s'." % {'min_ver': str(minv), 'max_ver': str(maxv)}) self.assertEqual(expected, str(ex))
Example #6
Source File: _webapp25.py From python-compat-runtime with Apache License 2.0 | 6 votes |
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)
Example #7
Source File: test_version_negotiation.py From senlin with Apache License 2.0 | 6 votes |
def test_request_path_contains_valid_version(self, mock_vc): vnf = vn.VersionNegotiationFilter(None, None) gvc = mock_vc.return_value x_controller = mock.Mock() gvc.get_controller = mock.Mock(return_value=x_controller) mock_check = self.patchobject(vnf, '_check_version_request') major = 1 minor = 0 request = webob.Request({'PATH_INFO': 'v1.0/resource'}) response = vnf.process_request(request) self.assertIsNone(response) self.assertEqual(major, request.environ['api.major']) self.assertEqual(minor, request.environ['api.minor']) gvc.get_controller.assert_called_once_with('1.0') mock_check.assert_called_once_with(request, x_controller)
Example #8
Source File: http.py From pledgeservice with Apache License 2.0 | 6 votes |
def wrapper(self, environ, start_response): """Wrap the wsgi application to override some path: ``/__application__``: allow to ping the server. ``/__file__?__file__={path}``: serve the file found at ``path`` """ if '__file__' in environ['PATH_INFO']: req = webob.Request(environ) resp = webob.Response() resp.content_type = 'text/html; charset=UTF-8' filename = req.params.get('__file__') if os.path.isfile(filename): body = open(filename, 'rb').read() body = body.replace(six.b('http://localhost/'), six.b('http://%s/' % req.host)) resp.body = body else: resp.status = '404 Not Found' return resp(environ, start_response) elif '__application__' in environ['PATH_INFO']: return webob.Response('server started')(environ, start_response) return self.test_app(environ, start_response)
Example #9
Source File: framework.py From pulsar with Apache License 2.0 | 6 votes |
def __call__(self, func): def controller_replacement(environ, start_response, **args): req = Request(environ) access_response = self.__handle_access(req, environ, start_response) if access_response: return access_response result = self.__execute_request(func, args, req, environ) resp = self.__build_response(result) return resp(environ, start_response) controller_replacement.func = func controller_replacement.response_type = self.response_type controller_replacement.body = self.body controller_replacement.__name__ = func.__name__ controller_replacement.__controller__ = True controller_replacement.__method__ = self.method controller_replacement.__path__ = self.path or "/%s" % func.__name__ return controller_replacement
Example #10
Source File: version_negotiation.py From senlin with Apache License 2.0 | 6 votes |
def _get_controller(self, subject, req): """Get a version specific controller based on endpoint version. Given a subject string, tries to match a major and/or minor version number. If found, sets the api.major and api.minor environ variables. :param subject: The string to check :param req: Webob.Request object :returns: A version controller instance or None. """ match = self.version_uri_regex.match(subject) if not match: return None major, minor = match.groups(0) major = int(major) minor = int(minor) req.environ['api.major'] = major req.environ['api.minor'] = minor version = '%s.%s' % (major, minor) return self.versions_app.get_controller(version)
Example #11
Source File: comp.py From kansha with BSD 3-Clause "New" or "Revised" License | 6 votes |
def __call__(self, environ, start_response): query = environ['QUERY_STRING'] if ('state=' in query) and (('code=' in query) or ('error=' in query)): request = webob.Request(environ) environ['QUERY_STRING'] += ('&' + request.params['state']) environ['REQUEST_METHOD'] = 'POST' if self.debug: perf = profile.Profile() start = time.time() ret = perf.runcall(super(WSGIApp, self).__call__, environ, start_response) if time.time() - start > 1: stats = pstats.Stats(perf) stats.sort_stats('cumtime') stats.print_stats(60) return ret else: return super(WSGIApp, self).__call__(environ, start_response)
Example #12
Source File: test_version_negotiation.py From senlin with Apache License 2.0 | 5 votes |
def test_check_version_request(self, mock_vc): controller = mock.Mock() minv = vr.APIVersionRequest('1.0') maxv = vr.APIVersionRequest('1.3') controller.min_api_version = mock.Mock(return_value=minv) controller.max_api_version = mock.Mock(return_value=maxv) request = webob.Request({'PATH_INFO': 'resource'}) request.headers[wsgi.API_VERSION_KEY] = 'clustering 1.0,compute 2.0' vnf = vn.VersionNegotiationFilter(None, None) vnf._check_version_request(request, controller) self.assertIsNotNone(request.version_request) expected = vr.APIVersionRequest('1.0') self.assertEqual(expected, request.version_request)
Example #13
Source File: test_version_negotiation.py From senlin with Apache License 2.0 | 5 votes |
def test_removes_version_from_request_path(self, mock_vc): vnf = vn.VersionNegotiationFilter(None, None) self.patchobject(vnf, '_check_version_request') expected_path = 'resource' request = webob.Request({'PATH_INFO': 'v1.0/%s' % expected_path}) response = vnf.process_request(request) self.assertIsNone(response) self.assertEqual(expected_path, request.path_info_peek())
Example #14
Source File: test_version_negotiation.py From senlin with Apache License 2.0 | 5 votes |
def test_simple_version_on_request_path(self, mock_vc): vnf = vn.VersionNegotiationFilter(None, None) self.patchobject(vnf, '_check_version_request') fake_vc = mock.Mock(return_value={'foo': 'bar'}) self.patchobject(vnf.versions_app, 'get_controller', return_value=fake_vc) request = webob.Request({'PATH_INFO': 'v1'}) response = vnf.process_request(request) self.assertEqual({'foo': 'bar'}, response)
Example #15
Source File: test_version_negotiation.py From senlin with Apache License 2.0 | 5 votes |
def test_full_version_on_request_path(self, mock_vc): vnf = vn.VersionNegotiationFilter(None, None) self.patchobject(vnf, '_check_version_request') fake_vc = mock.Mock(return_value={'foo': 'bar'}) self.patchobject(vnf.versions_app, 'get_controller', return_value=fake_vc) request = webob.Request({'PATH_INFO': 'v1.0'}) response = vnf.process_request(request) self.assertEqual({'foo': 'bar'}, response)
Example #16
Source File: test_version_negotiation.py From senlin with Apache License 2.0 | 5 votes |
def test_request_path_is_empty(self, mock_vc): vnf = vn.VersionNegotiationFilter(None, None) request = webob.Request({'PATH_INFO': '/'}) response = vnf.process_request(request) self.assertIs(mock_vc.return_value, response)
Example #17
Source File: test_version_negotiation.py From senlin with Apache License 2.0 | 5 votes |
def test_accept_header_contains_valid_version(self, mock_vc): vnf = vn.VersionNegotiationFilter(None, None) self.patchobject(vnf, '_check_version_request') major = 1 minor = 0 request = webob.Request({'PATH_INFO': 'resource'}) request.headers['Accept'] = 'application/vnd.openstack.clustering-v1.0' response = vnf.process_request(request) self.assertIsNone(response) self.assertEqual(major, request.environ['api.major']) self.assertEqual(minor, request.environ['api.minor'])
Example #18
Source File: test_version_negotiation.py From senlin with Apache License 2.0 | 5 votes |
def test_get_controller_not_match_version(self, mock_vc): gvc = mock_vc.return_value gvc.get_controller = mock.Mock(return_value=None) vnf = vn.VersionNegotiationFilter(None, None) request = webob.Request({}) res = vnf._get_controller("invalid", request) self.assertIsNone(res) self.assertEqual(0, gvc.get_controller.call_count)
Example #19
Source File: test_version_negotiation.py From senlin with Apache License 2.0 | 5 votes |
def test_accept_header_contains_unknown_version(self, mock_vc): vnf = vn.VersionNegotiationFilter(None, None) self.patchobject(vnf, '_check_version_request') request = webob.Request({'PATH_INFO': 'resource'}) request.headers['Accept'] = 'application/vnd.openstack.clustering-v2.0' response = vnf.process_request(request) self.assertIsNone(response) request.headers['Accept'] = 'application/vnd.openstack.clustering-vab' response = vnf.process_request(request) self.assertIsInstance(response, webob.exc.HTTPNotFound)
Example #20
Source File: _webapp25.py From python-compat-runtime with Apache License 2.0 | 5 votes |
def initialize(self, request, response): """Initializes this request handler with the given Request and Response.""" self.request = request self.response = response
Example #21
Source File: test_version_negotiation.py From senlin with Apache License 2.0 | 5 votes |
def test_check_version_request_invalid_format(self, mock_vc): controller = mock.Mock() request = webob.Request({'PATH_INFO': 'resource'}) request.headers[wsgi.API_VERSION_KEY] = 'clustering 2.03' vnf = vn.VersionNegotiationFilter(None, None) ex = self.assertRaises(webob.exc.HTTPBadRequest, vnf._check_version_request, request, controller) self.assertEqual("API Version String '2.03' is of invalid format. It " "must be of format 'major.minor'.", str(ex))
Example #22
Source File: test_version_negotiation.py From senlin with Apache License 2.0 | 5 votes |
def test_check_version_request_latest(self, mock_vc): controller = mock.Mock() controller.max_api_version = mock.Mock(return_value='12.34') request = webob.Request({'PATH_INFO': 'resource'}) request.headers[wsgi.API_VERSION_KEY] = 'clustering Latest' vnf = vn.VersionNegotiationFilter(None, None) vnf._check_version_request(request, controller) self.assertIsNotNone(request.version_request) expected = '12.34' self.assertEqual(expected, request.version_request)
Example #23
Source File: custom_middleware.py From allura with Apache License 2.0 | 5 votes |
def __call__(self, environ, start_response): req = Request(environ) # enforce POSTs cookie = req.cookies.get(self._cookie_name, None) if cookie is None: cookie = h.cryptographic_nonce() if req.method == 'POST': try: param = req.POST.pop(self._param_name, None) except KeyError: log.debug('error getting %s from POST', self._param_name, exc_info=True) param = None if cookie != param: log.warning('CSRF attempt detected: cookie %r != param %r', cookie, param) environ.pop('HTTP_COOKIE', None) # effectively kill the existing session if req.path.startswith('/auth/'): # for operations where you're not logged in yet (e.g. login form, pwd recovery, etc), then killing # the session doesn't help, so we block the request entirely resp = exc.HTTPForbidden() return resp(environ, start_response) # Set cookie for use in later forms: # in addition to setting a cookie, set this so its available on first response before cookie gets created in browser environ[self._cookie_name] = cookie def session_start_response(status, headers, exc_info=None): if dict(headers).get('Content-Type', '').startswith('text/html'): use_secure = 'secure; ' if environ['beaker.session'].secure else '' headers.append( (str('Set-cookie'), str('%s=%s; %sPath=/' % (self._cookie_name, cookie, use_secure)))) return start_response(status, headers, exc_info) return self._app(environ, session_start_response)
Example #24
Source File: custom_middleware.py From allura with Apache License 2.0 | 5 votes |
def __call__(self, environ, start_response): req = Request(environ) if self._no_redirect_re.match(environ['PATH_INFO']): return req.get_response(self.app)(environ, start_response) resp = None try: request_uri = req.url six.ensure_binary(request_uri).decode('ascii') except UnicodeError: resp = exc.HTTPBadRequest() else: secure = req.url.startswith('https://') srv_path = req.url.split('://', 1)[-1] # allura-loggedin is a non-secure cookie as a flag to know that the user has a session over on https force_ssl = (self._force_ssl_logged_in and req.cookies.get('allura-loggedin')) \ or self._force_ssl_re.match(environ['PATH_INFO']) if req.environ.get('tg.original_request'): # if an error occurs, then /error/document is fetched (denoted by tg.original_request) # and we don't want to do any redirects within that sub-request pass elif not secure and force_ssl: resp = exc.HTTPFound(location='https://' + srv_path) elif secure and not force_ssl: resp = exc.HTTPFound(location='http://' + srv_path) if not resp: resp = self.app return resp(environ, start_response)
Example #25
Source File: custom_middleware.py From allura with Apache License 2.0 | 5 votes |
def __call__(self, environ, start_response): environ['HTTP_HOST'] = tg.config['base_url'].split('://')[1] # setting environ['wsgi.url_scheme'] would make some links use the right http/https scheme, but is not safe # since the app may accept both http and https inbound requests, and many places in code need to check that # potentially could set wsgi.url_scheme based on 'HTTP_X_FORWARDED_SSL' == 'on' and/or # 'HTTP_X_FORWARDED_PROTO' == 'https' req = Request(environ) try: req.params # check for malformed unicode, this is the first middleware that might trip over it. resp = self.app except UnicodeError: resp = exc.HTTPBadRequest() return resp(environ, start_response)
Example #26
Source File: wsgi.py From coriolis with GNU Affero General Public License v3.0 | 5 votes |
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__'))
Example #27
Source File: wsgi.py From coriolis with GNU Affero General Public License v3.0 | 5 votes |
def __init__(self, *args, **kwargs): super(Request, self).__init__(*args, **kwargs) self._resource_cache = {}
Example #28
Source File: fakes.py From karbor with Apache License 2.0 | 5 votes |
def blank(cls, *args, **kwargs): if args is not None: if args[0].find('v1') == 0: kwargs['base_url'] = 'http://localhost/v1' else: kwargs['base_url'] = 'http://localhost/v2' use_admin_context = kwargs.pop('use_admin_context', False) out = os_wsgi.Request.blank(*args, **kwargs) out.environ['karbor.context'] = FakeRequestContext( 'fake_user', 'fakeproject', is_admin=use_admin_context) return out
Example #29
Source File: test_version_negotiation.py From senlin with Apache License 2.0 | 5 votes |
def test_get_version_controller(self, mock_vc): gvc = mock_vc.return_value xvc = mock.Mock() gvc.get_controller = mock.Mock(return_value=xvc) vnf = vn.VersionNegotiationFilter(None, None) request = webob.Request({}) res = vnf._get_controller('v1.0', request) self.assertEqual(xvc, res) self.assertEqual(1, request.environ['api.major']) self.assertEqual(0, request.environ['api.minor']) gvc.get_controller.assert_called_once_with('1.0')
Example #30
Source File: auth.py From bottle-auth with MIT License | 5 votes |
def __init__(self, request, settings=None, cookie_monster=None): self.settings = settings or {} if not isinstance(request, webob.Request): request = webob.Request(request) self.request = WebobRequestWrapper(request) if isinstance(cookie_monster, webob.Response): self.cookie_monster = WebobResponseWrapper(cookie_monster) else: self.cookie_monster = cookie_monster