当前位置: 首页>>代码示例>>Python>>正文


Python webob.Request方法代码示例

本文整理汇总了Python中webob.Request方法的典型用法代码示例。如果您正苦于以下问题:Python webob.Request方法的具体用法?Python webob.Request怎么用?Python webob.Request使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在webob的用法示例。


在下文中一共展示了webob.Request方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: wrapper

# 需要导入模块: import webob [as 别名]
# 或者: from webob import Request [as 别名]
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) 
开发者ID:MayOneUS,项目名称:pledgeservice,代码行数:25,代码来源:http.py

示例2: __call__

# 需要导入模块: import webob [as 别名]
# 或者: from webob import Request [as 别名]
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) 
开发者ID:Net-ng,项目名称:kansha,代码行数:19,代码来源:comp.py

示例3: __call__

# 需要导入模块: import webob [as 别名]
# 或者: from webob import Request [as 别名]
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 
开发者ID:galaxyproject,项目名称:pulsar,代码行数:23,代码来源:framework.py

示例4: __init__

# 需要导入模块: import webob [as 别名]
# 或者: from webob import Request [as 别名]
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 
开发者ID:rorodata,项目名称:firefly,代码行数:20,代码来源:app.py

示例5: __call__

# 需要导入模块: import webob [as 别名]
# 或者: from webob import Request [as 别名]
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) 
开发者ID:GoogleCloudPlatform,项目名称:python-docs-samples,代码行数:25,代码来源:i18n_utils.py

示例6: __init__

# 需要导入模块: import webob [as 别名]
# 或者: from webob import Request [as 别名]
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) 
开发者ID:GoogleCloudPlatform,项目名称:python-compat-runtime,代码行数:19,代码来源:_webapp25.py

示例7: _get_controller

# 需要导入模块: import webob [as 别名]
# 或者: from webob import Request [as 别名]
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) 
开发者ID:openstack,项目名称:senlin,代码行数:23,代码来源:version_negotiation.py

示例8: test_request_path_contains_valid_version

# 需要导入模块: import webob [as 别名]
# 或者: from webob import Request [as 别名]
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) 
开发者ID:openstack,项目名称:senlin,代码行数:19,代码来源:test_version_negotiation.py

示例9: test_accept_header_contains_simple_version

# 需要导入模块: import webob [as 别名]
# 或者: from webob import Request [as 别名]
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) 
开发者ID:openstack,项目名称:senlin,代码行数:18,代码来源:test_version_negotiation.py

示例10: test_no_URI_version_accept_with_invalid_MIME_type

# 需要导入模块: import webob [as 别名]
# 或者: from webob import Request [as 别名]
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) 
开发者ID:openstack,项目名称:senlin,代码行数:18,代码来源:test_version_negotiation.py

示例11: test_check_version_request_invalid_version

# 需要导入模块: import webob [as 别名]
# 或者: from webob import Request [as 别名]
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)) 
开发者ID:openstack,项目名称:senlin,代码行数:20,代码来源:test_version_negotiation.py

示例12: __init__

# 需要导入模块: import webob [as 别名]
# 或者: from webob import Request [as 别名]
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 
开发者ID:avelino,项目名称:bottle-auth,代码行数:14,代码来源:auth.py

示例13: get_authenticated_user

# 需要导入模块: import webob [as 别名]
# 或者: from webob import Request [as 别名]
def get_authenticated_user(self, callback):
        """Gets the OAuth authorized user and access token on callback.

        This method should be called from the handler for your registered
        OAuth Callback URL to complete the registration process. We call
        callback with the authenticated user, which in addition to standard
        attributes like 'name' includes the 'access_key' attribute, which
        contains the OAuth access you can use to make authorized requests
        to this service on behalf of the user.

        """
        request_key = self.get_argument("oauth_token")
        oauth_verifier = self.get_argument("oauth_verifier", None)
        request_cookie = self.get_cookie("_oauth_request_token")
        if not request_cookie:
            log.warning("Missing OAuth request token cookie")
            callback(None)
            return
        self.clear_cookie("_oauth_request_token")
        cookie_key, cookie_secret = [base64.b64decode(i) for i in request_cookie.split("|")]
        if cookie_key != request_key:
            log.warning("Request token does not match cookie")
            callback(None)
            return
        token = dict(key=cookie_key, secret=cookie_secret)
        if oauth_verifier:
          token["verifier"] = oauth_verifier
        http = httpclient.AsyncHTTPClient()
        http.fetch(self._oauth_access_token_url(token), self.async_callback(
            self._on_access_token, callback)) 
开发者ID:avelino,项目名称:bottle-auth,代码行数:32,代码来源:auth.py

示例14: __call__

# 需要导入模块: import webob [as 别名]
# 或者: from webob import Request [as 别名]
def __call__(self, environ, start_response):
        req = webob.Request(environ)
        params = req.params.mixed()
        method = req.method
        if method == "POST":
            resp = self._post(req, params)
        elif method == "GET":
            resp = self._get(req, params)
        else:
            raise Exception("Unhandled request method %s" % method)
        return resp(environ, start_response) 
开发者ID:galaxyproject,项目名称:pulsar,代码行数:13,代码来源:test_utils.py

示例15: __call__

# 需要导入模块: import webob [as 别名]
# 或者: from webob import Request [as 别名]
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__')) 
开发者ID:cloudbase,项目名称:vdi-broker,代码行数:37,代码来源:wsgi.py


注:本文中的webob.Request方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。