Esempio n. 1
0
    def test_dummy_setup_roundtrip(self):
        """Test a dummy configuration with a message round-trip."""
        app = web.Application()
        setup(app)

        app.router.add_route("GET", "/", handler)

        yield from self.create_server(app)

        response = yield from aiohttp.request("GET", self.server_url)
        self.assertEqual(response.status, 200)
        data = yield from response.text()

        self.assertEqual(data, TEST_BODY)
Esempio n. 2
0
    def test_static_route(self):
        """Test a static route with CORS."""
        app = web.Application()
        cors = setup(app, defaults={
            "*": ResourceOptions(
                allow_credentials=True,
                expose_headers="*",
                allow_methods="*",
                allow_headers=("Content-Type", "X-Header"),
            )
        })

        test_static_path = pathlib.Path(__file__).parent
        cors.add(app.router.add_static("/static", test_static_path, name='static'))

        yield from self.create_server(app)

        response = yield from aiohttp.request(
            "OPTIONS", URL(self.server_url) / "static/test_page.html",
            headers={
                hdrs.ORIGIN: "http://example.org",
                hdrs.ACCESS_CONTROL_REQUEST_METHOD: "OPTIONS",
                hdrs.ACCESS_CONTROL_REQUEST_HEADERS: "content-type",
            }
        )
        data = yield from response.text()
        self.assertEqual(response.status, 200)
        self.assertEqual(data, '')
Esempio n. 3
0
File: app.py Progetto: pubnub/python
async def make_app(loop):
    app = web.Application()
    # (r"/listen", ListenHandler),

    cors = aiohttp_cors.setup(app, defaults={
        "*": aiohttp_cors.ResourceOptions(
            allow_credentials=True,
            expose_headers="*",
            allow_headers="*",
        )
    })

    app.router.add_route('GET', '/app_key', app_key_handler)
    app.router.add_route('GET', '/subscription/add', add_channel_handler)
    app.router.add_route('GET', '/subscription/remove', remove_channel_handler)
    app.router.add_route('GET', '/subscription/list', list_channels_handler)
    app.router.add_route('GET', '/publish/sync', publish_sync)
    app.router.add_route('GET', '/publish/async', publish_sync)
    app.router.add_route('GET', '/publish/async2', publish_sync)

    for route in list(app.router.routes()):
        cors.add(route)

    srv = await loop.create_server(app.make_handler(), '0.0.0.0', 8080)
    return srv
Esempio n. 4
0
    def test_main(self):
        # This tests corresponds to example from documentation.
        # If you updating it, don't forget to update documentation.

        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",
                })

        app = web.Application()

        # `cors` object will store CORS configuration for the application.
        cors = aiohttp_cors.setup(app)

        # To enable CORS processing for specific route you need to add
        # that route to the CORS configuration object and specify it's
        # CORS options.
        cors.add(
            app.router.add_route("GET", "/hello", handler), {
                "http://client.example.org": aiohttp_cors.ResourceOptions(
                    allow_credentials=True,
                    expose_headers=("X-Custom-Server-Header",),
                    allow_headers=("X-Requested-With", "Content-Type"),
                    max_age=3600,
                )
            })
Esempio n. 5
0
async def start():
    await communionserver._start()
    app = web.Application()
    app.add_routes([
        web.get('/{tail:.*}', handler),
    ])

    # Configure default CORS settings.
    cors = aiohttp_cors.setup(app, defaults={
        "*": aiohttp_cors.ResourceOptions(
                allow_credentials=True,
                expose_headers="*",
                allow_headers="*",
                allow_methods=["GET", ]
            )
    })

    # Configure CORS on all routes.
    for route in list(app.router.routes()):
        cors.add(route)

    runner = web.AppRunner(app)
    await runner.setup()
    site = web.TCPSite(runner, ADDRESS, PORT)
    await site.start()
Esempio n. 6
0
def server():
    """
        Starts main dispatch server
    """
    allowed_domains = []

    opts = docopt(__doc__, version="0.0.1")

    logging.basicConfig(level=getattr(logging, opts.pop('loglevel')))
    r.set_loop_type("asyncio")

    with suppress(KeyError):
        allowed_domains = opts.pop('allowed_domains').split(',')
        allowed_domains = [a.strip() for a in allowed_domains]

    app = web.Application()
    app['rethinkdb'] = opts

    default_opts = aiohttp_cors.ResourceOptions(
        allow_credentials=True, expose_headers="*", allow_headers="*")
    cors = aiohttp_cors.setup(app, defaults={
        dom: default_opts for dom in allowed_domains})

    cors.add(cors.add(app.router.add_resource('/')).add_route('*', Dispatcher))
    cors.add(cors.add(app.router.add_resource('/ws')).add_route('*', wshandle))
    web.run_app(app)
Esempio n. 7
0
    def test_preflight_request_multiple_routers_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, "")
Esempio n. 8
0
    async def serve_rest(self):
        global web
        from aiohttp import web
        import aiohttp_cors
        app = web.Application()
        app.add_routes([
            web.get('/{tail:.*}', self._handle_get),
            web.put('/{tail:.*}', self._handle_put),
            web.patch('/{tail:.*}', self._handle_equilibrate),
        ])

        # Configure default CORS settings.
        cors = aiohttp_cors.setup(app, defaults={
            "*": aiohttp_cors.ResourceOptions(
                    allow_credentials=True,
                    expose_headers="*",
                    allow_headers="*",
                    allow_methods=["GET", "PATCH", "PUT"]
                )
        })

        # Configure CORS on all routes.
        for route in list(app.router.routes()):
            cors.add(route)

        runner = web.AppRunner(app)
        await runner.setup()
        site = web.TCPSite(runner, self.address, self.rest_port) #TODO: try more ports
        await site.start()
        print("Opened the seamless REST server at port {0}".format(self.rest_port))
Esempio n. 9
0
    def __init__(self, hass, development, api_password, ssl_certificate,
                 ssl_key, server_host, server_port, cors_origins,
                 use_x_forwarded_for, 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.use_x_forwarded_for = use_x_forwarded_for
        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
Esempio n. 10
0
    def init_routes(self):
        # add the cors handler
        self.cors = aiohttp_cors.setup(self.app)

        # for each route that was registered
        for route in self._routes:
            # add the corresponding http endpoint
            self.add_http_endpoint(**route)

        # add the schema reference to graphql handler
        self.api_request_handler_class.service = self

        # add a cors resource
        api_resource = self.cors.add(self.app.router.add_resource("/"))
        # add the root api handler
        self.cors.add(
            api_resource.add_route("GET", self.api_request_handler_class),
            {
                "": aiohttp_cors.ResourceOptions(
                    allow_credentials=True,
                    expose_headers=("X-Custom-Server-Header",),
                    allow_headers=("X-Requested-With", "Content-Type"),
                    max_age=3600,
                )
            }
        )
        # add the static file urls
        self.app.router.add_static('/graphiql/static/', api_endpoint_static)
        # add the graphiql endpoint
        self.add_http_endpoint('/graphiql', GraphiQLRequestHandler)
Esempio n. 11
0
def setup_cors(app, origins):
    """Setup cors."""
    import aiohttp_cors

    cors = aiohttp_cors.setup(app, defaults={
        host: aiohttp_cors.ResourceOptions(
            allow_headers=ALLOWED_CORS_HEADERS,
            allow_methods='*',
        ) for host in origins
    })

    @asyncio.coroutine
    def cors_startup(app):
        """Initialize cors when app starts up."""
        cors_added = set()

        for route in list(app.router.routes()):
            if hasattr(route, 'resource'):
                route = route.resource
            if route in cors_added:
                continue
            cors.add(route)
            cors_added.add(route)

    app.on_startup.append(cors_startup)
Esempio n. 12
0
    def _run_preflight_requests_tests(self, tests_descriptions, use_resources):
        """Runs CORS preflight requests based on the passed tests descriptions.
        """

        @asyncio.coroutine
        def run_test(test):
            """Run single test"""

            response = yield from aiohttp.options(
                self.server_url + "resource",
                headers=test.get("request_headers", {}))
            self.assertEqual(response.status, test.get("response_status", 200))
            response_text = yield from response.text()
            in_response = test.get("in_response")
            if in_response is not None:
                self.assertIn(in_response, response_text)
            else:
                self.assertEqual(response_text, "")

            for header_name, header_value in test.get(
                    "in_response_headers", {}).items():
                self.assertEqual(
                    response.headers.get(header_name),
                    header_value)

            for header_name in test.get("not_in_request_headers", {}).items():
                self.assertNotIn(header_name, response.headers)

        for test_descr in tests_descriptions:
            with self.subTest(group_name=test_descr["name"]):
                app = web.Application()
                cors = setup(app, defaults=test_descr["defaults"])

                if use_resources:
                    resource = cors.add(app.router.add_resource("/resource"))
                    cors.add(resource.add_route("GET", handler),
                             test_descr["route_config"])

                else:
                    cors.add(
                        app.router.add_route("GET", "/resource", handler),
                        test_descr["route_config"])

                yield from self.create_server(app)

                try:
                    for test_data in test_descr["tests"]:
                        with self.subTest(name=test_data["name"]):
                            yield from run_test(test_data)
                finally:
                    yield from self.shutdown_server()
Esempio n. 13
0
def create_app(
    default_cors_options: CORSOptions
) -> Tuple[web.Application, Iterable[WebMiddleware]]:
    app = web.Application()
    app.on_startup.append(init)
    app.on_shutdown.append(shutdown)
    app['api_versions'] = (4, 5)
    app['prefix'] = 'logs/error'
    cors = aiohttp_cors.setup(app, defaults=default_cors_options)
    cors.add(app.router.add_route('POST', '', append))
    cors.add(app.router.add_route('GET', '', list_logs))
    cors.add(app.router.add_route('POST', r'/{log_id}/clear', mark_cleared))

    return app, []
Esempio n. 14
0
def init_app():
    app = web.Application()
    cors = aiohttp_cors.setup(app)
    resource = cors.add(app.router.add_resource('/'))
    resource2 = cors.add(app.router.add_resource('/examples'))

    cors.add(resource.add_route("GET", GetChars), {
        "*": aiohttp_cors.ResourceOptions(allow_credentials=True),
    })
    cors.add(resource2.add_route("GET", GetExamples), {
        "*": aiohttp_cors.ResourceOptions(allow_credentials=True),
    })

    return app
Esempio n. 15
0
def init_web_app(message_queue, port=8080):

    '''
    create an Application instance and register the request handler on a particular HTTP method and path:
    '''
    #asyncio.set_event_loop(asyncio.new_event_loop())

    app = web.Application()

    # `aiohttp_cors.setup` returns `aiohttp_cors.CorsConfig` instance.
    # The `cors` instance will store CORS configuration for the
    # application.
    cors = aiohttp_cors.setup(app, defaults={
    "*": aiohttp_cors.ResourceOptions( # TODO: CHANGE "*" To server IP
            allow_credentials=True,
            expose_headers=('access-control-allow-origin','content-type','x-csrftoken'),
            allow_headers=('access-control-allow-origin','content-type','x-csrftoken'),
        )
    })

    # Web Applications can have context 
    # https://stackoverflow.com/questions/40616145/shared-state-with-aiohttp-web-server 
    app['message_queue'] = message_queue

    app.add_routes([
        web.get('/', hello),
        web.post('/post', post_handler),
    ])

    for route in list(app.router.routes()):
        cors.add(route)

    #resource = cors.add(app.router.add_resource("/post"))
    #cors.add(route)
    #    route = cors.add(
    #    resource.add_route("POST", post_handler), {
    #        # "http://client.example.org" 
    #        "*": aiohttp_cors.ResourceOptions(
    #            allow_credentials=True,
    #            expose_headers='*',
    #            allow_headers='*',
    #            #expose_headers=("Access-Control-Allow-Origin",),
    #            #allow_headers=("Access-Control-Allow-Origin", "Content-Type: application/json"),
    #            max_age=3600,
    #        )
    #        }
    #    )
    
    #After that, run the application by run_app() call:
    web.run_app(app, port=port)
Esempio n. 16
0
def create_app(
    default_cors_options: CORSOptions
) -> Tuple[web.Application, Iterable[WebMiddleware]]:
    app = web.Application()
    app['prefix'] = 'events'
    app['api_versions'] = (3, 4)
    app.on_shutdown.append(events_shutdown)
    cors = aiohttp_cors.setup(app, defaults=default_cors_options)
    add_route = app.router.add_route
    app.cleanup_ctx.append(events_app_ctx)
    cors.add(add_route('GET', r'/background-task',
                       push_background_task_events))
    cors.add(add_route('GET', r'/session', push_session_events))
    return app, []
Esempio n. 17
0
def setup_cors(app: web.Application):
    cors = aiohttp_cors.setup(app)

    resource = cors.add(app.router.add_resource("/get_structure_info"))
    route = cors.add(
        resource.add_route("GET", get_structure_info), {
            "*":
            aiohttp_cors.ResourceOptions(
                allow_credentials=True,
                expose_headers=("X-Custom-Server-Header", ),
                allow_headers=("X-Requested-With", "Content-Type"),
                max_age=3600,
            )
        })
Esempio n. 18
0
def routes(app):
    cors = aiohttp_cors.setup(app,
                              defaults={
                                  "*":
                                  aiohttp_cors.ResourceOptions(
                                      allow_methods=("*"),
                                      allow_credentials=True,
                                      expose_headers=("*", ),
                                      allow_headers=("*"),
                                      max_age=3600,
                                  )
                              })

    cors.add(app.router.add_get('/oauth/{type}', auth.oauth))
Esempio n. 19
0
async def main(start_port: int,
               show_timing: bool = False,
               container_name: str = "Simple_client"):
    global temp_message
    global temp_data
    global agent
    genesis = await default_genesis_txns()
    if not genesis:
        print("Error retrieving ledger genesis transactions")
        sys.exit(1)
    try:
        log_status(
            "#7 Provision an agent and wallet, get back configuration details")
        label = container_name
        agent = ClientAgent(label,
                            start_port,
                            start_port + 1,
                            genesis_data=genesis,
                            timing=show_timing)
        await agent.listen_webhooks(start_port + 2)

        with log_timer("Startup duration:"):
            await agent.start_process()
        log_msg("Admin url is at:", agent.admin_url)
        log_msg("Endpoint url is at:", agent.endpoint)
        app = web.Application()

        app.add_routes([
            web.post('/input_invitation', handle_input_invitation),
        ])

        cors = aiohttp_cors.setup(
            app,
            defaults={
                "*":
                aiohttp_cors.ResourceOptions(
                    allow_credentials=True,
                    expose_headers="*",
                    allow_headers="*",
                    allow_methods="*",
                )
            },
        )
        for route in app.router.routes():
            cors.add(route)

        return app
    except Exception:
        print("Error when starting to run server!!")
Esempio n. 20
0
async def main(start_port: int, show_timing: bool = False):
    global agent
    genesis = await default_genesis_txns()
    agent = None
    if not genesis:
        print("Error retrieving ledger genesis transactions")
        sys.exit(1)
    try:
        agent = CredentialIssuerAgent(start_port,
                                      start_port + 1,
                                      genesis_data=genesis,
                                      timing=show_timing)
        await agent.listen_webhooks(start_port + 2)
        await agent.register_did()
        with log_timer("Startup duration:"):
            await agent.start_process()
        log_msg("Admin url is at:", agent.admin_url)
        log_msg("Endpoint url is at:", agent.endpoint)

        app = web.Application()

        app.add_routes([
            web.get('/create_invitation', handle_create_invitation),
            web.post('/create_schema_cred_def',
                     handle_create_schema_credential_definition),
            web.post('/send_credential_offer', handle_send_credential_offer),
            web.get('/issue_credential', handle_issue_credential),
            web.get('/get_connection_list', handle_get_connection_list),
            web.get('/get_cred_def_list', handle_get_cred_def_list),
        ])

        cors = aiohttp_cors.setup(
            app,
            defaults={
                "*":
                aiohttp_cors.ResourceOptions(
                    allow_credentials=True,
                    expose_headers="*",
                    allow_headers="*",
                    allow_methods="*",
                )
            },
        )
        for route in app.router.routes():
            cors.add(route)

        return app
    except Exception:
        print("Error when starting to run server!!")
def create_app():
    logging.basicConfig(level=logging.DEBUG)

    app = web.Application(middlewares=[
        web_middlewares.normalize_path_middleware(append_slash=True),
    ],
                          client_max_size=4096**2)

    app.update(name='producer', settings=settings)

    # setup Jinja2 template renderer; jinja2 contains various loaders, can also try PackageLoader etc.
    aiohttp_jinja2.setup(app,
                         loader=jinja2.FileSystemLoader(
                             str(settings.PROJECT_ROOT / 'static')))

    # get credentials of the correct environment
    for key, value in get_postgres_credentials(
            settings.ENVIRONMENT)._asdict().items():
        setattr(app['settings'], key, value)

    # create db connection on startup, shutdown on exit
    app.on_startup.append(on_startup)
    app.on_cleanup.append(close_pg)

    # setup views and routes
    setup_routes(app)

    # setup middlewares
    # setup_middlewares(app)

    # setup aiojobs scheduler
    setup_aiojobs(app)

    # Configure default CORS settings.
    cors = aiohttp_cors.setup(app,
                              defaults={
                                  "*":
                                  aiohttp_cors.ResourceOptions(
                                      allow_credentials=True,
                                      expose_headers="*",
                                      allow_headers="*",
                                  )
                              })

    # Configure CORS on all routes.
    for route in list(app.router.routes()):
        cors.add(route)

    return app
Esempio n. 22
0
    def initialize(self):

        try:
            self.info = {}
            self.serverApp = web.Application()
            self.cors = aiohttp_cors.setup(self.serverApp,
                                           defaults={
                                               "*":
                                               aiohttp_cors.ResourceOptions(
                                                   allow_credentials=True,
                                                   expose_headers="*",
                                                   allow_methods='*',
                                                   allow_headers="*")
                                           })

            self.cors.add(
                self.serverApp.router.add_get('/state', self.state_handler))
            self.cors.add(
                self.serverApp.router.add_get('/volume/{zone}/{volume}',
                                              self.volume_handler))
            self.cors.add(
                self.serverApp.router.add_get('/power/{zone}/{power}',
                                              self.power_handler))
            self.cors.add(
                self.serverApp.router.add_get('/input/{zone}/{input}',
                                              self.input_handler))
            #self.cors.add(self.serverApp.router.add_get('/mute/{zone}/{mute}', self.mute_handler))
            self.runner = aiohttp.web.AppRunner(self.serverApp)
            self.loop.run_until_complete(self.runner.setup())

            #ssl_cert = self.config.cert
            #ssl_key = self.config.key
            #self.ssl_context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
            #self.ssl_context.load_cert_chain(str(ssl_cert), str(ssl_key))

            self.site = web.TCPSite(
                self.runner, self.config.rest_address,
                self.config.api_port)  # ssl_context=self.ssl_context)
            logger.info('.. Starting mca webserver at http://%s:%s' %
                        (self.config.rest_address, self.config.api_port))
            self.loop.run_until_complete(self.site.start())
            return True
        except socket.gaierror:
            logger.error('!! Error - DNS or network down during intialize.',
                         exc_info=True)
            return False
        except:
            logger.error('!! Error starting REST server', exc_info=True)
            return False
Esempio n. 23
0
def create_app(test_db_uri: Optional[str] = None):
    app = connexion.AioHttpApp(__name__, port=5000, specification_dir="", only_one_api=True)
    config = Config()

    spec_path = Path(__file__).parent / "api-spec.yaml"
    spec, operation_parameters = load_api_spec(spec_path, version=__version__, components=[BaseType])
    if config.SCRIPT_NAME:
        spec["servers"] = [{"url": config.SCRIPT_NAME}]
    
    app.add_api(
        spec,
        options={"swagger_ui": True, "middlewares": [compression_middleware, set_schema,]},
        resolver=AppResolver(operation_parameters),
        pass_context_arg_name="request",
    )

    aiohttp_app: aiohttp.web.Application = app.app
    aiohttp_app._client_max_size = config.MAX_REQUEST_SIZE
    aiohttp_app.add_routes([web.get("/", swaggr_ui_redirect)])
    aiohttp_app["HTTPS"] = config.HTTPS
    aiohttp_app["config"] = config
    # register_login_handlers(aiohttp_app, config.AUTH_SERVICE_URL)

    cors_options = aiohttp_cors.ResourceOptions(
        allow_credentials=True, expose_headers="*", allow_headers="*", allow_methods=["DELETE", "GET", "PATCH", "POST"]
    )
    origins = ["http://localhost:8080"]
    cors = aiohttp_cors.setup(app.app, defaults={origin: cors_options for origin in origins})

    for route in app.app.router.routes():
        cors.add(route)

    if config.SCRIPT_NAME:
        app.app._router = RouterSubpathMiddleware(app.app.router, config.SCRIPT_NAME or "")

    
    async def on_startup(app: web.Application):
        if test_db_uri:
            uri = test_db_uri
        else:
            uri = config.SQLALCHEMY_DATABASE_URI
        app["engine"] = await gino.create_engine(uri)
        from .models import db

        db.bind = app["engine"]

    aiohttp_app.on_startup.append(on_startup)

    return app
Esempio n. 24
0
def apply_cors(app, url):
    cors = aiohttp_cors.setup(app,
                              defaults={
                                  url:
                                  aiohttp_cors.ResourceOptions(
                                      allow_credentials=False,
                                      expose_headers="*",
                                      allow_headers="*",
                                  ),
                              })

    for route in app.router.routes():
        cors.add(route)

    return app
Esempio n. 25
0
def setup_cors(app):
    cors = aiohttp_cors.setup(app,
                              defaults={
                                  "*":
                                  aiohttp_cors.ResourceOptions(
                                      allow_credentials=True,
                                      expose_headers="*",
                                      allow_headers="*",
                                  )
                              })

    for route in list(app.router.routes()):
        cors.add(route)

    return cors
Esempio n. 26
0
 def aio_cors(self, app, **kw):
     """
     aio_http不支持跨域,这是是跨域插件
     """
     # Configure default CORS settings.
     cors = aiohttp_cors.setup(app,
                               defaults={
                                   self._cors_url:
                                   aiohttp_cors.ResourceOptions(
                                       allow_credentials=True,
                                       expose_headers="*",
                                       allow_headers="*",
                                   )
                               })
     return cors
Esempio n. 27
0
def create_app():
    app = web.Application()
    cors = aiohttp_cors.setup(app, defaults={
        "*": aiohttp_cors.ResourceOptions(allow_credentials=True, expose_headers="*", allow_headers="*",)
    })
    setup_routes(app)
    for route in list(app.router.routes()):
        cors.add(route)

    setup_swagger(app=app,
                  description='An extensible Aiohttp Restful API template',
                  title='Aiohttp API',
                  api_version='v1',
                  swagger_url='api/v1/docs')
    return app
Esempio n. 28
0
async def create_app():
    app = web.Application()
    app.router.add_get('/health', index)
    setup_routes(app)
    cors = aiohttp_cors.setup(app, defaults={
        "*": aiohttp_cors.ResourceOptions(
            allow_credentials=True,
            expose_headers="*",
            allow_headers="*",
            allow_methods=["GET", "PUT", "POST", "DELETE", "PATCH", "OPTIONS"]
        )
    })
    for route in list(app.router.routes()):
        cors.add(route)
    return app
Esempio n. 29
0
    def _configure_cors(self, app: web.Application):
        cors = aiohttp_cors.setup(app,
                                  defaults={
                                      "*":
                                      aiohttp_cors.ResourceOptions(
                                          allow_credentials=True,
                                          expose_headers="*",
                                          allow_headers="*",
                                      )
                                  })

        for route in list(app.router.routes()):
            cors.add(route)

        return app
Esempio n. 30
0
def setup_cors(app):
    # `aiohttp_cors.setup` returns `aiohttp_cors.CorsConfig` instance.
    # The `cors` instance will store CORS configuration for the
    # application.
    cors = aiohttp_cors.setup(
        app,
        defaults={
            # Allow all to read all CORS-enabled resources from
            # *.
            "*": aiohttp_cors.ResourceOptions(),
        })

    # Configure CORS on all routes.
    for route in list(app.router.routes()):
        cors.add(route)
Esempio n. 31
0
def setup_routes(app):
    app.add_routes((web.view('/youtube/storedvideos', youtube.StoredVideos),
                    web.view('/youtube/search', youtube.SearchVideos)))

    cors = aiohttp_cors.setup(app,
                              defaults={
                                  '*':
                                  aiohttp_cors.ResourceOptions(
                                      allow_credentials=True,
                                      expose_headers='*',
                                      allow_headers='*')
                              })

    for route in list(app.router.routes()):
        cors.add(route, webview=True)
Esempio n. 32
0
def add_routes(app):
    cors = aiohttp_cors.setup(app,
                              defaults={
                                  "*":
                                  aiohttp_cors.ResourceOptions(
                                      allow_credentials=True,
                                      expose_headers="*",
                                      allow_headers="*",
                                  )
                              })

    resource = cors.add(app.router.add_resource("/play"))
    cors.add(resource.add_route("POST", play))

    app.router.add_route("GET", "/healthcheck", healthcheck)
def create_app(default_cors_options: CORSOptions) -> Tuple[web.Application, Iterable[WebMiddleware]]:
    app = web.Application()
    app.on_startup.append(init)
    app.on_shutdown.append(shutdown)
    app['api_versions'] = (4, 5)
    app['prefix'] = 'template/cluster'
    cors = aiohttp_cors.setup(app, defaults=default_cors_options)
    cors.add(app.router.add_route('POST', '', create))
    cors.add(app.router.add_route('GET', '', list_template))
    template_resource = cors.add(app.router.add_resource(r'/{template_id}'))
    cors.add(template_resource.add_route('GET', get))
    cors.add(template_resource.add_route('PUT', put))
    cors.add(template_resource.add_route('DELETE', delete))

    return app, []
Esempio n. 34
0
def set_cors(server):
    """Set CORS rules."""
    # Configure CORS settings
    cors = aiohttp_cors.setup(server,
                              defaults={
                                  "*":
                                  aiohttp_cors.ResourceOptions(
                                      allow_credentials=True,
                                      expose_headers="*",
                                      allow_headers="*",
                                  )
                              })
    # Apply CORS to endpoints
    for route in list(server.router.routes()):
        cors.add(route)
Esempio n. 35
0
def init_app(argv=None) -> web.Application:
    app = web.Application(middlewares=[
        HttpLoggerForAIOHTTP(
            url=os.environ.get("USAGE_LOGGERS_URL",
                               "http://localhost:4001/message"),
            rules="include debug",
        )
    ])
    cors = aiohttp_cors.setup(app)

    init_config(app, argv)
    init_routes(app, cors)
    app.on_startup.extend([init_database])
    app.on_cleanup.extend([close_database])
    return app
Esempio n. 36
0
 def __init__(self, bot: CustomClient):
     self.bot = bot
     self.app = web.Application()
     self.routes = web.RouteTableDef()
     self.site: web.TCPSite
     self.cors = aiohttp_cors.setup(self.app,
                                    defaults={
                                        "*":
                                        aiohttp_cors.ResourceOptions(
                                            allow_credentials=True,
                                            expose_headers="*",
                                            allow_headers="*",
                                        )
                                    })
     self.bot.loop.create_task(self.run_api())
Esempio n. 37
0
def create_app(
    default_cors_options: CORSOptions
) -> Tuple[web.Application, Iterable[WebMiddleware]]:
    app = web.Application()
    app.on_startup.append(init)
    app.on_shutdown.append(shutdown)
    app['api_versions'] = (4, 5)
    app['prefix'] = 'domain-config'
    cors = aiohttp_cors.setup(app, defaults=default_cors_options)
    cors.add(app.router.add_route('POST', '/dotfiles', create))
    cors.add(app.router.add_route('GET', '/dotfiles', list_or_get))
    cors.add(app.router.add_route('PATCH', '/dotfiles', update))
    cors.add(app.router.add_route('DELETE', '/dotfiles', delete))

    return app, []
Esempio n. 38
0
def serve(argv):
    app = aiohttp.web.Application()
    cors = aiohttp_cors.setup(app)
    resource = cors.add(app.router.add_resource(config.get_url_path()))
    route = resource.add_route('GET', gateway.websocket_rabbitmq_gateway)
    cors.add(
        route,
        {
            origin: aiohttp_cors.ResourceOptions(
                allow_credentials=True,
            )
            for origin in config.get_cors_allowed_origins()
        }
    )
    return app
Esempio n. 39
0
def init_routes(app):
    app.router.add_route('*', '/', index)
    app.router.add_route('*', '/graphiql', gqil_view, name='graphiql')

    cors = aiohttp_cors.setup(app)
    gql_resource = cors.add(
        app.router.add_resource("/graphql"), {
            "*":
            aiohttp_cors.ResourceOptions(expose_headers="*",
                                         allow_headers="*",
                                         allow_credentials=True,
                                         allow_methods=["POST", "PUT", "GET"]),
        })

    gql_resource.add_route("POST", gql_view)
Esempio n. 40
0
def allow_cors(app):
    cors = aiohttp_cors.setup(app,
                              defaults={
                                  "*":
                                  aiohttp_cors.ResourceOptions(
                                      allow_credentials=True,
                                      expose_headers="*",
                                      allow_methods="*",
                                      allow_headers="*",
                                      max_age=3600)
                              })

    for route in list(app.router.routes()):
        logger.info(f'Adding cors to {route.method} {route.handler}')
        cors.add(route)
Esempio n. 41
0
def escape_cross_origin_block(app):
    cors = aiohttp_cors.setup(
        app,
        defaults={
            "*":
            aiohttp_cors.ResourceOptions(
                # Access-Control-Allow-Origin
                allow_credentials=True,
                expose_headers="*",
                allow_headers=("X-Requested-With", "Content-Type",
                               "Authorization", "Content-Length"),
                allow_methods=['POST', 'GET'])
        })
    for resource in app.router.resources():
        cors.add(resource)
Esempio n. 42
0
    def _run_preflight_requests_tests(self, tests_descriptions, use_resources):
        """Runs CORS preflight requests based on the passed tests descriptions.
        """
        @asyncio.coroutine
        def run_test(test):
            """Run single test"""

            response = yield from self.session.options(
                self.server_url + "resource",
                headers=test.get("request_headers", {}))
            self.assertEqual(response.status, test.get("response_status", 200))
            response_text = yield from response.text()
            in_response = test.get("in_response")
            if in_response is not None:
                self.assertIn(in_response, response_text)
            else:
                self.assertEqual(response_text, "")

            for header_name, header_value in test.get("in_response_headers",
                                                      {}).items():
                self.assertEqual(response.headers.get(header_name),
                                 header_value)

            for header_name in test.get("not_in_request_headers", {}).items():
                self.assertNotIn(header_name, response.headers)

        for test_descr in tests_descriptions:
            with self.subTest(group_name=test_descr["name"]):
                app = web.Application()
                cors = setup(app, defaults=test_descr["defaults"])

                if use_resources:
                    resource = cors.add(app.router.add_resource("/resource"))
                    cors.add(resource.add_route("GET", handler),
                             test_descr["route_config"])

                else:
                    cors.add(app.router.add_route("GET", "/resource", handler),
                             test_descr["route_config"])

                yield from self.create_server(app)

                try:
                    for test_data in test_descr["tests"]:
                        with self.subTest(name=test_data["name"]):
                            yield from run_test(test_data)
                finally:
                    yield from self.shutdown_server()
Esempio n. 43
0
def setup_cors(app, origins):
    """Set up CORS."""
    import aiohttp_cors

    cors = aiohttp_cors.setup(app,
                              defaults={
                                  host: aiohttp_cors.ResourceOptions(
                                      allow_headers=ALLOWED_CORS_HEADERS,
                                      allow_methods='*',
                                  )
                                  for host in origins
                              })

    cors_added = set()

    def _allow_cors(route, config=None):
        """Allow CORS on a route."""
        if hasattr(route, 'resource'):
            path = route.resource
        else:
            path = route

        path = path.canonical

        if path in cors_added:
            return

        cors.add(route, config)
        cors_added.add(path)

    app['allow_cors'] = lambda route: _allow_cors(
        route, {
            '*':
            aiohttp_cors.ResourceOptions(
                allow_headers=ALLOWED_CORS_HEADERS,
                allow_methods='*',
            )
        })

    if not origins:
        return

    async def cors_startup(app):
        """Initialize CORS when app starts up."""
        for route in list(app.router.routes()):
            _allow_cors(route)

    app.on_startup.append(cors_startup)
Esempio n. 44
0
    def test_defaults(self):
        # This tests corresponds to example from documentation.
        # If you updating it, don't forget to update documentation.

        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)
Esempio n. 45
0
def setup_cors(app, origins):
    """Set up CORS."""
    import aiohttp_cors

    cors = aiohttp_cors.setup(app, defaults={
        host: aiohttp_cors.ResourceOptions(
            allow_headers=ALLOWED_CORS_HEADERS,
            allow_methods='*',
        ) for host in origins
    })

    cors_added = set()

    def _allow_cors(route, config=None):
        """Allow CORS on a route."""
        if hasattr(route, 'resource'):
            path = route.resource
        else:
            path = route

        path = path.canonical

        if path in cors_added:
            return

        cors.add(route, config)
        cors_added.add(path)

    app['allow_cors'] = lambda route: _allow_cors(route, {
        '*': aiohttp_cors.ResourceOptions(
            allow_headers=ALLOWED_CORS_HEADERS,
            allow_methods='*',
        )
    })

    if not origins:
        return

    async def cors_startup(app):
        """Initialize CORS when app starts up."""
        for route in list(app.router.routes()):
            _allow_cors(route)

    app.on_startup.append(cors_startup)
Esempio n. 46
0
    def _run_simple_requests_tests(self, tests_descriptions):
        """Runs CORS simple requests (without a preflight request) based
        on the passed tests descriptions.
        """

        @asyncio.coroutine
        def run_test(test):
            """Run single test"""

            response = yield from aiohttp.get(
                self.server_url + "resource",
                headers=test.get("request_headers", {}))
            self.assertEqual(response.status, 200)
            self.assertEqual((yield from response.text()), TEST_BODY)

            for header_name, header_value in test.get(
                    "in_response_headers", {}).items():
                with self.subTest(header_name=header_name):
                    self.assertEqual(
                        response.headers.get(header_name),
                        header_value)

            for header_name in test.get("not_in_request_headers", {}).items():
                self.assertNotIn(header_name, response.headers)

        for test_descr in tests_descriptions:
            with self.subTest(group_name=test_descr["name"]):
                app = web.Application()
                cors = setup(app, defaults=test_descr["defaults"])

                cors.add(
                    app.router.add_route("GET", "/resource", handler),
                    test_descr["route_config"])

                yield from self.create_server(app)

                try:
                    for test_data in test_descr["tests"]:
                        with self.subTest(name=test_data["name"]):
                            yield from run_test(test_data)
                finally:
                    yield from self.shutdown_server()
Esempio n. 47
0
    def __init__(self, hass, development, api_password, ssl_certificate,
                 ssl_key, server_host, server_port, cors_origins,
                 use_x_forwarded_for, trusted_networks,
                 login_threshold, is_ban_enabled):
        """Initialize the WSGI Home Assistant server."""
        import aiohttp_cors

        middlewares = [auth_middleware, staticresource_middleware]

        if is_ban_enabled:
            middlewares.insert(0, ban_middleware)

        self.app = web.Application(middlewares=middlewares, loop=hass.loop)
        self.app['hass'] = hass
        self.app[KEY_USE_X_FORWARDED_FOR] = use_x_forwarded_for
        self.app[KEY_TRUSTED_NETWORKS] = trusted_networks
        self.app[KEY_BANS_ENABLED] = is_ban_enabled
        self.app[KEY_LOGIN_THRESHOLD] = login_threshold
        self.app[KEY_DEVELOPMENT] = development

        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._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
Esempio n. 48
0
 def create_app(self, tasks_queue):
     self.app = web.Application(loop=self.loop, middlewares=(middleware,))
     self.app[ASEXOR_SESSION] = dict()
     session = AsexorBackendSession(tasks_queue, loop=self.app.loop)
     
     
     res = self.app.router.add_resource('/')        
     route_get=res.add_route('POST', session.handle_call)
     route_post=res.add_route('GET', session.handle_messages)
     
     if Config.LP.ENABLE_CORS:
         
     
         cors = aiohttp_cors.setup(self.app, defaults={
                      Config.LP.CORS_ORIGIN : aiohttp_cors.ResourceOptions(
                             allow_credentials= Config.LP.CORS_ALLOW_CREDENTIAL,
                             expose_headers= Config.LP.CORS_EXPOSE_HEADERS,
                             allow_headers= Config.LP.CORS_ALLOW_HEADERS,
                         )
                 })
         cors.add(res)
         cors.add(route_get)
         cors.add(route_post)
Esempio n. 49
0
def configure():
    app = aiohttp.web.Application()

    # Pull configuration out of the environment
    app["settings"] = {
        "endpoint": os.environ["CONVEYOR_ENDPOINT"],
        "docs_bucket": os.environ["DOCS_BUCKET"],
    }

    # Setup a HTTP session for our clients to share connections with and
    # register a shutdown callback to close the session.
    app["http.session"] = aiohttp.ClientSession(
        loop=asyncio.get_event_loop(),
        headers={"User-Agent": "conveyor"},
    )
    app["boto.session"] = aiobotocore.get_session(
        loop=asyncio.get_event_loop(),
    )
    app.on_shutdown.append(session_close)

    app["tasks"] = []

    app["redirects"] = {}
    _fetch_redirects_task = asyncio.ensure_future(
        redirects_refresh_task(app),
        loop=asyncio.get_event_loop(),
    )

    app.on_shutdown.append(cancel_tasks)

    # Allow cross-origin GETs by default
    cors = aiohttp_cors.setup(app, defaults={
            "*": aiohttp_cors.ResourceOptions(
                allow_methods="GET",
            )
    })

    # Add routes and views to our application
    cors.add(app.router.add_route(
        "GET",
        "/packages/{python_version}/{project_l}/{project_name}/{filename}",
        redirect,
    ))
    app.router.add_route(
        "HEAD",
        "/packages/{python_version}/{project_l}/{project_name}/{filename}",
        redirect,
    )
    cors.add(app.router.add_route(
        "GET",
        "/packages/{tail:.*}",
        not_found,
    ))
    cors.add(app.router.add_route(
        "GET",
        "/packages",
        not_found,
    ))

    app.router.add_route(
        "GET",
        "/_health/",
        health,
    )
    app.router.add_route(
        "GET",
        "/_health",
        health,
    )

    # Add Documentation routes
    app.router.add_route(
        "GET",
        "/",
        index,
    )
    app.router.add_route(
        "HEAD",
        "/",
        index,
    )
    app.router.add_route(
        "GET",
        "/{project_name}/{path:.*}",
        documentation,
    )
    app.router.add_route(
        "GET",
        "/{project_name}",
        documentation_top,
    )

    return app
Esempio n. 50
0
    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()

        server_sockets = {}

        # Create applications and sockets.
        for server_name, server_descr in self.servers.items():
            server_descr.app = web.Application()

            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            sock.bind(("127.0.0.1", 0))
            sock.listen(10)
            server_sockets[server_name] = sock

            hostaddr, port = sock.getsockname()
            server_descr.url = "http://{host}:{port}".format(
                host=hostaddr, port=port)

        # 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")

        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)

        # 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,
                                              sock=server_sockets[server_name])
            server_descr.handler = handler
            server_descr.server = server

            self._logger.info("Started server '%s' at '%s'",
                              server_name, server_descr.url)
Esempio n. 51
0
        for movie in person.known_for
        ])
    return payload


def format_datetime(datetime_):
    """Convert datetime object to something JSON-serializable."""
    if datetime_ is None:
        return None
    return datetime_.strftime('%Y-%m-%dT%H:%M:%SZ')


if __name__ == '__main__':
    tmdb_client = TMDbClient.from_env()
    app = web.Application()
    cors = setup(app, defaults={
        'https://known-for-web.cfapps.pez.pivotal.io': ResourceOptions(),
        'http://localhost:4200': ResourceOptions(),
    })

    for route, func in [
        ('/api/person', random_person),
        ('/api/search', search),
        ('/mock/api/person', mock_random_person),
        ('/mock/api/search', mock_search),
        ('/api/config', config),
    ]:
        route = cors.add(app.router.add_route('GET', route, func))

    web.run_app(app, port=getenv('PORT', 8080))
Esempio n. 52
0
    def run(self):
        """
        Starts the server.
        """

        server_logger = logging.getLogger('aiohttp.server')
        # In debug mode we don't use the standard request log but a more complete in response.py
        if log.getEffectiveLevel() == logging.DEBUG:
            server_logger.setLevel(logging.CRITICAL)

        logger = logging.getLogger("asyncio")
        logger.setLevel(logging.ERROR)

        if sys.platform.startswith("win"):
            loop = asyncio.get_event_loop()
            # Add a periodic callback to give a chance to process signals on Windows
            # because asyncio.add_signal_handler() is not supported yet on that platform
            # otherwise the loop runs outside of signal module's ability to trap signals.

            def wakeup():
                loop.call_later(0.5, wakeup)
            loop.call_later(0.5, wakeup)

        server_config = Config.instance().get_section_config("Server")

        ssl_context = None
        if server_config.getboolean("ssl"):
            if sys.platform.startswith("win"):
                log.critical("SSL mode is not supported on Windows")
                raise SystemExit
            ssl_context = self._create_ssl_context(server_config)

        self._loop = asyncio.get_event_loop()
        # Asyncio will raise error if coroutine is not called
        self._loop.set_debug(True)

        for key, val in os.environ.items():
            log.debug("ENV %s=%s", key, val)

        self._app = aiohttp.web.Application()
        # Background task started with the server
        self._app.on_startup.append(self._on_startup)

        # Allow CORS for this domains
        cors = aiohttp_cors.setup(self._app, defaults={
            # Default web server for web gui dev
            "http://127.0.0.1:8080": aiohttp_cors.ResourceOptions(expose_headers="*", allow_headers="*"),
            "http://localhost:8080": aiohttp_cors.ResourceOptions(expose_headers="*", allow_headers="*"),
            "http://gns3.github.io": aiohttp_cors.ResourceOptions(expose_headers="*", allow_headers="*")
        })

        PortManager.instance().console_host = self._host

        for method, route, handler in Route.get_routes():
            log.debug("Adding route: {} {}".format(method, route))
            cors.add(self._app.router.add_route(method, route, handler))
        for module in MODULES:
            log.debug("Loading module {}".format(module.__name__))
            m = module.instance()
            m.port_manager = PortManager.instance()

        log.info("Starting server on {}:{}".format(self._host, self._port))

        self._handler = self._app.make_handler()
        if self._run_application(self._handler, ssl_context) is False:
            self._loop.stop()
            return

        self._signal_handling()
        self._exit_handling()

        if server_config.getboolean("shell"):
            asyncio.async(self.start_shell())

        try:
            self._loop.run_forever()
        except TypeError as e:
            # This is to ignore an asyncio.windows_events exception
            # on Windows when the process gets the SIGBREAK signal
            # TypeError: async() takes 1 positional argument but 3 were given
            log.warning("TypeError exception in the loop {}".format(e))
        finally:
            if self._loop.is_running():
                self._loop.run_until_complete(self.shutdown_server())
Esempio n. 53
0
    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"),
            )
        })

        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(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())
        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: "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()))
Esempio n. 54
0
def serve_tiles(server_configs, layer_recipes, host, port):
    if not os.path.isfile(os.path.abspath(os.path.normpath(server_configs))):
        raise FileNotFoundError(('Server configuration file not found at {0}'.format(os.path.normpath(server_configs))))
    if not os.path.isdir(os.path.abspath(layer_recipes)):
        raise NotADirectoryError(('Layer recipes directory not found at {0}'.format(os.path.abspath(layer_recipes))))
    if not os.listdir(os.path.abspath(layer_recipes)):
        raise FileExistsError('Layer recipes directory is empty. Minimum 1 recipe is required.')

    # set the server configs
    Configs.init_server_configs(os.path.abspath(server_configs))

    # setup logging
    try:
        log_level = Configs.server['log_level'].upper()
    except KeyError:
        log_level = 'INFO'
    logging.basicConfig(stream=sys.stdout, level=log_level)
    logger = logging.getLogger(__name__)
    logger.info('STARTING ASYNCIO TILE SERVER APP')

    # load plugins
    logger.info('Loading plugins')
    Configs.plugins = Plugins
    Configs.plugins.load(Configs.server)

    # TODO: develop and test some 'before_load' plugin hooks
    Configs.plugins.hook('before_load', config=Configs.server)

    # set the layer configs
    for file in os.listdir(os.path.abspath(layer_recipes)):
        if file.endswith('.yaml') or file.endswith('.yml'):
            Configs.init_layer_recipes(os.path.join(os.path.abspath(layer_recipes), file))
    # check if a default recipe has been set in server configs. If so, set:
    try:
        default_recipe = Configs.server['default_recipe']
        if default_recipe[-4:] == '.yml':
            default_recipe = default_recipe[:-4]
        elif default_recipe[-5:] == '.yaml':
            default_recipe = default_recipe[:-5]
        Configs.recipes['default_recipe'] = Configs.recipes[default_recipe]
        Configs.recipes['default_recipe'].name = 'default_recipe_(same as {0})'.format(default_recipe)
        logger.info('Default recipe set to: {0}'.format(default_recipe))
    except KeyError:
        for first_recipe in Configs.recipes:
            logger.info('No default recipe set, using the first or only recipe as default: "{0}"'.format(first_recipe))
            Configs.recipes['default_recipe'] = Configs.recipes[first_recipe]
            break

    # TODO: develop and test some 'load' plugin hooks
    Configs.plugins.hook('load', config=Configs.server, recipes=Configs.recipes)

    # create server app
    logger.info('Creating the server app')
    app = web.Application()

    # setup url routes and corresponding handlers
    async def request_pbf(request):
        return await ServePBF.serve(request)
    app.router.add_route('GET', '/{layers}/{z}/{x}/{y}.pbf', request_pbf)
    app.router.add_route('GET', '/{recipe}/{layers}/{z}/{x}/{y}.pbf', request_pbf)
    app.router.add_route('GET', '/{layers}/{z}/{x}/{y}.mvt', request_pbf)
    app.router.add_route('GET', '/{recipe}/{layers}/{z}/{x}/{y}.mvt', request_pbf)

    async def request_geojson(request):
        return await ServeGeoJSON.serve(request)
    app.router.add_route('GET', '/{layers}/{z}/{x}/{y}.geojson', request_geojson)
    app.router.add_route('GET', '/{recipe}/{layers}/{z}/{x}/{y}.geojson', request_geojson)

    async def request_json(request):
        return await ServeJSON.serve(request)
    app.router.add_route('GET', '/{layers}/{z}/{x}/{y}.json', request_json)
    app.router.add_route('GET', '/{recipe}/{layers}/{z}/{x}/{y}.json', request_json)

    #TODO: confirm and test request_tilejson
    async def request_tilejson(request):
        content_type, body = TileJson.get()
        return web.Response(content_type=content_type, body=body.encode())
    app.router.add_route('GET', '/tilejson/mvt.json', request_tilejson)


    # configure CORS
    try:
        cors_config = Configs.server['CORS']
        logger.warning('CORS set to {0}'.format(cors_config))
    except KeyError:
        cors_config = '*'
        logger.warning('No CORS setting provided in server config file. Setting CORS to "*"')
    cors = aiohttp_cors.setup(app, defaults={
        cors_config: aiohttp_cors.ResourceOptions(
            allow_credentials=True,
            expose_headers=cors_config,
            allow_headers=cors_config
        )
    })
    for route in list(app.router.routes()):
        cors.add(route)


    # start the database pool
    logger.info('Creating the database pool')
    Configs.DB = DB  # create the DB instance
    loop = asyncio.get_event_loop()
    for db_name, dsn_string in Configs.server['databases'].items():
        loop.run_until_complete(Configs.DB.connect(db_name, dsn_string)) # this is an awaitable async so use run_until_complete

    # start the server
    logger.info('Starting the server app at host: {0}, port: {1}'.format(host, port))
    web.run_app(app, host=host, port=int(port))
Esempio n. 55
0
    def test_dummy_setup(self):
        """Test a dummy configuration."""
        app = web.Application()
        setup(app)

        yield from self.create_server(app)