async def json_from_request(cls, request: Request) -> Json: if request.content_type in ["application/json"]: return await request.json() # type: ignore elif request.content_type in ["application/yaml", "text/yaml"]: text = await request.text() return yaml.safe_load(text) # type: ignore else: raise HTTPNotAcceptable(text="Only support json")
async def request_content(self, url: str, accept: str = CONTENT_TYPE_JSON): # aiohttp_session = aiohttp.ClientSession(loop=asyncio.get_event_loop()) headers = {'accept': accept} async with aiohttp.ClientSession() as session: async with session.get(url) as resp: if 400 <= resp.status <= 599: raise HTTPNotAcceptable() content_type = resp.content_type if content_type in [CONTENT_TYPE_JSON, CONTENT_TYPE_GEOJSON]: return await resp.json()
async def registration(request: Request): if 'X-UserId' in request.headers: return HTTPNotAcceptable() session_maker = request.app['db_session_manager'] session: Session = session_maker() try: data = await request.json() if data: user_db = session.query(Users).filter_by(login=data['login']).first() if user_db: return HTTPConflict() data_without_password = dict(data) data_without_password.pop('password') data_for_auth = {'login': data['login'], 'password': data['password']} if 'account_manager' in request.app['config']['app']: url = request.app['config']['app']['account_manager']['url'] async with aiohttp.ClientSession(raise_for_status=True) as http_client_session: async with http_client_session.post(url, json=data_without_password) as \ resp: account_manager_resp = await resp.json() data_for_auth['id'] = account_manager_resp['id'] user_serializer = UsersSchema().load(data_for_auth, session=session) else: user_serializer = UsersSchema().load(data_for_auth, session=session) session.add(user_serializer) session.commit() return HTTPCreated(headers={'Location': f"/users/{user_serializer.login}"}) else: return HTTPBadRequest() except InvalidURL as ex: raise Exception(f"""Invalid url account_manager:{str(ex)}""") except ClientResponseError: return HTTPConflict() except ClientError as ex: raise Exception(f"""Can't connect to account_manager:{str(ex)}""") except Exception: session.rollback() raise finally: session.close()
def accept_guard(request: web.Request, *accepts: str): for accept in request.headers.getall('ACCEPT', []): if accept in accepts: return raise HTTPNotAcceptable(text=f"Accepted types: {','.join(accepts)}")
async def do_route(self, request: web.Request): for accept in request.headers.getall('ACCEPT', []): acceptor = self._accepts.get(accept) if acceptor is not None: return await acceptor(request) raise HTTPNotAcceptable()