aiohttp.web.Request

Here are the examples of the python api aiohttp.web.Request taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

18 Examples 7

Example 1

Project: webargs
License: View license
Source File: aiohttpparser.py
    def get_request_from_view_args(self, view, args, kwargs):
        """Get request object from a handler function or method. Used internally by
        ``use_args`` and ``use_kwargs``.
        """
        if len(args) > 1:
            req = args[1]
        else:
            req = args[0]
        assert isinstance(req, web.Request), 'Request argument not found for handler'
        return req

Example 2

Project: aiohttp-cors
License: View license
Source File: abc.py
    @asyncio.coroutine
    @abstractmethod
    def get_preflight_request_config(
            self,
            preflight_request: web.Request,
            origin: str,
            requested_method: str):
        """Get stored CORS configuration for specified HTTP method and origin

Example 3

Project: aiohttp-cors
License: View license
Source File: cors_config.py
    @staticmethod
    def _parse_request_method(request: web.Request):
        """Parse Access-Control-Request-Method header of the preflight request
        """
        method = request.headers.get(hdrs.ACCESS_CONTROL_REQUEST_METHOD)
        if method is None:
            raise web.HTTPForbidden(
                text="CORS preflight request failed: "
                     "'Access-Control-Request-Method' header is not specified")

        # FIXME: validate method string (ABNF: method = token), if parsing
        # fails, raise HTTPForbidden.

        return method

Example 4

Project: aiohttp-cors
License: View license
Source File: cors_config.py
    @staticmethod
    def _parse_request_headers(request: web.Request):
        """Parse Access-Control-Request-Headers header or the preflight request

        Returns set of headers in upper case.
        """
        headers = request.headers.get(hdrs.ACCESS_CONTROL_REQUEST_HEADERS)
        if headers is None:
            return frozenset()

        # FIXME: validate each header string, if parsing fails, raise
        # HTTPForbidden.
        # FIXME: check, that headers split and stripped correctly (according
        # to ABNF).
        headers = (h.strip(" \t").upper() for h in headers.split(","))
        # pylint: disable=bad-builtin
        return frozenset(filter(None, headers))

Example 5

    @asyncio.coroutine
    def get_preflight_request_config(
            self,
            preflight_request: web.Request,
            origin: str,
            requested_method: str):
        assert self.is_preflight_request(preflight_request)

        # TODO: Test difference between request.raw_path and request.path.
        path = preflight_request.path
        for route, config in self._route_config.items():
            match_info, allowed_methods = yield from route.resource.resolve(
                requested_method, path)
            if match_info is not None:
                return collections.ChainMap(config, self._default_config)
        else:
            raise KeyError

Example 6

Project: aiohttp-cors
License: View license
Source File: test_main.py
@asyncio.coroutine
# pylint: disable=unused-argument
def handler(request: web.Request) -> web.StreamResponse:
    """Dummy request handler, returning `TEST_BODY`."""
    response = web.Response(text=TEST_BODY)

    response.headers[SERVER_CUSTOM_HEADER_NAME] = SERVER_CUSTOM_HEADER_VALUE

    return response

Example 7

Project: aiohttp-jinja2
License: View license
Source File: test_simple_renderer.py
    def make_request(self, app, method, path):
        headers = CIMultiDict()
        message = aiohttp.RawRequestMessage(method, path,
                                            aiohttp.HttpVersion(1, 1),
                                            headers, [], False, False)
        self.payload = mock.Mock()
        self.transport = mock.Mock()
        self.writer = mock.Mock()
        req = web.Request(app, message, self.payload,
                          self.transport, self.writer, 15)
        return req

Example 8

Project: aiohttp-cors
License: View license
Source File: abc.py
    @abstractmethod
    def is_preflight_request(self, request: web.Request) -> bool:
        """Is `request` is a CORS preflight request."""

Example 9

Project: aiohttp-cors
License: View license
Source File: abc.py
    @abstractmethod
    def is_cors_enabled_on_request(self, request: web.Request) -> bool:
        """Is `request` is a request for CORS-enabled resource."""

Example 10

Project: aiohttp-cors
License: View license
Source File: abc.py
    @abstractmethod
    def get_non_preflight_request_config(self, request: web.Request):
        """Get stored CORS configuration for routing entity that handles

Example 11

Project: aiohttp-cors
License: View license
Source File: cors_config.py
    @asyncio.coroutine
    def _on_response_prepare(self,
                             request: web.Request,
                             response: web.StreamResponse):
        """Non-preflight CORS request response processor.

        If request is done on CORS-enabled route, process request parameters
        and set appropriate CORS response headers.
        """
        if (not self._router_adapter.is_cors_enabled_on_request(request) or
                self._router_adapter.is_preflight_request(request)):
            # Either not CORS enabled route, or preflight request which is
            # handled in its own handler.
            return

        # Processing response of non-preflight CORS-enabled request.

        config = self._router_adapter.get_non_preflight_request_config(request)

        # Handle according to part 6.1 of the CORS specification.

        origin = request.headers.get(hdrs.ORIGIN)
        if origin is None:
            # Terminate CORS according to CORS 6.1.1.
            return

        options = config.get(origin, config.get("*"))
        if options is None:
            # Terminate CORS according to CORS 6.1.2.
            return

        assert hdrs.ACCESS_CONTROL_ALLOW_ORIGIN not in response.headers
        assert hdrs.ACCESS_CONTROL_ALLOW_CREDENTIALS not in response.headers
        assert hdrs.ACCESS_CONTROL_EXPOSE_HEADERS not in response.headers

        # Process according to CORS 6.1.4.
        # Set exposed headers (server headers exposed to client) before
        # setting any other headers.
        if options.expose_headers == "*":
            # Expose all headers that are set in response.
            exposed_headers = \
                frozenset(response.headers.keys()) - _SIMPLE_RESPONSE_HEADERS
            response.headers[hdrs.ACCESS_CONTROL_EXPOSE_HEADERS] = \
                ",".join(exposed_headers)

        elif options.expose_headers:
            # Expose predefined list of headers.
            response.headers[hdrs.ACCESS_CONTROL_EXPOSE_HEADERS] = \
                ",".join(options.expose_headers)

        # Process according to CORS 6.1.3.
        # Set allowed origin.
        response.headers[hdrs.ACCESS_CONTROL_ALLOW_ORIGIN] = origin
        if options.allow_credentials:
            # Set allowed credentials.
            response.headers[hdrs.ACCESS_CONTROL_ALLOW_CREDENTIALS] = _TRUE

Example 12

Project: aiohttp-cors
License: View license
Source File: cors_config.py
    @asyncio.coroutine
    def _preflight_handler(self, request: web.Request):
        """CORS preflight request handler"""

        # Handle according to part 6.2 of the CORS specification.

        origin = request.headers.get(hdrs.ORIGIN)
        if origin is None:
            # Terminate CORS according to CORS 6.2.1.
            raise web.HTTPForbidden(
                text="CORS preflight request failed: "
                     "origin header is not specified in the request")

        # CORS 6.2.3. Doing it out of order is not an error.
        request_method = self._parse_request_method(request)

        # CORS 6.2.5. Doing it out of order is not an error.

        try:
            config = \
                yield from self._router_adapter.get_preflight_request_config(
                    request, origin, request_method)
        except KeyError:
            raise web.HTTPForbidden(
                text="CORS preflight request failed: "
                     "request method {!r} is not allowed "
                     "for {!r} origin".format(request_method, origin))

        if not config:
            # No allowed origins for the route.
            # Terminate CORS according to CORS 6.2.1.
            raise web.HTTPForbidden(
                text="CORS preflight request failed: "
                     "no origins are allowed")

        options = config.get(origin, config.get("*"))
        if options is None:
            # No configuration for the origin - deny.
            # Terminate CORS according to CORS 6.2.2.
            raise web.HTTPForbidden(
                text="CORS preflight request failed: "
                     "origin '{}' is not allowed".format(origin))

        # CORS 6.2.4
        request_headers = self._parse_request_headers(request)

        # CORS 6.2.6
        if options.allow_headers == "*":
            pass
        else:
            disallowed_headers = request_headers - options.allow_headers
            if disallowed_headers:
                raise web.HTTPForbidden(
                    text="CORS preflight request failed: "
                         "headers are not allowed: {}".format(
                             ", ".join(disallowed_headers)))

        # Ok, CORS actual request with specified in the preflight request
        # parameters is allowed.
        # Set appropriate headers and return 200 response.

        response = web.Response()

        # CORS 6.2.7
        response.headers[hdrs.ACCESS_CONTROL_ALLOW_ORIGIN] = origin
        if options.allow_credentials:
            # Set allowed credentials.
            response.headers[hdrs.ACCESS_CONTROL_ALLOW_CREDENTIALS] = _TRUE

        # CORS 6.2.8
        if options.max_age is not None:
            response.headers[hdrs.ACCESS_CONTROL_MAX_AGE] = \
                str(options.max_age)

        # CORS 6.2.9
        # TODO: more optimal for client preflight request cache would be to
        # respond with ALL allowed methods.
        response.headers[hdrs.ACCESS_CONTROL_ALLOW_METHODS] = request_method

        # CORS 6.2.10
        if request_headers:
            # Note: case of the headers in the request is changed, but this
            # shouldn't be a problem, since the headers should be compared in
            # the case-insensitive way.
            response.headers[hdrs.ACCESS_CONTROL_ALLOW_HEADERS] = \
                ",".join(request_headers)

        return response

Example 13

    @asyncio.coroutine
    def get_preflight_request_config(
            self,
            preflight_request: web.Request,
            origin: str,
            requested_method: str):
        assert self.is_preflight_request(preflight_request)

        resource = self._request_resource(preflight_request)
        resource_config = self._resource_config[resource]
        defaulted_config = collections.ChainMap(
            resource_config.default_config,
            self._default_config)

        options = defaulted_config.get(origin, defaulted_config.get("*"))
        if options is not None and options.is_method_allowed(requested_method):
            # Requested method enabled for CORS in defaults, override it with
            # explicit route configuration (if any).
            route_config = resource_config.method_config.get(
                requested_method, {})

        else:
            # Requested method is not enabled in defaults.
            # Enable CORS for it only if explicit configuration exists.
            route_config = resource_config.method_config[requested_method]

        defaulted_config = collections.ChainMap(route_config, defaulted_config)

        return defaulted_config

Example 14

Project: aiohttp-cors
License: View license
Source File: test_real_browser.py
    @asyncio.coroutine
    def start_servers(self):
        test_page_path = pathlib.Path(__file__).with_name("test_page.html")

        @asyncio.coroutine
        def handle_test_page(request: web.Request) -> web.StreamResponse:
            with test_page_path.open("r", encoding="utf-8") as f:
                return web.Response(
                    text=f.read(),
                    headers={hdrs.CONTENT_TYPE: "text/html"})

        @asyncio.coroutine
        def handle_no_cors(request: web.Request) -> web.StreamResponse:
            return web.Response(
                text="""{"type": "no_cors.json"}""",
                headers={hdrs.CONTENT_TYPE: "application/json"})

        @asyncio.coroutine
        def handle_resource(request: web.Request) -> web.StreamResponse:
            return web.Response(
                text="""{"type": "resource"}""",
                headers={hdrs.CONTENT_TYPE: "application/json"})

        @asyncio.coroutine
        def handle_servers_addresses(
                request: web.Request) -> web.StreamResponse:
            servers_addresses = \
                {name: descr.url for name, descr in self.servers.items()}
            return web.Response(
                text=json.dumps(servers_addresses))

        # For most resources:
        # "origin" server has no CORS configuration.
        # "allowing" server explicitly allows CORS requests to "origin" server.
        # "denying" server explicitly disallows CORS requests to "origin"
        # server.
        # "free_for_all" server allows CORS requests for all origins server.
        # "no_cors" server has no CORS configuration.
        cors_server_names = ["allowing", "denying", "free_for_all"]
        server_names = cors_server_names + ["origin", "no_cors"]

        for server_name in server_names:
            assert server_name not in self.servers
            self.servers[server_name] = _ServerDescr()

        # Create applications.
        for server_descr in self.servers.values():
            server_descr.app = web.Application()

        # Server test page from origin server.
        self.servers["origin"].app.router.add_route(
            "GET", "/", handle_test_page)
        self.servers["origin"].app.router.add_route(
            "GET", "/servers_addresses", handle_servers_addresses)

        # Add routes to all servers.
        for server_name in server_names:
            app = self.servers[server_name].app
            app.router.add_route("GET", "/no_cors.json", handle_no_cors)
            app.router.add_route("GET", "/cors_resource", handle_resource,
                                 name="cors_resource")

        # Start servers.
        for server_name, server_descr in self.servers.items():
            handler = server_descr.app.make_handler()
            server = yield from create_server(handler, self.loop)
            server_descr.handler = handler
            server_descr.server = server

            hostaddr, port = server.sockets[0].getsockname()
            server_descr.url = "http://{host}:{port}".format(
                host=hostaddr, port=port)

            self._logger.info("Started server '%s' at '%s'",
                              server_name, server_descr.url)

        cors_default_configs = {
            "allowing": {
                self.servers["origin"].url:
                    ResourceOptions(
                        allow_credentials=True, expose_headers="*",
                        allow_headers="*")
            },
            "denying": {
                # Allow requests to other than "origin" server.
                self.servers["allowing"].url:
                    ResourceOptions(
                        allow_credentials=True, expose_headers="*",
                        allow_headers="*")
            },
            "free_for_all": {
                "*":
                    ResourceOptions(
                        allow_credentials=True, expose_headers="*",
                        allow_headers="*")
            },
        }

        # Configure CORS.
        for server_name, server_descr in self.servers.items():
            default_config = cors_default_configs.get(server_name)
            if default_config is None:
                continue
            server_descr.cors = setup(
                server_descr.app, defaults=default_config)

        # Add CORS routes.
        for server_name in cors_server_names:
            server_descr = self.servers[server_name]
            # TODO: Starting from aiohttp 0.21.0 name-based access returns
            # Resource, not Route. Manually get route while aiohttp_cors
            # doesn't support configuring for Resources.
            resource = server_descr.app.router["cors_resource"]
            route = next(iter(resource))
            if self.use_resources:
                server_descr.cors.add(resource)
                server_descr.cors.add(route)

            else:
                server_descr.cors.add(route)

Example 15

Project: sockjs
License: View license
Source File: test_base.py
    def make_request(self, method, path, query_params={}, headers=None,
                     match_info=None):
        if query_params:
            path = '%s?%s' % (path, urllib.parse.urlencode(query_params))

        # Ported from:
        # https://github.com/KeepSafe/aiohttp/blob/fa06acc2392c516491bdb25301ad3ef2b700ff5f/tests/test_web_websocket.py#L21-L45  # noqa
        self.app = mock.Mock()
        self.app._debug = False
        if headers is None:
            headers = CIMultiDict(
                {'HOST': 'server.example.com',
                 'UPGRADE': 'websocket',
                 'CONNECTION': 'Upgrade',
                 'SEC-WEBSOCKET-KEY': 'dGhlIHNhbXBsZSBub25jZQ==',
                 'ORIGIN': 'http://example.com',
                 'SEC-WEBSOCKET-PROTOCOL': 'chat, superchat',
                 'SEC-WEBSOCKET-VERSION': '13'})

        message = make_raw_request_message(method, path, headers)
        self.payload = mock.Mock()
        self.transport = mock.Mock()
        self.reader = mock.Mock()
        self.writer = mock.Mock()
        self.app.loop = self.loop
        self.app.on_response_prepare = Signal(self.app)
        req = Request(self.app, message, self.payload,
                      self.transport, self.reader, self.writer)
        req._match_info = match_info
        return req

Example 16

Project: Flask-aiohttp
License: View license
Source File: handler.py
    @abc.abstractmethod
    def handle_request(self, request: aiohttp.web.Request):
        pass

Example 17

Project: Flask-aiohttp
License: View license
Source File: handler.py
    @asyncio.coroutine
    def __call__(self, request: aiohttp.web.Request):
        response = yield from self.handle_request(request)
        return response

Example 18

Project: Flask-aiohttp
License: View license
Source File: handler.py
    @asyncio.coroutine
    def handle_request(self, request: aiohttp.web.Request) -> \
            aiohttp.web.StreamResponse:
        """Handle WSGI request with aiohttp"""

        # Use aiohttp's WSGI implementation
        protocol = WSGIServerHttpProtocol(request.app, True)
        protocol.transport = request.transport

        # Build WSGI Response
        environ = protocol.create_wsgi_environ(request, request.content)

        # Create responses
        ws = aiohttp.web.WebSocketResponse()
        response = aiohttp.web.StreamResponse()

        #: Write delegate
        @asyncio.coroutine
        def write(data):
            yield from response.write(data)

        #: EOF Write delegate
        @asyncio.coroutine
        def write_eof():
            yield from response.write_eof()

        # WSGI start_response function
        def start_response(status, headers, exc_info=None):
            if exc_info:
                raise exc_info[1]

            status_parts = status.split(' ', 1)
            status = int(status_parts.pop(0))
            reason = status_parts[0] if status_parts else None

            response.set_status(status, reason=reason)

            for name, value in headers:
                response.headers[name] = value

            response.start(request)

            return write
        if is_websocket_request(request):
            ws.start(request)

            # WSGI HTTP responses in websocket are meaningless.
            def start_response(status, headers, exc_info=None):
                if exc_info:
                    raise exc_info[1]
                ws.start(request)
                return []

            @asyncio.coroutine
            def write(data):
                return

            @asyncio.coroutine
            def write_eof():
                return

            response = ws
        else:
            ws = None

        # Add websocket response to WSGI environment
        environ['wsgi.websocket'] = ws

        # Run WSGI app
        response_iter = self.wsgi(environ, start_response)

        try:
            iterator = iter(response_iter)

            wsgi_response = []
            try:
                item = next(iterator)
            except StopIteration as stop:
                try:
                    iterator = iter(stop.value)
                except TypeError:
                    pass
                else:
                    wsgi_response = iterator
            else:
                if isinstance(item, bytes):
                    # This is plain WSGI response iterator
                    wsgi_response = itertools.chain([item], iterator)
                else:
                    # This is coroutine
                    yield item
                    wsgi_response = yield from iterator
            for item in wsgi_response:
                yield from write(item)

            yield from write_eof()
        finally:
            if hasattr(response_iter, 'close'):
                response_iter.close()

        # Return selected response
        return response