コード例 #1
0
 def start_server(loop):
     app = Application(loop=loop)
     app.router.add_route(*handler.route)
     routes = app.router.routes()._urls
     assert len(routes), routes
     srv = yield from loop.create_server(app.make_handler(), "localhost", 9000)
     return srv
コード例 #2
0
ファイル: clang.py プロジェクト: Shellu/clang
async def init(loop):
    app = Application(loop=loop)
    app['sockets'] = {}
    print("Connecting to DB...")
    app['db'] = await db.create_db()
    print("Connected.")

    # HTML endpoint
    app.router.add_route('GET', '/', api.index.index)

    # Admin dashboard app management endpoints
    app.router.add_route('GET', '/apps', api.apps.get_all_apps)
    app.router.add_route('GET', '/apps/{app_id}', api.apps.get_app)
    app.router.add_route('POST', '/apps', api.apps.create_app)
    app.router.add_route('DELETE', '/apps/{app_id}', api.apps.delete_app)

    # Http lib endpoints
    # app.router.add_route('GET', '/apps/{app_id}/channels', '')
    # app.router.add_route('GET', '/apps/{app_id}/channels/{channel_name}', '')
    # app.router.add_route('GET', '/apps/{app_id}/channels/{channel_name}/users', '')
    # app.router.add_route('POST', '/apps/{app_id}/events', '')

    # Websocket and message endpoints
    app.router.add_route('GET', '/ws/{channel}', api.message.ws_handler)
    app.router.add_route('POST', '/apps/{app_id}/events', api.message.msg_handler)

    root = os.path.dirname(os.path.abspath(__file__))
    here = root + '/client/dist/assets'
    app.router.add_static('/assets', here)

    logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.DEBUG)
    handler = app.make_handler(access_log=logging.getLogger('clang.access'))
    srv = await loop.create_server(handler, '127.0.0.1', 8040)
    print("Server started at http://127.0.0.1:8040")
    return app, srv, handler
コード例 #3
0
ファイル: client.py プロジェクト: petrjanda/pysk
    async def init(loop):
        app = Application(loop=loop)
        app.router.add_route('POST', '/query', handle)

        handler = app.make_handler()
        srv = await loop.create_server(handler, conf['http_hostname'], conf['http_port'])
        return srv, handler
コード例 #4
0
async def init(loop):
    app = Application(loop=loop)
    app.router.add_route('GET', '/', handle)

    srv = await loop.create_server(app.make_handler(),
                                   '127.0.0.1', 1337)
    print('Server started at http://127.0.0.1:1337')
    return srv
コード例 #5
0
def init(loop):
    app = Application(loop=loop, middlewares=[middleware_factory])
    app.router.add_route("GET", "/", handler)

    requests_handler = app.make_handler()
    srv = yield from loop.create_server(requests_handler, "127.0.0.1", 8080)
    print("Server started at http://127.0.0.1:8080")
    return srv, requests_handler
コード例 #6
0
def init(loop):
    app = Application(loop=loop)
    app.router.add_route('GET', '/', simple)

    handler = app.make_handler()
    srv = yield from loop.create_server(handler, '127.0.0.1', 8080)
    print("Server started at http://127.0.0.1:8080")
    return srv, handler
コード例 #7
0
ファイル: __main__.py プロジェクト: MartijnBraam/drush-queued
def webserver(loop):
    app = Application(loop=loop)

    app.router.add_route('GET', '/eventsource/', eventsource)

    handler = app.make_handler()
    srv = yield from loop.create_server(handler, '127.0.0.1', args.eventsource)
    logging.info("Eventsource started at http://127.0.0.1:{}".format(args.eventsource))
    return srv, handler
コード例 #8
0
ファイル: ipn.py プロジェクト: Avatarchik/netwrok-server
def init(loop):
    global handler
    app = Application(loop=loop)
    app.router.add_route('GET', '/', handle_get)
    app.router.add_route('POST', '/IPN', handle_ipn)

    handler = app.make_handler()
    srv = yield from loop.create_server(handler, '0.0.0.0', 8080)
    logging.info("IPN Server started at http://0.0.0.0:8080")
コード例 #9
0
ファイル: ws.py プロジェクト: tao12345666333/Talk-Is-Cheap
async def init(loop):
    app = Application(loop=loop)
    app['connections'] = {}
    app.router.add_route('GET', '/', ws_handler)

    handler = app.make_handler()
    srv = await loop.create_server(handler, '127.0.0.1', '8000')
    print("Server running on 127.0.0.1:8000")
    return app, srv, handler
コード例 #10
0
ファイル: web_ws.py プロジェクト: bossjones/etc-python
def init(loop):
    app = Application(loop=loop)
    app['sockets'] = []
    app.router.add_route('GET', '/wfb', wshandler)

    handler = app.make_handler()
    srv = yield from loop.create_server(handler, '127.0.0.1', 8001)
    print("Server started at http://127.0.0.1:8080")
    return app, srv, handler
コード例 #11
0
ファイル: app.py プロジェクト: JSFansw/wechatpy
def main(loop):
    app = Application(loop=loop)
    app.router.add_route('GET', '/', user_info)
    app.router.add_route('GET', '/group_id', user_group_id)

    handler = app.make_handler()
    srv = yield from loop.create_server(handler, '127.0.0.1', 8888)
    print("Server started at http://127.0.0.1:8888")
    return srv, handler
コード例 #12
0
ファイル: server.py プロジェクト: YGeeneY/tic_tac_toe
def init(loop):
    app = Application(middlewares=[session_middleware(
        EncryptedCookieStorage(SECRET_KEY))])
    setup_jinja(app, loader=FileSystemLoader(TEMPLATE_DIR))
    for route in routes:
        app.router.add_route(route['method'], route['url'], route['handler'], **route['kwargs_'])
    srv = yield from loop.create_server(
        app.make_handler(), '0.0.0.0', 8080)
    return srv
コード例 #13
0
ファイル: server.py プロジェクト: basti2342/aiohttp-json-rpc
def init(loop):
    app = Application(loop=loop)
    wsgi_handler = WSGIHandler(django_app)

    app.router.add_route('*', '/ws/myjrpc', MyJsonRpc)
    app.router.add_route('*', '/ws/mydajrpc', MyDjangoAuthJsonRpc)
    app.router.add_route('*', '/{path_info:.*}', wsgi_handler.handle_request)

    yield from loop.create_server(app.make_handler(), '', 8080)
コード例 #14
0
ファイル: web_ws.py プロジェクト: graingert/aiohttp
def init(loop):
    app = Application(loop=loop)
    app["sockets"] = []
    app.router.add_route("GET", "/", wshandler)

    handler = app.make_handler()
    srv = yield from loop.create_server(handler, "127.0.0.1", 8080)
    print("Server started at http://127.0.0.1:8080")
    return app, srv, handler
コード例 #15
0
ファイル: web_ws.py プロジェクト: cphyc/andremote
def init(loop, args):
    app = Application(loop=loop)
    app['sockets'] = []
    app.router.add_route('GET', '/', wsHandler)

    handler = app.make_handler()
    srv = yield from loop.create_server(handler, args.host, args.port)
    print("Server started at http://{}:{}".format(args.host, args.port))
    return app, srv, handler
コード例 #16
0
ファイル: server.py プロジェクト: krasch/spotbox
def init(loop, host, port):
    app = Application(loop=loop)
    app['sockets'] = []
    app.router.add_route('GET', '/ws', wshandler)
    app.router.add_route('GET', '/', redirect)
    app.router.add_static('/', '../ui/static')
    handler = app.make_handler()
    srv = yield from loop.create_server(handler, host, port)
    print("Server started at {}:{}".format(host, port))
    return app, srv, handler
コード例 #17
0
ファイル: web.py プロジェクト: user-dob/pyweb
    def init(self, loop):
        app = Application(loop=loop)

        for (method, rule, handler) in self.routes:
            app.router.add_route(method, rule, handler)

        handler = app.make_handler()
        srv = yield from loop.create_server(handler, self.host, self.port)

        return srv, handler
コード例 #18
0
ファイル: web_classview1.py プロジェクト: merrellb/aiohttp
async def init(loop):
    app = Application(loop=loop)
    app.router.add_route("GET", "/", index)
    app.router.add_route("GET", "/get", MyView)
    app.router.add_route("POST", "/post", MyView)

    handler = app.make_handler()
    srv = await loop.create_server(handler, "127.0.0.1", 8080)
    print("Server started at http://127.0.0.1:8080")
    return srv, handler
コード例 #19
0
async def init(loop):
    app = Application(loop=loop)
    app.router.add_get('/', index)
    app.router.add_get('/get', MyView)
    app.router.add_post('/post', MyView)

    handler = app.make_handler()
    srv = await loop.create_server(handler, '127.0.0.1', 8080)
    print("Server started at http://127.0.0.1:8080")
    return srv, handler
コード例 #20
0
ファイル: web_srv.py プロジェクト: bcl/aiohttp
def init(loop):
    app = Application(loop=loop)
    app.router.add_route('GET', '/', intro)
    app.router.add_route('GET', '/simple', simple)
    app.router.add_route('GET', '/change_body', change_body)
    app.router.add_route('GET', '/hello/{name}', hello)
    app.router.add_route('GET', '/hello', hello)

    srv = yield from loop.create_server(app.make_handler(), '127.0.0.1', 8080)
    print("Server started at http://127.0.0.1:8080")
    return srv
コード例 #21
0
ファイル: chat.py プロジェクト: hairychris/aiohttp-sse
def init(loop):
    app = Application(loop=loop)
    app["sockets"] = set()

    app.router.add_route("GET", "/chat", chat)
    app.router.add_route("POST", "/everyone", message)
    app.router.add_route("GET", "/subscribe", subscribe)

    handler = app.make_handler()
    srv = yield from loop.create_server(handler, "127.0.0.1", 8080)
    print("Server started at http://127.0.0.1:8080")
    return srv, handler
コード例 #22
0
ファイル: app.py プロジェクト: kunalprompt/kasync
def init(loop):
    app = Application(loop=loop)
    jinja2_setup(app, loader=FileSystemLoader('templates'))

    app.router.add_route('GET', '/name/{name}', get_name)
    app.router.add_route('POST', '/post', post_name)

    host = '0.0.0.0'
    port = environ.get('PORT', 8000)
    srv = yield from loop.create_server(app.make_handler(), host, port)
    print('Server started at http://{0}:{1}'.format(host, port))
    return srv
コード例 #23
0
ファイル: http.py プロジェクト: akheron/sinap
class HTTPModule(Module):
    export_as = 'http'

    def __init__(self, *args, **kwds):
        super().__init__(*args, **kwds)
        self._app = Application()
        self._server = None
        self._handler = None
        self._started = False

    def add_route(self, method, path, handler):
        self._app.router.add_route(method, path, handler)

        # Start when the first handlers are added
        self._maybe_start()

    def add_routes(self, routes):
        # routes is a list of (method, path, handler) tuples
        for method, path, handler in routes:
            self._app.router.add_route(method, path, handler)

        # Start when the first handlers are added
        self._maybe_start()

    def reverse_url(self, name, *args):
        baseurl = self.config.get('baseurl', '')
        return baseurl + self._app.reverse_url(name, *args)

    def _maybe_start(self):
        if not self._started:
            # Start when the first handlers are added
            self._started = True
            self.loop.create_task(self._start())

    async def _start(self):
        address = self.config.get('address', '127.0.0.1')
        port = self.config.get('port', 8000)

        self.log.info('Starting HTTP server at %s:%s' % (address, port))
        self._handler = self._app.make_handler()
        self._server = await self.loop.create_server(self._handler, address, port)

    def shutdown(self):
        if self._started:
            self.loop.create_task(self._shutdown_server())

    async def _shutdown_server(self):
        self._server.close()
        await self._server.wait_closed()
        await self._app.shutdown()
        await self._handler.finish_connections(1.0)
        await self._app.cleanup()
コード例 #24
0
ファイル: app.py プロジェクト: mariomcginley/BBS5
def init(loop):
    app = Application(loop=loop)
    aiohttp_jinja2.setup(app, loader=jinja2.FileSystemLoader('templates'))
    app['sockets'] = []
    app.router.add_static('/static', 'static')
    app.router.add_route('GET', '/', home)
    wshandler = WebsocketHandler()
    app.router.add_route('GET', '/ws', wshandler.handle)

    handler = app.make_handler()
    srv = yield from loop.create_server(handler, '127.0.0.1', 8080)
    print("Server started at http://127.0.0.1:8080")
    return app, srv, handler
コード例 #25
0
ファイル: app.py プロジェクト: bearstech/flowpanel
def init(loop):
    app = Application(middlewares=[auth_factory])
    app['redis'] = yield from asyncio_redis.Pool.create(host='127.0.0.1',
                                                        port=6379, poolsize=10)
    app.register_on_finish(close_redis)

    app.router.add_route('GET', '/', static)
    app.router.add_route('GET', '/static/{file}', static)
    app.router.add_route('GET', '/chaussette', websocket_handler)
    app.router.add_route('PUT', '/event/{user}', event)
    handler = app.make_handler()
    srv = yield from loop.create_server(handler, '0.0.0.0', 8080)
    return srv, handler, app
コード例 #26
0
ファイル: bus.py プロジェクト: pmittal1982/vyked
 def _create_http_service_host(self):
     if self._http_host:
         host_ip, host_port = self._http_host.socket_address
         ssl_context = self._http_host.ssl_context
         app = Application(loop=self._loop)
         for each in self._http_host.__ordered__:
             fn = getattr(self._http_host, each)
             if callable(fn) and getattr(fn, 'is_http_method', False):
                 for path in fn.paths:
                     app.router.add_route(fn.method, path, self.verify(fn))
         handler = app.make_handler()
         http_coro = self._loop.create_server(handler, host_ip, host_port, ssl=ssl_context)
         return self._loop.run_until_complete(http_coro)
コード例 #27
0
ファイル: routes.py プロジェクト: oohlaf/sprezz
def setup_routes(app: web.Application) -> None:
    app.add_routes([web.view('/connect/authorize', AuthorizeView),
                    web.view('/connect/token', TokenView),
                    web.view('/client', ClientListView),
                    web.view('/client/register', RegisterClientView),
                    web.view('/account', AccountListView),
                    web.view('/account/create', CreateAccountView),
                    web.view('/account/{username}', GetAccountView),
                    web.route('*', '/{tail:.*}', catch_all)])

    project_root = pathlib.Path(__file__).parent.parent
    app.add_routes([web.static('/static/',
                               path=project_root / 'static',
                               name='static')])
コード例 #28
0
    def init(self, loop):
        app = Application(loop=loop)

        # configure stream handler for console
        ch = logging.StreamHandler()
        self._logger.addHandler(ch)

        app.router.add_route('GET', '/', self._returnfaces)
        app.router.add_route('POST', '/detectface', self._detectface)


        handler = app.make_handler()
        srv = yield from loop.create_server(handler, self._address, self._port)
        self._logger.info("Server started on host {} / port {}".format(self._address, self._port))
        return srv, handler
コード例 #29
0
ファイル: conftest.py プロジェクト: djudman/myfeed
 def create(*, debug=False, ssl_ctx=None, proto='http'):
     nonlocal app, handler, srv
     app = Application(
         loop=loop,
         middlewares=[
             session_middleware(EncryptedCookieStorage(b'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'))
         ]
     )
     port = unused_port()
     handler = app.make_handler(debug=debug, keep_alive_on=False)
     srv = yield from loop.create_server(handler, '127.0.0.1', port,
                                                  ssl=ssl_ctx)
     if ssl_ctx:
         proto += 's'
     url = "{}://127.0.0.1:{}".format(proto, port)
     return app, url
コード例 #30
0
ファイル: host.py プロジェクト: technomaniac/vyked
 def _create_http_server(cls):
     if cls._http_service:
         host_ip, host_port = cls._http_service.socket_address
         ssl_context = cls._http_service.ssl_context
         app = Application(loop=asyncio.get_event_loop())
         for each in cls._http_service.__ordered__:
             fn = getattr(cls._http_service, each)
             if callable(fn) and getattr(fn, 'is_http_method', False):
                 for path in fn.paths:
                     app.router.add_route(fn.method, path, fn)
                     if cls._http_service.cross_domain_allowed:
                         app.router.add_route('options', path, cls._http_service.preflight_response)
         fn = getattr(cls._http_service, 'pong')
         app.router.add_route('GET', '/ping', fn)
         handler = app.make_handler()
         task = asyncio.get_event_loop().create_server(handler, host_ip, host_port, ssl=ssl_context)
         return asyncio.get_event_loop().run_until_complete(task)
コード例 #31
0
def post_process_routes(app: web.Application):
    """Amend swagger API."""

    # Add top-level tags description
    if "tags" not in app._state["swagger_dict"]:
        app._state["swagger_dict"]["tags"] = []
    app._state["swagger_dict"]["tags"].append(
        {
            "name": "credentials",
            "description": "Holder credential management",
            "externalDocs": {
                "description": "Overview",
                "url": ("https://w3c.github.io/vc-data-model/#credentials"),
            },
        }
    )
コード例 #32
0
def post_process_routes(app: web.Application):
    """Amend swagger API."""

    # Add top-level tags description
    if "tags" not in app._state["swagger_dict"]:
        app._state["swagger_dict"]["tags"] = []
    app._state["swagger_dict"]["tags"].append(
        {
            "name": "out-of-band",
            "description": "Out-of-band connections",
            "externalDocs": {
                "description": "Design",
                "url": SPEC_URI,
            },
        }
    )
コード例 #33
0
def post_process_routes(app: web.Application):
    """Amend swagger API."""

    # Add top-level tags description
    if "tags" not in app._state["swagger_dict"]:
        app._state["swagger_dict"]["tags"] = []
    app._state["swagger_dict"]["tags"].append({
        "name": "wallet",
        "description": "DID and tag policy management",
        "externalDocs": {
            "description":
            "Design",
            "url": ("https://github.com/hyperledger/indy-sdk/tree/"
                    "master/docs/design/003-wallet-storage"),
        },
    })
コード例 #34
0
def build_app() -> Application:
    app = Application()
    jinja = Environment(
        loader=FileSystemLoader(str(TEMPLATES_DIR)),
        enable_async=True,
    )
    app.router.add_get('/', render_view(jinja, 'index.html'))
    app.router.add_get('/html/', render_view(jinja, 'form.html'))
    app.router.add_post('/form/', render_view(jinja, 'data.html',
                                              process_form))
    app.router.add_get('/js/', render_view(jinja, 'js.html'))
    app.router.add_get('/cookie/',
                       render_view(jinja, 'data.html', process_cookies))
    app.router.add_get('/actions/', render_view(jinja, 'actions.html'))
    app.router.add_get('/screenshot/', render_view(jinja, 'screenshot.html'))
    return app
コード例 #35
0
def post_process_routes(app: web.Application):
    """Amend swagger API."""

    # Add top-level tags description
    if "tags" not in app._state["swagger_dict"]:
        app._state["swagger_dict"]["tags"] = []
    app._state["swagger_dict"]["tags"].append({
        "name": "ledger",
        "description": "Interaction with ledger",
        "externalDocs": {
            "description":
            "Overview",
            "url": ("https://hyperledger-indy.readthedocs.io/projects/plenum/"
                    "en/latest/storage.html#ledger"),
        },
    })
コード例 #36
0
def post_process_routes(app: web.Application):
    """Amend swagger API."""

    # Add top-level tags description
    if "tags" not in app._state["swagger_dict"]:
        app._state["swagger_dict"]["tags"] = []
    app._state["swagger_dict"]["tags"].append({
        "name": "schema",
        "description": "Schema operations",
        "externalDocs": {
            "description":
            "Specification",
            "url": ("https://github.com/hyperledger/indy-node/blob/master/"
                    "design/anoncreds.md#schema"),
        },
    })
コード例 #37
0
    def __init__(self, loop=None):
        if loop is None:
            loop = asyncio.get_event_loop()

        self.__event_loop = loop

        tdir = os.path.dirname(__file__)
        hdir = os.path.join(tdir, 'health')
        kdir = os.path.join(tdir, 'kv')

        self.__health = {}
        self.__kv = {}

        self.__health['rtsp-master'] = load_json(
            os.path.join(hdir, "rtsp-master.json"))
        self.__health['rtsp-edge'] = load_json(
            os.path.join(hdir, "rtsp-edge.json"))
        self.__health['mp4-edge'] = load_json(
            os.path.join(hdir, "mp4-edge.json"))
        self.__health['mjpeg-proxy'] = load_json(
            os.path.join(hdir, "mjpeg-proxy.json"))
        self.__health['arrow-asns'] = load_json(
            os.path.join(hdir, "arrow-asns.json"))

        self.__kv['rtsp-master'] = load_json(
            os.path.join(kdir, "rtsp-master.json"))
        self.__kv['rtsp-edge'] = load_json(os.path.join(
            kdir, "rtsp-edge.json"))
        self.__kv['mp4-edge'] = load_json(os.path.join(kdir, "mp4-edge.json"))
        self.__kv['mjpeg-proxy'] = load_json(
            os.path.join(kdir, "mjpeg-proxy.json"))
        self.__kv['arrow-asns'] = load_json(
            os.path.join(kdir, "arrow-asns.json"))

        self.health = copy.deepcopy(self.__health)
        self.kv = copy.deepcopy(self.__kv)

        app = Application(loop=loop)

        app.router.add_route('GET', r"/v1/health/service/{svc}",
                             self.__handle_health_request)
        app.router.add_route('GET', r"/v1/kv/{svc:.+}",
                             self.__handle_kv_request)

        self.__app = app
        self.__handler = None
        self.__server = None
コード例 #38
0
ファイル: runners.py プロジェクト: MartinThoma/phlasch
def get_runnable(app_name):
    app = Application()
    configure_db(app)
    if app_name == 'all':
        configure_shortener(app)
        configure_stats(app)
        configure_redirector(app)
    elif app_name == 'shortener':
        configure_shortener(app)
    elif app_name == 'stats':
        configure_stats(app)
    elif app_name == 'redirector':
        configure_redirector(app)
    else:
        raise Exception('app not found!')
    setup_swagger(app)
    return app
コード例 #39
0
def function213(arg680):
    var1625 = ArgumentParser(prog='aiohttp.web ...',
                             description='Application CLI',
                             add_help=False)
    var1625.add_argument('message', help='message to print')
    var1625.add_argument('--repeat',
                         help='number of times to repeat message',
                         type=int,
                         default='1')
    var1625.add_argument('--app-help',
                         help='show this message and exit',
                         action='help')
    var3728 = var1625.parse_args(arg680)
    var4631 = Application()
    var4631['args'] = var3728
    var4631.router.add_get('/', function1605)
    return var4631
コード例 #40
0
def post_process_routes(app: web.Application):
    """Amend swagger API."""

    # Add top-level tags description
    if "tags" not in app._state["swagger_dict"]:
        app._state["swagger_dict"]["tags"] = []
    app._state["swagger_dict"]["tags"].append({
        "name": "out-of-band",
        "description": "Out-of-band connections",
        "externalDocs": {
            "description":
            "Design",
            "url":
            ("https://github.com/hyperledger/aries-rfcs/tree/"
             "2da7fc4ee043effa3a9960150e7ba8c9a4628b68/features/0434-outofband"
             ),
        },
    })
コード例 #41
0
ファイル: main.py プロジェクト: kurkl/aiohttp-tictactoe
async def init_app(pg_url=None) -> Application:
    """
    Create an instance of the server and run it
    """
    # for gunicorn run
    if not pg_url:
        pg_url = POSTGRES_URI

    app = Application(middlewares=[error_middleware])
    app["config"] = pg_url

    engine = await init_or_get_pg(app, pg_url)
    setup_routes(app, engine)
    logger.debug(app["config"])

    app.on_cleanup.append(close_pg)

    return app
コード例 #42
0
async def init_app(on_startup=None, on_cleanup=None):
    from aiohttp.web import Application
    from aiohttp_wsgi import WSGIHandler
    from tob_anchor.urls import get_routes

    wsgi_handler = WSGIHandler(application)
    app = Application()
    app["manager"] = MANAGER
    app.router.add_routes(get_routes())
    # all other requests forwarded to django
    app.router.add_route("*", "/{path_info:.*}", wsgi_handler)

    if on_startup:
        app.on_startup.append(on_startup)
    if on_cleanup:
        app.on_cleanup.append(on_cleanup)

    return app
コード例 #43
0
ファイル: proxy_server.py プロジェクト: fbwfbi/proxypool
def init(loop):
    app = Application(loop=loop)
    app.router.add_route('GET', '/', index)
    resource = app.router.add_resource(r'/proxies/{count:\d*}',
                                       name='proxy-get')
    resource.add_route('GET', get_ip_list)
    app.router.add_route('GET', '/proxies/count', get_count)
    app.router.add_static('/css/',
                          path=str(PROJECT_ROOT / 'static/css'),
                          name='css')
    app.router.add_static('/font/',
                          path=str(PROJECT_ROOT / 'static/font'),
                          name='font')
    if SSL_ON:
        ssl_context = get_ssl_context()
    else:
        ssl_context = None
    run_app(app, host=HOST, port=PORT, ssl_context=ssl_context)
コード例 #44
0
ファイル: server.py プロジェクト: JZQT/nexus-rpc
    def __init__(self,
                 services_map: list,
                 address: tuple,
                 protocol_cls=TBinaryProtocol):
        """Initialize AsyncNexusServer

        :param services_map: A list of (thrift_service, api_handler) two-tuples.
        :param address: A (host, port) tuple.
        :param protocol_cls: Thrift protocol class, default is `TBinaryProtocol`.
        """
        self.services_map: Dict[str, ThriftService] = {}
        for service_module, handler in services_map:
            service = ThriftService(service_module, handler)
            self.services_map[service.name] = service
        self.address = address
        self.protocol_cls = protocol_cls
        self._app = Application()
        self._app.router.add_post('/{service}/{rpc}', self._handle_request)
コード例 #45
0
ファイル: serve.py プロジェクト: aio-libs/aiohttp-devtools
def modify_main_app(app: web.Application, config: Config) -> None:
    """
    Modify the app we're serving to make development easier, eg.
    * modify responses to add the livereload snippet
    * set ``static_root_url`` on the app
    """
    app._debug = True
    dft_logger.debug('livereload enabled: %s', '✓' if config.livereload else '✖')

    def get_host(request: web.Request) -> str:
        if config.infer_host:
            return request.headers.get('host', 'localhost').split(':', 1)[0]
        else:
            return config.host

    if config.livereload:
        async def on_prepare(request: web.Request, response: web.StreamResponse) -> None:
            if (not isinstance(response, web.Response)
                    or not isinstance(response.body, bytes)  # No support for Payload
                    or request.path.startswith("/_debugtoolbar")
                    or "text/html" not in response.content_type):
                return
            lr_snippet = LIVE_RELOAD_HOST_SNIPPET.format(get_host(request), config.aux_port)
            dft_logger.debug("appending live reload snippet '%s' to body", lr_snippet)
            response.body += lr_snippet.encode()
            response.headers[CONTENT_LENGTH] = str(len(response.body))
        app.on_response_prepare.append(on_prepare)

    static_path = config.static_url.strip('/')
    if config.infer_host and config.static_path is not None:
        # we set the app key even in middleware to make the switch to production easier and for backwards compat.
        @web.middleware
        async def static_middleware(request: web.Request, handler: Handler) -> web.StreamResponse:
            static_url = 'http://{}:{}/{}'.format(get_host(request), config.aux_port, static_path)
            dft_logger.debug('setting app static_root_url to "%s"', static_url)
            _change_static_url(request.app, static_url)
            return await handler(request)

        app.middlewares.insert(0, static_middleware)

    if config.static_path is not None:
        static_url = 'http://{}:{}/{}'.format(config.host, config.aux_port, static_path)
        dft_logger.debug('settings app static_root_url to "%s"', static_url)
        _set_static_url(app, static_url)
コード例 #46
0
async def pg_engine(app: web.Application):
    engine = None

    pg_cfg: PostgresSettings = app[APP_CONFIG_KEY].STORAGE_POSTGRES
    dsn = DataSourceName(
        application_name=f"{__name__}_{id(app)}",
        database=pg_cfg.POSTGRES_DB,
        user=pg_cfg.POSTGRES_USER,
        password=pg_cfg.POSTGRES_PASSWORD.get_secret_value(),
        host=pg_cfg.POSTGRES_HOST,
        port=pg_cfg.POSTGRES_PORT,
    )  # type: ignore

    log.info("Creating pg engine for %s", dsn)
    async for attempt in AsyncRetrying(
        **PostgresRetryPolicyUponInitialization(log).kwargs
    ):
        with attempt:
            engine = await create_pg_engine(
                dsn, minsize=pg_cfg.POSTGRES_MINSIZE, maxsize=pg_cfg.POSTGRES_MAXSIZE
            )
            await raise_if_not_responsive(engine)

    if app[APP_CONFIG_KEY].STORAGE_TESTING:
        log.info("Initializing tables for %s", dsn)
        init_pg_tables(dsn, schema=metadata)

    assert engine  # nosec
    app[APP_DB_ENGINE_KEY] = engine

    yield  # ----------

    if engine is not app.get(APP_DB_ENGINE_KEY):
        log.critical("app does not hold right db engine. Somebody has changed it??")

    if engine:
        engine.close()
        await engine.wait_closed()
        log.debug(
            "engine '%s' after shutdown: closed=%s, size=%d",
            engine.dsn,
            engine.closed,
            engine.size,
        )
コード例 #47
0
def build_app() -> Application:
    app = Application()
    jinja = Environment(loader=FileSystemLoader(str(TEMPLATES_DIR)),
                        enable_async=True)
    app.router.add_get("/", render_view(jinja, "index.html"))
    app.router.add_get("/html/", render_view(jinja, "form.html"))
    app.router.add_post("/form/", render_view(jinja, "data.html",
                                              process_form))
    app.router.add_get("/js/", render_view(jinja, "js.html"))
    app.router.add_get("/cookie/",
                       render_view(jinja, "data.html", process_cookies))
    app.router.add_get("/actions/", render_view(jinja, "actions.html"))
    app.router.add_get("/screenshot/", render_view(jinja, "screenshot.html"))
    app.router.add_get("/file/", render_view(jinja, "file_form.html"))
    app.router.add_post(
        "/file/", render_view(jinja, "file_data.html", process_file_form))
    app.router.add_get("/selectors/", render_view(jinja,
                                                  "selector_types.html"))
    return app
コード例 #48
0
ファイル: path_norm.py プロジェクト: ox-it/aiohttp_utils
def setup(app: web.Application,
          *,
          append_slash: bool = DEFAULTS['APPEND_SLASH'],
          merge_slashes: bool = DEFAULTS['MERGE_SLASHES']):
    """Set up the path normalization middleware. Reads configuration from
    ``app['AIOHTTP_UTILS']``.

    :param app: Application to set up.
    :param append_slash: Whether to append trailing slashes to URLs.
    :param merge_slashes: Whether to merge multiple slashes in URLs to a single
        slash
    """
    config = app.get(CONFIG_KEY, {})
    middleware = normalize_path_middleware(
        append_slash=config.get('APPEND_SLASH', append_slash),
        merge_slashes=config.get('MERGE_SLASHES', merge_slashes),
    )
    app.middlewares.append(middleware)
    return app
コード例 #49
0
ファイル: db.py プロジェクト: doytsujin/osparc-simcore
async def pg_engine(app: web.Application):
    cfg = app[APP_CONFIG_KEY][CONFIG_SECTION_NAME]
    pg_cfg = cfg["postgres"]

    app[f"{__name__}.dsn"] = dsn = DataSourceName(
        application_name=f"{__name__}_{id(app)}",
        database=pg_cfg["database"],
        user=pg_cfg["user"],
        password=pg_cfg["password"],
        host=pg_cfg["host"],
        port=pg_cfg["port"],
    )

    log.info("Creating pg engine for %s", dsn)
    for attempt in Retrying(
            **PostgresRetryPolicyUponInitialization(log).kwargs):
        with attempt:
            engine = await create_pg_engine(dsn,
                                            minsize=pg_cfg["minsize"],
                                            maxsize=pg_cfg["maxsize"])
            await raise_if_not_responsive(engine)

    assert engine  # nosec
    app[APP_DB_ENGINE_KEY] = engine

    if cfg["init_tables"]:
        log.info("Initializing tables for %s", dsn)
        init_pg_tables(dsn, schema=metadata)

    yield  # -------------------

    if engine is not app.get(APP_DB_ENGINE_KEY):
        log.critical(
            "app does not hold right db engine. Somebody has changed it??")

    engine.close()
    await engine.wait_closed()
    log.debug(
        "engine '%s' after shutdown: closed=%s, size=%d",
        engine.dsn,
        engine.closed,
        engine.size,
    )
コード例 #50
0
def init_routes(app: web.Application) -> None:

    app.router.add_route('*', '/', index, name='index')
    app.add_routes([web.post('/vips', vips_handler)])
    app.add_routes([web.post('/vipscli', vips_cli_handler)])

    app.add_routes([web.post('/pillow', pillow_handler)])

    # added static dir
    app.router.add_static(
        '/static/',
        path=(PROJECT_PATH / 'static'),
        name='static',
    )
コード例 #51
0
ファイル: app.py プロジェクト: NPPElement/visiobas-gateway
    async def create_app(self) -> Application:
        """Creates an instance of the application.

        Returns:
            Instance of the application, ready to run.
        """
        _LOG.debug("Creating app")
        app = Application()
        app["gateway"] = self._gateway
        app["scheduler"] = await aiojobs.create_scheduler(close_timeout=60,
                                                          limit=100)

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

        # Register handlers
        for handler in self.handlers:
            _LOG.debug(
                "Registering handler",
                extra={
                    "handler": handler.__name__,
                    "url": handler.URL_PATH
                },
            )
            cors.add(app.router.add_route("*", handler.URL_PATH, handler))

        # Swagger docs
        # setup_aiohttp_apispec(app=app, title='VisioBASGateway API',
        #                       swagger_path='/', error_callback=None)
        return app
コード例 #52
0
def setup(app: web.Application):
    """
        Inits and registers a session middleware in aiohttp.web.Application

    """
    logger.debug("Setting up %s ...", __name__)

    # TODO: Ensure called only once per application

    secret_key = app.get(APP_SESSION_SECRET_KEY)
    if secret_key is None:
        # secret_key must be 32 url-safe base64-encoded bytes
        fernet_key = fernet.Fernet.generate_key()
        secret_key = base64.urlsafe_b64decode(fernet_key)

        app[APP_SESSION_SECRET_KEY] = secret_key

    # FIXME: limits service scalability since every replica of the app will have a different key!
    storage = EncryptedCookieStorage(secret_key, cookie_name="API_SESSION")
    aiohttp_session.setup(app, storage)
コード例 #53
0
async def cli(loop, aiohttp_client):
    await init_db()

    db = Gino()
    app = Application(middlewares=[db])

    db.init_app(app, config={'dsn': DB_ADDRESS})

    authors = GenericResource('authors', Author)
    books = GenericResource('books', Book)
    countries = GenericResource('countries', Country)

    authors.register(app.router)
    books.register(app.router)
    countries.register(app.router)

    await _create_model_instances()
    yield await aiohttp_client(app)

    await teardown_db()
コード例 #54
0
async def init_app() -> Application:
    app = Application()
    setup_routes(app)
    cors = cors_setup(app,
                      defaults={
                          '*':
                          ResourceOptions(
                              allow_credentials=True,
                              expose_headers=('Content-Type',
                                              'Access-Control-Allow-Origin'),
                              allow_headers=('Content-Type',
                                             'Access-Control-Allow-Origin',
                                             'Authorization'),
                              allow_methods="*",
                          )
                      })
    for route in list(app.router.routes()):
        cors.add(route)
    app.cleanup_ctx.append(engine_pool)
    return app
コード例 #55
0
ファイル: listen_bot.py プロジェクト: gleb-chipiga/aiotgbot
 def __init__(self,
              url: Union[str, URL],
              token: str,
              handler_table: 'HandlerTableProtocol',
              storage: StorageProtocol,
              certificate: Optional[InputFile] = None,
              ip_address: Optional[str] = None,
              connector: Optional[BaseConnector] = None,
              check_address: bool = False,
              address_header: Optional[str] = None,
              **application_args: Any) -> None:
     super().__init__(token, handler_table, storage, connector)
     self._url: URL = URL(url) if isinstance(url, str) else url
     self._certificate = certificate
     self._ip_address = ip_address
     self._webhook_token: Optional[str] = None
     self._check_address: Final[bool] = check_address
     self._address_header: Final[Optional[str]] = address_header
     self._application = Application(**application_args)
     self._application.router.add_post('/{token}', self._handler)
コード例 #56
0
def build_application():
    loop = asyncio.get_event_loop()
    app = Application(loop=loop)

    loop.run_until_complete(
        aio_yamlconfig.setup(app,
                             config_files=[CONFIG_FILE],
                             trafaret_validator=CONFIG_TRAFARET,
                             base_dir=os.path.dirname(__file__)))

    loop.run_until_complete(
        aio_pybars.setup(app,
                         templates_dir=app.config['TEMPLATES_DIR'],
                         Loader=AppFSTemplateLoader))

    app.router.add_route('*', r'/', Index.index)
    app.router.add_static(
        r'/static/',
        os.path.join(os.path.dirname(__file__), app.config['ASSETS_DIR']))
    return app
コード例 #57
0
    def __init__(self, config_file_name: str):
        self._pending_tasks_by_auction = {}

        self.config = Config(config_file_name).get_config()

        # Start Listening the web server application
        loop = asyncio.get_event_loop()
        self.app = Application(loop=loop)

        # Gets the log file
        log_file_name = self.config['DefaultLogFile']
        self.logger = log(log_file_name).get_logger()

        self.domain = ParseFormats.parse_int(Config().get_config_param(
            'Main', 'Domain'))
        self.immediate_start = ParseFormats.parse_bool(
            Config().get_config_param('Main', 'ImmediateStart'))

        self._load_main_data()
        self._load_control_data()
コード例 #58
0
ファイル: db.py プロジェクト: sanderegg/osparc-simcore
async def postgres_cleanup_ctx(app: web.Application):
    engine = None

    pg_cfg: PostgresSettings = app[APP_CONFIG_KEY].STORAGE_POSTGRES
    dsn = DataSourceName(
        application_name=f"{__name__}_{id(app)}",
        database=pg_cfg.POSTGRES_DB,
        user=pg_cfg.POSTGRES_USER,
        password=pg_cfg.POSTGRES_PASSWORD.get_secret_value(),
        host=pg_cfg.POSTGRES_HOST,
        port=pg_cfg.POSTGRES_PORT,
    )  # type: ignore

    log.info("Creating pg engine for %s", dsn)

    engine = await _ensure_pg_ready(dsn,
                                    min_size=pg_cfg.POSTGRES_MINSIZE,
                                    max_size=pg_cfg.POSTGRES_MAXSIZE)

    if app[APP_CONFIG_KEY].STORAGE_TESTING:
        log.info("Initializing tables for %s", dsn)
        init_pg_tables(dsn, schema=metadata)

    assert engine  # nosec
    app[APP_DB_ENGINE_KEY] = engine

    yield  # ----------

    if engine is not app.get(APP_DB_ENGINE_KEY):
        log.critical(
            "app does not hold right db engine. Somebody has changed it??")

    if engine:
        await close_engine(engine)

        log.debug(
            "engine '%s' after shutdown: closed=%s, size=%d",
            engine.dsn,
            engine.closed,
            engine.size,
        )
コード例 #59
0
ファイル: secret_rest.py プロジェクト: secRetDBot/secRet_dBot
    async def init(self):
        # setup app
        app = Application(loop=self.event_loop)

        # setup cors
        cors = aiohttp_cors.setup(app)

        # setup routers
        resource = cors.add(app.router.add_resource("/"))

        cors.add(
            resource.add_route("GET", self.status), {
                "*":
                aiohttp_cors.ResourceOptions(
                    allow_credentials=True,
                    expose_headers=("X-SecretServer-Header", ),
                    allow_headers=("X-Requested-With", "Content-Type"),
                    max_age=3600,
                )
            })
        return app
コード例 #60
0
def run():
    application = Application()
    
    application.router.add_routes(routes)
    
    aiohttp_jinja2.setup(application, loader=FileSystemLoader(f"{APPLICATION_DIR}/static"))
    aiohttp_session.setup(application, SimpleCookieStorage())
    aiohttp_security.setup(application, SessionIdentityPolicy(), DatabaseAuthorizationPolicy())

    # do load file configuraion
    configuration.load()
    # do load database configuraion
    dictionary.database.set_configuration(
        host=configuration['database']['host'],
        port=configuration['database']['port'],
        name=configuration['database']['name'],
        user=configuration['database']['user'],
        password=configuration['database']['password']
    )

    return run_app(application, host='0.0.0.0', port=configuration['application']['business']['listen'])