async def run():
    app = web.Application(middlewares=[
        cors_middleware, db_middleware, auth_middleware, error_middleware
    ])

    def cors_fallback(req):
        return web.Response(headers={
            "Access-Control-Allow-Origin": "*",
            "Access-Control-Allow-Headers": "Authorization",
            "Access-Control-Allow-Methods": "GET, POST, PATCH"
        },
                            status=404 if req.method != "OPTIONS" else 200)

    app.add_routes([
        web.get("/s", Handlers.get_system),
        web.post("/s/switches", Handlers.post_switch),
        web.get("/s/{system}", Handlers.get_other_system),
        web.get("/s/{system}/members", Handlers.get_system_members),
        web.get("/s/{system}/switches", Handlers.get_system_switches),
        web.get("/s/{system}/fronters", Handlers.get_system_fronters),
        web.patch("/s", Handlers.patch_system),
        web.get("/m/{member}", Handlers.get_member),
        web.post("/m", Handlers.post_member),
        web.patch("/m/{member}", Handlers.patch_member),
        web.delete("/m/{member}", Handlers.delete_member),
        web.post("/discord_oauth", Handlers.discord_oauth),
        web.route("*", "/{tail:.*}", cors_fallback)
    ])
    app["pool"] = await db.connect(os.environ["DATABASE_URI"])
    return app
async def register(app: web.Application):
    """Register routes."""
    app.add_routes([
        web.post("/revocation/create-registry", revocation_create_registry),
        web.get(
            "/revocation/registries/created",
            revocation_registries_created,
            allow_head=False,
        ),
        web.get("/revocation/registry/{rev_reg_id}",
                get_registry,
                allow_head=False),
        web.get(
            "/revocation/active-registry/{cred_def_id}",
            get_active_registry,
            allow_head=False,
        ),
        web.get(
            "/revocation/registry/{rev_reg_id}/tails-file",
            get_tails_file,
            allow_head=False,
        ),
        web.patch("/revocation/registry/{rev_reg_id}", update_registry),
        web.post("/revocation/registry/{rev_reg_id}/publish",
                 publish_registry),
        web.patch(
            "/revocation/registry/{rev_reg_id}/set-state",
            set_registry_state,
        ),
    ])
Exemple #3
0
async def register(app: web.Application):
    """Register routes."""
    app.add_routes([
        web.post("/revocation/create-registry", create_rev_reg),
        web.get(
            "/revocation/registries/created",
            rev_regs_created,
            allow_head=False,
        ),
        web.get("/revocation/registry/{rev_reg_id}",
                get_rev_reg,
                allow_head=False),
        web.get(
            "/revocation/active-registry/{cred_def_id}",
            get_active_rev_reg,
            allow_head=False,
        ),
        web.get(
            "/revocation/registry/{rev_reg_id}/tails-file",
            get_tails_file,
            allow_head=False,
        ),
        web.put("/revocation/registry/{rev_reg_id}/tails-file",
                upload_tails_file),
        web.patch("/revocation/registry/{rev_reg_id}", update_rev_reg),
        web.post("/revocation/registry/{rev_reg_id}/definition",
                 send_rev_reg_def),
        web.post("/revocation/registry/{rev_reg_id}/entry",
                 send_rev_reg_entry),
        web.patch(
            "/revocation/registry/{rev_reg_id}/set-state",
            set_rev_reg_state,
        ),
    ])
Exemple #4
0
 def setup_routes(self):
     self.app.add_routes([
         web.patch('', self.update_channel_entries),
         web.delete('', self.delete_channel_entries),
         web.get('/torrents/{infohash}/health', self.get_torrent_health),
         web.patch(r'/{public_key:\w*}/{id:\w*}',
                   self.update_channel_entry),
         web.get(r'/{public_key:\w*}/{id:\w*}', self.get_channel_entries),
     ])
Exemple #5
0
    def _create_api(self, spec) -> None:

        resource = Resource(spec, self.injector)

        self.add_routes([
            web.get('/',
                    RootResource(spec).get),
            web.get('/{resource}/{id}', resource.get, allow_head=False),
            web.get('/{resource}', resource.get, allow_head=False),
            web.head('/{resource}/{id}', resource.head),
            web.head('/{resource}', resource.head),
            web.patch('/{resource}/{id}', resource.patch),
            web.patch('/{resource}', resource.patch),
        ])
Exemple #6
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))
Exemple #7
0
 def setup_routes(self):
     self.app.add_routes(
         [
             web.patch('/{infohash}', self.update_tags_entries),
             web.get('/{infohash}/suggestions', self.get_suggestions),
         ]
     )
Exemple #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))
def setup() -> _T:
    state: Dict[str, str] = {}

    async def reg(request: Request) -> None:
        nonlocal state
        state["method"] = request.method
        state["body"] = await request.read()

    async def handler(request: Request) -> Response:
        await reg(request)
        return Response(text="Some text")

    async def json_handler(request: Request) -> Response:
        await reg(request)
        return json_response({"key": "value"})

    app = Application()
    app.add_routes([
        web.get("/url/", handler),
        web.post("/url/", handler),
        web.options("/url/", handler),
        web.put("/url/", handler),
        web.patch("/url/", handler),
        web.delete("/url/", handler),
        web.get("/json_url/", json_handler),
    ])

    return app, state
Exemple #10
0
 def routes(self):
     return [
         web.get("/api/dashboard", self.dashboards),
         web.post("/api/dashboard", self.add_dashboard),
         web.get("/api/dashboard/{dashboard_id}", self.dashboard),
         web.delete("/api/dashboard/{dashboard_id}", self.remove_dashboard),
         web.patch("/api/dashboard/{dashboard_id}", self.patch_dashboard),
     ]
Exemple #11
0
 def setup_routes(self):
     self.app.add_routes([
         web.get('', self.get_downloads),
         web.put('', self.add_download),
         web.delete('/{infohash}', self.return_404),
         web.patch('/{infohash}', self.update_download),
         web.get('/{infohash}/torrent', self.return_404),
         web.get('/{infohash}/files', self.get_files),
     ])
Exemple #12
0
async def register(app: web.Application):
    """Register routes."""
    app.add_routes([
        web.post("/revocation/create-registry", revocation_create_registry),
        web.get("/revocation/registry/{id}", get_current_registry),
        web.get("/revocation/registry/{id}/tails-file", get_tails_file),
        web.patch("/revocation/registry/{id}", update_registry),
        web.post("/revocation/registry/{id}/publish", publish_registry),
    ])
Exemple #13
0
def get_routes(api):
    return [
        web.post('/api/card_payment', api.card_payment_post),
        web.post('/api/requested_payment', api.requested_payment_post),
        web.get('/api/card_payment', api.card_payment_get),
        web.get('/api/requested_payment', api.requested_payment_get),
        web.patch('/api/card_payment', api.card_payment_patch),
        web.post('/api/internet_bank_payment', api.internet_bank_payment),
        web.get('/payment/{customer}', api.payment_customer),
    ]
Exemple #14
0
async def run():
    app = web.Application(
        middlewares=[db_middleware, auth_middleware, error_middleware])

    app.add_routes([
        web.get("/s", Handlers.get_system),
        web.post("/s/switches", Handlers.post_switch),
        web.get("/s/{system}", Handlers.get_other_system),
        web.get("/s/{system}/members", Handlers.get_system_members),
        web.get("/s/{system}/switches", Handlers.get_system_switches),
        web.get("/s/{system}/fronters", Handlers.get_system_fronters),
        web.patch("/s", Handlers.patch_system),
        web.get("/m/{member}", Handlers.get_member),
        web.post("/m", Handlers.post_member),
        web.patch("/m/{member}", Handlers.patch_member),
        web.delete("/m/{member}", Handlers.delete_member),
        web.post("/discord_oauth", Handlers.discord_oauth)
    ])
    app["pool"] = await db.connect(os.environ["DATABASE_URI"])
    return app
Exemple #15
0
def test_patch(router: Any) -> None:
    async def handler(request):
        pass

    router.add_routes([web.patch("/", handler)])
    assert len(router.routes()) == 1

    route = list(router.routes())[0]
    assert route.handler is handler
    assert route.method == "PATCH"
    assert str(route.url_for()) == "/"
Exemple #16
0
def add_handlers(app):
    """
    Adding handlers for web application
    """
    app.add_routes([web.get('', handlers.get_help_handle),
                    web.post('/imports', handlers.import_handle),
                    web.patch('/imports/{import_id}/citizens/{citizen_id}', handlers.patch_handle),
                    web.get('/imports/{import_id}/citizens', handlers.get_citizens_handle),
                    web.get('/imports/{import_id}/citizens/birthdays', handlers.get_presents_handle),
                    web.get('/imports/{import_id}/towns/stat/percentile/age', handlers.percentile_handle)
                    ])
Exemple #17
0
def create_app(settings: Optional[Settings] = None) -> web.Application:
    """Identification provider entry point: builds and run a webserver."""
    settings = settings or load_conf()
    app = web.Application(middlewares=[enforce_json, vary_origin])
    setup(app)
    app["settings"] = settings
    app["identity_backend"] = import_idp(
        settings["identity_backend"]["class"])(
            options=settings["identity_backend"].get("options", {}))

    async def on_startup_wrapper(app):
        """Wrapper to call __aenter__."""
        await app["identity_backend"].__aenter__()

    async def on_cleanup_wrapper(app):
        """Wrapper to call __exit__."""
        await app["identity_backend"].__aexit__(None, None, None)

    app.on_startup.append(on_startup_wrapper)
    app.on_cleanup.append(on_cleanup_wrapper)

    app.add_routes([
        web.get("/", views.get_root),
        web.get("/users/", views.get_users),
        web.post("/users/", views.post_users),
        web.get("/jwt/", views.get_jwts),
        web.post("/jwt/", views.post_jwt),
        web.get("/jwt/{jid}", views.get_jwt),
        web.get("/users/", views.get_users),
        web.patch("/users/{user_id}/", views.patch_user),
        web.get("/password_recoveries/", views.get_password_recoveries),
        web.post("/password_recoveries/", views.post_password_recoveries),
        web.get("/health", views.get_health),
    ])

    cors = aiohttp_cors.setup(
        app,
        defaults={
            "*":
            aiohttp_cors.ResourceOptions(
                allow_credentials=True,
                expose_headers="*",
                allow_headers="*",
                allow_methods=[
                    "GET", "OPTIONS", "PUT", "POST", "DELETE", "PATCH"
                ],
            )
        },
    )

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

    return app
Exemple #18
0
def start_server():

    app = web.Application()
    app.add_routes([
        web.get('/', handle),
        web.patch('/', handle),
        web.post('/', handle),
        web.put('/', handle),
    ])
    runner = web.AppRunner(app)
    return runner
def test_patch(router):
    async def handler(request):
        pass

    router.add_routes([web.patch('/', handler)])
    assert len(router.routes()) == 1

    route = list(router.routes())[0]
    assert route.handler is handler
    assert route.method == 'PATCH'
    assert str(route.url_for()) == '/'
Exemple #20
0
 def setup_routes(self):
     self.app.add_routes([
         web.get('', self.get_downloads),
         web.put('', self.add_download),
         web.delete('/{infohash}', self.delete_download),
         web.patch('/{infohash}', self.update_download),
         web.get('/{infohash}/torrent', self.get_torrent),
         web.get('/{infohash}/files', self.get_files),
         web.get('/{infohash}/stream/{fileindex}',
                 self.stream,
                 allow_head=False)
     ])
async def register(app: web.Application):
    """Register routes."""

    app.add_routes([
        web.post("/ledger/register-nym", register_ledger_nym),
        web.patch("/ledger/rotate-public-did-keypair",
                  rotate_public_did_keypair),
        web.get("/ledger/did-verkey", get_did_verkey, allow_head=False),
        web.get("/ledger/did-endpoint", get_did_endpoint, allow_head=False),
        web.get("/ledger/taa", ledger_get_taa, allow_head=False),
        web.post("/ledger/taa/accept", ledger_accept_taa),
    ])
Exemple #22
0
 def setup_routes(self):
     self.app.add_routes([
         web.get('', self.get_channel),
         web.put('', self.update_channel),
         web.post('', self.create_channel),
         web.get('/torrents', self.get_torrents),
         web.post('/torrents', self.update_torrents),
         web.delete('/torrents', self.delete_torrent),
         web.get('/torrents/count', self.get_torrent_count),
         web.patch('/torrents/{infohash}', self.update_torrent),
         web.post('/commit', self.commit),
     ])
Exemple #23
0
 def routes(self):
     return [
         put('/upload/drive/v3/files/progress/{id}', self._uploadProgress),
         post('/upload/drive/v3/files/', self._upload),
         post('/drive/v3/files/', self._create),
         get('/drive/v3/files/', self._query),
         delete('/drive/v3/files/{id}/', self._delete),
         patch('/drive/v3/files/{id}/', self._update),
         get('/drive/v3/files/{id}/', self._get),
         post('/oauth2/v4/token', self._oauth2Token),
         get('/o/oauth2/v2/auth', self._oAuth2Authorize),
         get('/drive/customcreds', self._getCustomCred),
         post('/token', self._driveToken),
     ]
async def register(app: web.Application):
    """Register routes."""

    app.add_routes([
        web.get("/wallet/did", wallet_did_list, allow_head=False),
        web.post("/wallet/did/create", wallet_create_did),
        web.get("/wallet/did/public", wallet_get_public_did, allow_head=False),
        web.post("/wallet/did/public", wallet_set_public_did),
        web.post("/wallet/set-did-endpoint", wallet_set_did_endpoint),
        web.get("/wallet/get-did-endpoint",
                wallet_get_did_endpoint,
                allow_head=False),
        web.patch("/wallet/did/local/rotate-keypair",
                  wallet_rotate_did_keypair),
    ])
Exemple #25
0
 def _register_routes(self):
     self._app.add_routes([
         web.get("/", lambda _: web.HTTPFound("/index.html")),
         # search
         web.get("/api/v1/search", self._search_handler.search),
         web.get("/api/v1/details", self._search_handler.details),
         # session
         web.get("/api/v1/session", self._session_handler.show),
         web.post("/api/v1/session", self._session_handler.update),
         # torrents
         web.get("/api/v1/session/torrents", self._torrents_handler.index),
         web.get("/api/v1/session/torrents/{info_hash}",
                 self._torrents_handler.show),
         web.post("/api/v1/session/torrents",
                  self._torrents_handler.create),
         web.patch("/api/v1/session/torrents/{info_hash}",
                   self._torrents_handler.update),
         web.delete("/api/v1/session/torrents/{info_hash}",
                    self._torrents_handler.destroy),
         # files
         web.get("/api/v1/session/torrents/{info_hash}/files",
                 self._files_handler.index),
         web.get("/api/v1/session/torrents/{info_hash}/files/{file_idx}",
                 self._files_handler.show),
         web.patch("/api/v1/session/torrents/{info_hash}/files/{file_idx}",
                   self._files_handler.update),
         # watch
         web.get("/watch", self._watch_handler.show),
         web.get("/watch/{info_hash}", self._watch_handler.show),
         web.get("/watch/{info_hash}/{file_name}",
                 self._watch_handler.show),
         web.get("/play/{info_hash}/{file_name}", self._play),
         # static
         # always keep static route last
         web.static("/", self.resource_path("web/"))
     ])
Exemple #26
0
 def setUp(self):
     self.DATA_PATH = './tests/data'
     self.HOST = '127.0.0.1'
     self.PORT = 8000
     self.SERVER_ADDRESS = (self.HOST, self.PORT)
     self.app = web.Application()
     self.app.add_routes([
         web.get('/{tail:.*}', handle_factory(self.DATA_PATH)),
         web.post('/{tail:.*}', handle_factory(self.DATA_PATH)),
         web.put('/{tail:.*}', handle_factory(self.DATA_PATH)),
         web.patch('/{tail:.*}', handle_factory(self.DATA_PATH)),
         web.head('/{tail:.*}', handle_factory(self.DATA_PATH)),
         web.delete('/{tail:.*}', handle_factory(self.DATA_PATH)),
         web.options('/{tail:.*}', handle_factory(self.DATA_PATH)),
     ])
     self.test_server = TestServer(self.app, host=self.HOST, port=self.PORT)
Exemple #27
0
def create_application(path):
    app = web.Application()
    try:
        db = sqlite3.connect(path)
        app['db'] = db
    except sqlite3.Error as e:
        print(e)
    app.add_routes([
        web.post('/couriers', couriers),
        web.patch('/couriers/{id}', update_couriers),
        web.post('/orders', orders),
        web.post('/orders/assign', assign_orders),
        web.post('/orders/complete', complete_orders),
        web.get('/couriers/{id}', courier_info)
    ])
    return app
Exemple #28
0
async def async_main():

    stdout_handler = logging.StreamHandler(sys.stdout)
    for logger_name in ["aiohttp.server", "aiohttp.web", "aiohttp.access"]:
        logger = logging.getLogger(logger_name)
        logger.setLevel(logging.DEBUG)
        logger.addHandler(stdout_handler)

    async def handle_http(request):
        data = {
            "method": request.method,
            "content": (await request.read()).decode(),
            "headers": dict(request.headers),
        }
        return web.json_response(
            data, status=405, headers={"from-upstream": "upstream-header-value"}
        )

    async def handle_websockets(request):
        wsock = web.WebSocketResponse()
        await wsock.prepare(request)

        await wsock.send_str(json.dumps(dict(request.headers)))

        async for msg in wsock:
            if msg.type == aiohttp.WSMsgType.CLOSE:
                await wsock.close()
            if msg.type == aiohttp.WSMsgType.TEXT:
                await wsock.send_str(msg.data)
            if msg.type == aiohttp.WSMsgType.BINARY:
                await wsock.send_bytes(msg.data)

        return wsock

    upstream = web.Application()
    upstream.add_routes(
        [
            web.get("/http", handle_http),
            web.patch("/http", handle_http),
            web.get("/websockets", handle_websockets),
        ]
    )
    upstream_runner = web.AppRunner(upstream)
    await upstream_runner.setup()
    upstream_site = web.TCPSite(upstream_runner, "0.0.0.0", 8888)
    await upstream_site.start()
    await asyncio.Future()
Exemple #29
0
    def __init__(self, **kwargs):
        self.app = web.Application(**kwargs)
        self.app.router.add_routes([
            web.post("/user", self._post_user),
            web.patch("/user", self._patch_user),
            web.get("/user", self._get_user),
            web.delete("/user", self._delete_user),
            web.delete(r"/user/error/{id:[a-f0-9]+}", self._delete_user_error),
            web.get("/user/courses", self._get_user_courses),
            web.post("/user/courses/update", self._post_user_courses_update),
            web.post("/form_geometry", self._post_form_geometry),
            web.post("/update_all_courses", self._post_update_all_courses),
            web.get("/debug/tasks", self._get_debug_tasks),
            web.post("/debug/tasks/update", self._post_debug_tasks_update),
            web.post("/test_form", self._post_test_form)
        ])

        self.db = LockboxDB("db", 27017)
 def routes(self):
     return [
         post('/addons/self/options', self.hassioUpdateOptions),
         post("/homeassistant/api/services/persistent_notification/dismiss",
              self.dismissNotification),
         post("/homeassistant/api/services/persistent_notification/create",
              self.createNotification),
         post("/homeassistant/api/events/{name}", self.haEventUpdate),
         post("/homeassistant/api/states/{entity}", self.haStateUpdate),
         post('/auth', self.hassioAuthenticate),
         get('/auth', self.hassioAuthenticate),
         get('/info', self.hassioInfo),
         get('/addons/self/info', self.hassioSelfInfo),
         get('/snapshots/{slug}/download', self.hassioSnapshotDownload),
         get('/snapshots/{slug}/info', self.hassioSnapshotInfo),
         post('/snapshots/{slug}/remove', self.hassioDelete),
         post('/snapshots/new/upload', self.uploadNewSnapshot),
         get('/snapshots/new/upload', self.uploadNewSnapshot),
         get('/debug/toggleblock', self.toggleBlockSnapshot),
         post('/snapshots/new/partial', self.hassioNewPartialSnapshot),
         post('/snapshots/new/full', self.hassioNewFullSnapshot),
         get('/snapshots/new/full', self.hassioNewFullSnapshot),
         get('/homeassistant/info', self.haInfo),
         get('/supervisor/info', self.hassioSupervisorInfo),
         get('/supervisor/logs', self.supervisorLogs),
         get('/core/logs', self.coreLogs),
         get('/snapshots', self.hassioSnapshots),
         put('/upload/drive/v3/files/progress/{id}',
             self.driveContinueUpload),
         post('/upload/drive/v3/files/', self.driveStartUpload),
         post('/drive/v3/files/', self.driveCreate),
         get('/drive/v3/files/', self.driveQuery),
         delete('/drive/v3/files/{id}/', self.driveDelete),
         patch('/drive/v3/files/{id}/', self.driveUpdate),
         get('/drive/v3/files/{id}/', self.driveGetItem),
         post('/updatesettings', self.updateSettings),
         get('/readfile', self.readFile),
         post('/uploadfile', self.uploadfile),
         post('/doareset', self.reset),
         post('/oauth2/v4/token', self.driveRefreshToken),
         get('/o/oauth2/v2/auth', self.driveAuthorize),
         post('/token', self.driveToken),
         get('/hassio/ingress/self_slug', self.slugRedirect)
     ]
Exemple #31
0
def main():
    parser = argparse.ArgumentParser(description='HTTP data mocker')
    parser.add_argument('data_path', help='The data folder')
    parser.add_argument('-p',
                        '--port',
                        help='The TCP port',
                        default=TCP_PORT,
                        type=int)
    parser.add_argument('--host', help='The host', default=HOST)
    parser.add_argument('-l',
                        '--log-file',
                        help='save log messages in a given file')
    parser.add_argument('-v',
                        '--verbose',
                        action='store_true',
                        default=False,
                        help='print more detailed log messages')
    parser.add_argument(
        '--version',
        action='version',
        version=f'Mocker version {pkg_resources.require("mocker")[0].version}')
    args = parser.parse_args()

    logging_level = logging.DEBUG if args.verbose else logging.INFO
    logging.basicConfig(filename=args.log_file, level=logging_level)

    if os.path.exists(args.data_path):
        app = web.Application()
        app.add_routes([
            web.get('/{tail:.*}', handle_factory(args.data_path)),
            web.post('/{tail:.*}', handle_factory(args.data_path)),
            web.put('/{tail:.*}', handle_factory(args.data_path)),
            web.patch('/{tail:.*}', handle_factory(args.data_path)),
            web.head('/{tail:.*}', handle_factory(args.data_path)),
            web.delete('/{tail:.*}', handle_factory(args.data_path)),
            web.options('/{tail:.*}', handle_factory(args.data_path)),
        ])
        try:
            web.run_app(app, host=args.host, port=args.port)
        except KeyboardInterrupt:
            print('Exiting Mocker...')
    else:
        print('Folder {} not found'.format(args.data_path))