aiohttp_cors.ResourceOptions

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

14 Examples 7

Example 1

Project: aiohttp-cors Source File: test_cors_config.py
Function: set_up
    def setUp(self):
        self.loop = asyncio.new_event_loop()
        self.app = web.Application(loop=self.loop)
        self.cors = CorsConfig(self.app, defaults={
            "*": ResourceOptions()
        })
        self.get_route = self.app.router.add_route(
            "GET", "/get_path", _handler)
        self.options_route = self.app.router.add_route(
            "OPTIONS", "/options_path", _handler)

Example 2

Project: aiohttp-cors Source File: test_urldispatcher_router_adapter.py
Function: set_up
    def setUp(self):
        self.loop = asyncio.new_event_loop()
        self.app = web.Application(loop=self.loop)

        self.adapter = ResourcesUrlDispatcherRouterAdapter(
            self.app.router, defaults={
                "*": ResourceOptions()
            })
        self.get_route = self.app.router.add_route(
            "GET", "/get_path", _handler)
        self.options_route = self.app.router.add_route(
            "OPTIONS", "/options_path", _handler)

Example 3

Project: aiohttp-cors Source File: test_basic_usage.py
    def test_defaults(self):
        # This tests corresponds to example from docuementation.
        # If you updating it, don't forget to update docuementation.

        import asyncio
        from aiohttp import web
        import aiohttp_cors

        @asyncio.coroutine
        def handler(request):
            return web.Response(
                text="Hello!",
                headers={
                    "X-Custom-Server-Header": "Custom data",
                })

        handler_post = handler
        handler_put = handler

        app = web.Application()

        # Example:

        cors = aiohttp_cors.setup(app, defaults={
                # Allow all to read all CORS-enabled resources from
                # http://client.example.org.
                "http://client.example.org": aiohttp_cors.ResourceOptions(),
            })

        # Enable CORS on routes.

        # According to defaults POST and PUT will be available only to
        # "http://client.example.org".
        hello_resource = cors.add(app.router.add_resource("/hello"))
        cors.add(hello_resource.add_route("POST", handler_post))
        cors.add(hello_resource.add_route("PUT", handler_put))

        # In addition to "http://client.example.org", GET request will be
        # allowed from "http://other-client.example.org" origin.
        cors.add(hello_resource.add_route("GET", handler), {
                "http://other-client.example.org":
                aiohttp_cors.ResourceOptions(),
            })

        # CORS will be enabled only on the resources added to `CorsConfig`,
        # so following resource will be NOT CORS-enabled.
        app.router.add_route("GET", "/private", handler)

Example 4

Project: aiohttp-cors Source File: test_main.py
Function: test_simple_default
    @asynctest
    @asyncio.coroutine
    def test_simple_default(self):
        """Test CORS simple requests with a route with the default
        configuration.

        The default configuration means that:
          * no credentials are allowed,
          * no headers are exposed,
          * no client headers are allowed.
        """

        client1 = "http://client1.example.org"
        client2 = "http://client2.example.org"
        client1_80 = "http://client1.example.org:80"
        client1_https = "https://client2.example.org"

        tests_descriptions = [
            {
                "name": "default",
                "defaults": None,
                "route_config":
                    {
                        client1: ResourceOptions(),
                    },
                "tests": [
                    {
                        "name": "no origin header",
                        "not_in_response_headers": {
                            hdrs.ACCESS_CONTROL_ALLOW_ORIGIN,
                            hdrs.ACCESS_CONTROL_EXPOSE_HEADERS,
                            hdrs.ACCESS_CONTROL_ALLOW_CREDENTIALS,
                        }
                    },
                    {
                        "name": "allowed origin",
                        "request_headers": {
                            hdrs.ORIGIN: client1,
                        },
                        "in_response_headers": {
                            hdrs.ACCESS_CONTROL_ALLOW_ORIGIN: client1,
                        },
                        "not_in_response_headers": {
                            hdrs.ACCESS_CONTROL_EXPOSE_HEADERS,
                            hdrs.ACCESS_CONTROL_ALLOW_CREDENTIALS,
                        }
                    },
                    {
                        "name": "not allowed origin",
                        "request_headers": {
                            hdrs.ORIGIN: client2,
                        },
                        "not_in_response_headers": {
                            hdrs.ACCESS_CONTROL_ALLOW_ORIGIN,
                            hdrs.ACCESS_CONTROL_EXPOSE_HEADERS,
                            hdrs.ACCESS_CONTROL_ALLOW_CREDENTIALS,
                        }
                    },
                    {
                        "name": "explicitly specified default port",
                        # CORS specification says, that origins may compared
                        # as strings, so "example.org:80" is not the same as
                        # "example.org".
                        "request_headers": {
                            hdrs.ORIGIN: client1_80,
                        },
                        "not_in_response_headers": {
                            hdrs.ACCESS_CONTROL_ALLOW_ORIGIN,
                            hdrs.ACCESS_CONTROL_EXPOSE_HEADERS,
                            hdrs.ACCESS_CONTROL_ALLOW_CREDENTIALS,
                        }
                    },
                    {
                        "name": "different scheme",
                        "request_headers": {
                            hdrs.ORIGIN: client1_https,
                        },
                        "not_in_response_headers": {
                            hdrs.ACCESS_CONTROL_ALLOW_ORIGIN,
                            hdrs.ACCESS_CONTROL_EXPOSE_HEADERS,
                            hdrs.ACCESS_CONTROL_ALLOW_CREDENTIALS,
                        }
                    },
                    ],
            },
        ]

        yield from self._run_simple_requests_tests(tests_descriptions, False)
        yield from self._run_simple_requests_tests(tests_descriptions, True)

Example 5

Project: aiohttp-cors Source File: test_main.py
    @asynctest
    @asyncio.coroutine
    def test_simple_with_credentials(self):
        """Test CORS simple requests with a route with enabled authorization.

        Route with enabled authorization must return
        Origin: <origin as requested, NOT "*">
        Access-Control-Allow-Credentials: true
        """

        client1 = "http://client1.example.org"
        client2 = "http://client2.example.org"

        credential_tests = [
            {
                "name": "no origin header",
                "not_in_response_headers": {
                    hdrs.ACCESS_CONTROL_ALLOW_ORIGIN,
                    hdrs.ACCESS_CONTROL_EXPOSE_HEADERS,
                    hdrs.ACCESS_CONTROL_ALLOW_CREDENTIALS,
                }
            },
            {
                "name": "allowed origin",
                "request_headers": {
                    hdrs.ORIGIN: client1,
                },
                "in_response_headers": {
                    hdrs.ACCESS_CONTROL_ALLOW_ORIGIN: client1,
                    hdrs.ACCESS_CONTROL_ALLOW_CREDENTIALS: "true",
                },
                "not_in_response_headers": {
                    hdrs.ACCESS_CONTROL_EXPOSE_HEADERS,
                }
            },
            {
                "name": "disallowed origin",
                "request_headers": {
                    hdrs.ORIGIN: client2,
                },
                "not_in_response_headers": {
                    hdrs.ACCESS_CONTROL_ALLOW_ORIGIN,
                    hdrs.ACCESS_CONTROL_EXPOSE_HEADERS,
                    hdrs.ACCESS_CONTROL_ALLOW_CREDENTIALS,
                }
            },
        ]

        tests_descriptions = [
            {
                "name": "route settings",
                "defaults": None,
                "route_config":
                    {
                        client1: ResourceOptions(allow_credentials=True),
                    },
                "tests": credential_tests,
            },
            {
                "name": "cors default settings",
                "defaults":
                    {
                        client1: ResourceOptions(allow_credentials=True),
                    },
                "route_config": None,
                "tests": credential_tests,
            },
        ]

        yield from self._run_simple_requests_tests(tests_descriptions, False)
        yield from self._run_simple_requests_tests(tests_descriptions, True)

Example 6

Project: aiohttp-cors Source File: test_main.py
    @asynctest
    @asyncio.coroutine
    def test_simple_expose_headers(self):
        """Test CORS simple requests with a route that exposes header."""

        client1 = "http://client1.example.org"
        client2 = "http://client2.example.org"

        tests_descriptions = [
            {
                "name": "default",
                "defaults": None,
                "route_config":
                    {
                        client1: ResourceOptions(
                            expose_headers=(SERVER_CUSTOM_HEADER_NAME,)),
                    },
                "tests": [
                    {
                        "name": "no origin header",
                        "not_in_response_headers": {
                            hdrs.ACCESS_CONTROL_ALLOW_ORIGIN,
                            hdrs.ACCESS_CONTROL_EXPOSE_HEADERS,
                            hdrs.ACCESS_CONTROL_ALLOW_CREDENTIALS,
                        }
                    },
                    {
                        "name": "allowed origin",
                        "request_headers": {
                            hdrs.ORIGIN: client1,
                        },
                        "in_response_headers": {
                            hdrs.ACCESS_CONTROL_ALLOW_ORIGIN: client1,
                            hdrs.ACCESS_CONTROL_EXPOSE_HEADERS:
                                SERVER_CUSTOM_HEADER_NAME,
                        },
                        "not_in_response_headers": {
                            hdrs.ACCESS_CONTROL_ALLOW_CREDENTIALS,
                        }
                    },
                    {
                        "name": "not allowed origin",
                        "request_headers": {
                            hdrs.ORIGIN: client2,
                        },
                        "not_in_response_headers": {
                            hdrs.ACCESS_CONTROL_ALLOW_ORIGIN,
                            hdrs.ACCESS_CONTROL_EXPOSE_HEADERS,
                            hdrs.ACCESS_CONTROL_ALLOW_CREDENTIALS,
                        }
                    },
                    ],
            },
        ]

        yield from self._run_simple_requests_tests(tests_descriptions, False)
        yield from self._run_simple_requests_tests(tests_descriptions, True)
        yield from self._run_simple_requests_tests(tests_descriptions, True)

Example 7

Project: aiohttp-cors Source File: test_main.py
    @asynctest
    @asyncio.coroutine
    def test_preflight_default(self):
        """Test CORS preflight requests with a route with the default
        configuration.

        The default configuration means that:
          * no credentials are allowed,
          * no headers are exposed,
          * no client headers are allowed.
        """

        client1 = "http://client1.example.org"
        client2 = "http://client2.example.org"

        tests_descriptions = [
            {
                "name": "default",
                "defaults": None,
                "route_config":
                    {
                        client1: ResourceOptions(),
                    },
                "tests": [
                    {
                        "name": "no origin",
                        "response_status": 403,
                        "in_response": "origin header is not specified",
                        "not_in_response_headers": {
                            hdrs.ACCESS_CONTROL_ALLOW_ORIGIN,
                            hdrs.ACCESS_CONTROL_ALLOW_CREDENTIALS,
                            hdrs.ACCESS_CONTROL_MAX_AGE,
                            hdrs.ACCESS_CONTROL_EXPOSE_HEADERS,
                            hdrs.ACCESS_CONTROL_ALLOW_METHODS,
                            hdrs.ACCESS_CONTROL_ALLOW_HEADERS,
                        },
                    },
                    {
                        "name": "no method",
                        "request_headers": {
                            hdrs.ORIGIN: client1,
                        },
                        "response_status": 403,
                        "in_response": "'Access-Control-Request-Method' "
                                       "header is not specified",
                        "not_in_response_headers": {
                            hdrs.ACCESS_CONTROL_ALLOW_ORIGIN,
                            hdrs.ACCESS_CONTROL_ALLOW_CREDENTIALS,
                            hdrs.ACCESS_CONTROL_MAX_AGE,
                            hdrs.ACCESS_CONTROL_EXPOSE_HEADERS,
                            hdrs.ACCESS_CONTROL_ALLOW_METHODS,
                            hdrs.ACCESS_CONTROL_ALLOW_HEADERS,
                        },
                    },
                    {
                        "name": "origin and method",
                        "request_headers": {
                            hdrs.ORIGIN: client1,
                            hdrs.ACCESS_CONTROL_REQUEST_METHOD: "GET",
                        },
                        "in_response_headers": {
                            hdrs.ACCESS_CONTROL_ALLOW_ORIGIN: client1,
                            hdrs.ACCESS_CONTROL_ALLOW_METHODS: "GET",
                        },
                        "not_in_response_headers": {
                            hdrs.ACCESS_CONTROL_ALLOW_CREDENTIALS,
                            hdrs.ACCESS_CONTROL_MAX_AGE,
                            hdrs.ACCESS_CONTROL_EXPOSE_HEADERS,
                            hdrs.ACCESS_CONTROL_ALLOW_HEADERS,
                        },
                    },
                    {
                        "name": "disallowed origin",
                        "request_headers": {
                            hdrs.ORIGIN: client2,
                            hdrs.ACCESS_CONTROL_REQUEST_METHOD: "GET",
                        },
                        "response_status": 403,
                        "in_response": "origin '{}' is not allowed".format(
                            client2),
                        "not_in_response_headers": {
                            hdrs.ACCESS_CONTROL_ALLOW_ORIGIN,
                            hdrs.ACCESS_CONTROL_ALLOW_CREDENTIALS,
                            hdrs.ACCESS_CONTROL_MAX_AGE,
                            hdrs.ACCESS_CONTROL_EXPOSE_HEADERS,
                            hdrs.ACCESS_CONTROL_ALLOW_METHODS,
                            hdrs.ACCESS_CONTROL_ALLOW_HEADERS,
                        },
                    },
                    {
                        "name": "disallowed method",
                        "request_headers": {
                            hdrs.ORIGIN: client1,
                            hdrs.ACCESS_CONTROL_REQUEST_METHOD: "POST",
                        },
                        "response_status": 403,
                        "in_response": "request method 'POST' is not allowed",
                        "not_in_response_headers": {
                            hdrs.ACCESS_CONTROL_ALLOW_ORIGIN,
                            hdrs.ACCESS_CONTROL_ALLOW_CREDENTIALS,
                            hdrs.ACCESS_CONTROL_MAX_AGE,
                            hdrs.ACCESS_CONTROL_EXPOSE_HEADERS,
                            hdrs.ACCESS_CONTROL_ALLOW_METHODS,
                            hdrs.ACCESS_CONTROL_ALLOW_HEADERS,
                        },
                    },
                    ],
            },
        ]

        yield from self._run_preflight_requests_tests(
            tests_descriptions, False)
        yield from self._run_preflight_requests_tests(
            tests_descriptions, True)

Example 8

Project: aiohttp-cors Source File: test_main.py
    @asynctest
    @asyncio.coroutine
    def test_preflight_request_multiple_routes_with_one_options(self):
        """Test CORS preflight handling on resource that is available through
        several routes.
        """
        app = web.Application()
        cors = setup(app, defaults={
            "*": ResourceOptions(
                allow_credentials=True,
                expose_headers="*",
                allow_headers="*",
            )
        })

        cors.add(app.router.add_route("GET", "/{name}", handler))
        cors.add(app.router.add_route("PUT", "/{name}", handler))

        yield from self.create_server(app)

        response = yield from aiohttp.request(
            "OPTIONS", self.server_url + "user",
            headers={
                hdrs.ORIGIN: "http://example.org",
                hdrs.ACCESS_CONTROL_REQUEST_METHOD: "PUT"
            }
        )
        self.assertEqual(response.status, 200)

        data = yield from response.text()
        self.assertEqual(data, "")

Example 9

Project: aiohttp-cors Source File: test_main.py
    @asynctest
    @asyncio.coroutine
    def test_preflight_request_multiple_routes_with_one_options_resource(self):
        """Test CORS preflight handling on resource that is available through
        several routes.
        """
        app = web.Application()
        cors = setup(app, defaults={
            "*": ResourceOptions(
                allow_credentials=True,
                expose_headers="*",
                allow_headers="*",
            )
        })

        resource = cors.add(app.router.add_resource("/{name}"))
        cors.add(resource.add_route("GET", handler))
        cors.add(resource.add_route("PUT", handler))

        yield from self.create_server(app)

        response = yield from aiohttp.request(
            "OPTIONS", self.server_url + "user",
            headers={
                hdrs.ORIGIN: "http://example.org",
                hdrs.ACCESS_CONTROL_REQUEST_METHOD: "PUT"
            }
        )
        self.assertEqual(response.status, 200)

        data = yield from response.text()
        self.assertEqual(data, "")

Example 10

Project: aiohttp-cors Source File: test_main.py
    @asynctest
    @asyncio.coroutine
    def test_preflight_request_headers_resource(self):
        """Test CORS preflight request handlers handling."""
        app = web.Application()
        cors = setup(app, defaults={
            "*": ResourceOptions(
                allow_credentials=True,
                expose_headers="*",
                allow_headers=("Content-Type", "X-Header"),
            )
        })

        cors.add(app.router.add_route("PUT", "/", handler))

        yield from self.create_server(app)

        response = yield from aiohttp.request(
            "OPTIONS", self.server_url,
            headers={
                hdrs.ORIGIN: "http://example.org",
                hdrs.ACCESS_CONTROL_REQUEST_METHOD: "PUT",
                hdrs.ACCESS_CONTROL_REQUEST_HEADERS: "content-type",
            }
        )
        self.assertEqual((yield from response.text()), "")
        self.assertEqual(response.status, 200)
        # Access-Control-Allow-Headers must be compared in case-insensitive
        # way.
        self.assertEqual(
            response.headers[hdrs.ACCESS_CONTROL_ALLOW_HEADERS].upper(),
            "content-type".upper())

        response = yield from aiohttp.request(
            "OPTIONS", self.server_url,
            headers={
                hdrs.ORIGIN: "http://example.org",
                hdrs.ACCESS_CONTROL_REQUEST_METHOD: "PUT",
                hdrs.ACCESS_CONTROL_REQUEST_HEADERS: "X-Header,content-type",
            }
        )
        self.assertEqual(response.status, 200)
        # Access-Control-Allow-Headers must be compared in case-insensitive
        # way.
        self.assertEqual(
            frozenset(response.headers[hdrs.ACCESS_CONTROL_ALLOW_HEADERS]
                      .upper().split(",")),
            {"X-Header".upper(), "content-type".upper()})
        self.assertEqual((yield from response.text()), "")

        response = yield from aiohttp.request(
            "OPTIONS", self.server_url,
            headers={
                hdrs.ORIGIN: "http://example.org",
                hdrs.ACCESS_CONTROL_REQUEST_METHOD: "PUT",
                hdrs.ACCESS_CONTROL_REQUEST_HEADERS: "content-type,Test",
            }
        )
        self.assertEqual(response.status, 403)
        self.assertNotIn(
            hdrs.ACCESS_CONTROL_ALLOW_HEADERS,
            response.headers)
        self.assertIn(
            "headers are not allowed: TEST",
            (yield from response.text()))

Example 11

Project: aiohttp-cors Source File: test_main.py
    @asynctest
    @asyncio.coroutine
    def test_preflight_request_headers(self):
        """Test CORS preflight request handlers handling."""
        app = web.Application()
        cors = setup(app, defaults={
            "*": ResourceOptions(
                allow_credentials=True,
                expose_headers="*",
                allow_headers=("Content-Type", "X-Header"),
            )
        })

        resource = cors.add(app.router.add_resource("/"))
        cors.add(resource.add_route("PUT", handler))

        yield from self.create_server(app)

        response = yield from aiohttp.request(
            "OPTIONS", self.server_url,
            headers={
                hdrs.ORIGIN: "http://example.org",
                hdrs.ACCESS_CONTROL_REQUEST_METHOD: "PUT",
                hdrs.ACCESS_CONTROL_REQUEST_HEADERS: "content-type",
            }
        )
        self.assertEqual((yield from response.text()), "")
        self.assertEqual(response.status, 200)
        # Access-Control-Allow-Headers must be compared in case-insensitive
        # way.
        self.assertEqual(
            response.headers[hdrs.ACCESS_CONTROL_ALLOW_HEADERS].upper(),
            "content-type".upper())

        response = yield from aiohttp.request(
            "OPTIONS", self.server_url,
            headers={
                hdrs.ORIGIN: "http://example.org",
                hdrs.ACCESS_CONTROL_REQUEST_METHOD: "PUT",
                hdrs.ACCESS_CONTROL_REQUEST_HEADERS: "X-Header,content-type",
            }
        )
        self.assertEqual(response.status, 200)
        # Access-Control-Allow-Headers must be compared in case-insensitive
        # way.
        self.assertEqual(
            frozenset(response.headers[hdrs.ACCESS_CONTROL_ALLOW_HEADERS]
                      .upper().split(",")),
            {"X-Header".upper(), "content-type".upper()})
        self.assertEqual((yield from response.text()), "")

        response = yield from aiohttp.request(
            "OPTIONS", self.server_url,
            headers={
                hdrs.ORIGIN: "http://example.org",
                hdrs.ACCESS_CONTROL_REQUEST_METHOD: "PUT",
                hdrs.ACCESS_CONTROL_REQUEST_HEADERS: "content-type,Test",
            }
        )
        self.assertEqual(response.status, 403)
        self.assertNotIn(
            hdrs.ACCESS_CONTROL_ALLOW_HEADERS,
            response.headers)
        self.assertIn(
            "headers are not allowed: TEST",
            (yield from response.text()))

Example 12

Project: aiohttp-cors Source File: test_real_browser.py
Function: start_servers
    @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 13

Project: aiohttp-cors Source File: test_urldispatcher_router_adapter.py
    def test_get_non_preflight_request_config(self):
        self.adapter.add_preflight_handler(
            self.get_route.resource, _handler)
        self.adapter.set_config_for_routing_entity(
            self.get_route.resource, {
                'http://example.org': ResourceOptions(),
            })

        self.adapter.add_preflight_handler(
            self.get_route, _handler)
        self.adapter.set_config_for_routing_entity(
            self.get_route, {
                'http://test.example.org': ResourceOptions(),
            })

        request = mock.Mock()

        with mock.patch('aiohttp_cors.urldispatcher_router_adapter.'
                        'ResourcesUrlDispatcherRouterAdapter.'
                        'is_cors_enabled_on_request'
                        ) as is_cors_enabled_on_request, \
            mock.patch('aiohttp_cors.urldispatcher_router_adapter.'
                       'ResourcesUrlDispatcherRouterAdapter.'
                       '_request_resource'
                       ) as _request_resource:
            is_cors_enabled_on_request.return_value = True
            _request_resource.return_value = self.get_route.resource

            self.assertEqual(
                self.adapter.get_non_preflight_request_config(request),
                {
                    '*': ResourceOptions(),
                    'http://example.org': ResourceOptions(),
                })

            request.method = 'GET'

            self.assertEqual(
                self.adapter.get_non_preflight_request_config(request),
                {
                    '*': ResourceOptions(),
                    'http://example.org': ResourceOptions(),
                    'http://test.example.org': ResourceOptions(),
                })

Example 14

Project: home-assistant Source File: http.py
    def __init__(self, hass, development, api_password, ssl_certificate,
                 ssl_key, server_host, server_port, cors_origins,
                 trusted_networks):
        """Initialize the WSGI Home Assistant server."""
        import aiohttp_cors

        self.app = web.Application(loop=hass.loop)
        self.hass = hass
        self.development = development
        self.api_password = api_password
        self.ssl_certificate = ssl_certificate
        self.ssl_key = ssl_key
        self.server_host = server_host
        self.server_port = server_port
        self.trusted_networks = trusted_networks
        self.event_forwarder = None
        self._handler = None
        self.server = None

        if cors_origins:
            self.cors = aiohttp_cors.setup(self.app, defaults={
                host: aiohttp_cors.ResourceOptions(
                    allow_headers=ALLOWED_CORS_HEADERS,
                    allow_methods='*',
                ) for host in cors_origins
            })
        else:
            self.cors = None

        # CACHE HACK
        _GZIP_FILE_SENDER.development = development