async def db_middleware(request: Request, handler: Callable) -> Response: async with settings.db_pool.acquire() as conn: app_conn = getattr(request.app, 'conn', None) if app_conn: # Use single conn from app for test cases to rollback all sub transactions request.conn = app_conn else: request.conn = conn return await handler(request)
async def middleware(request: Request) -> Response: request.user = None jwt_token = request.headers.get('X-API-Key', None) if not jwt_token: jwt_token = request.cookies.get('JWT_TOKEN', None) if jwt_token: jwt_token = 'Bearer ' + jwt_token if jwt_token: request.user = await container.get('uaa_service').validate_token( jwt_token) return await handler(request)
async def redis_middleware(request: Request, handler: Callable) -> Response: request.redis = await get_redis() try: return await handler(request) except Exception: request.redis.close() await request.redis.wait_closed() raise
def __new__(self, stream_data=b"test data"): reader = asyncio.StreamReader() reader.feed_data(stream_data) reader.feed_eof() headers = {"Content-Length": len(stream_data)} request = Request(uri="http://fake.com", headers=headers, body=stream_data) return RequestStreamReader(request, reader)
async def middleware(request: Request): request.user = None jwt_token = request.headers.getone('X-API-Key', None) if not jwt_token: jwt_token = request.cookies.get('JWT_TOKEN', None) if jwt_token: jwt_token = 'Bearer ' + jwt_token if jwt_token: payload = decode_token(jwt_token) try: user_service: UserService = container.get('user_service') user = await user_service.get_user_by_id(payload['user_id']) request.user = dict(user) if user else None except KeyError: raise HTTPUnauthorized(reason='Wrong authorization token') return await handler(request)
async def all_products(request: Request) -> Response: async with aiohttp.ClientSession() as session: products = asyncio.create_task(session.get(f'{PRODUCT_BASE}/products')) favorites = asyncio.create_task( session.get(f'{FAVORITE_BASE}/users/3/favorites')) cart = asyncio.create_task(session.get(f'{CART_BASE}/users/3/cart')) requests = [products, favorites, cart] done, pending = await asyncio.wait(requests, timeout=1.0) if products in pending: [request.cancel() for request in requests] return web.json_response( {'error': 'Could not reach products service.'}, status=504) elif products in done and products.exception() is not None: [request.cancel() for request in requests] logging.exception('Server error reaching product service.', exc_info=products.exception()) return web.json_response( {'error': 'Server error reaching products service.'}, status=500) else: product_response = await products.result().json() product_results: List[Dict] = await get_products_with_inventory( session, product_response) cart_item_count: Optional[int] = await get_response_item_count( cart, done, pending, 'Error getting user cart.') favorite_item_count: Optional[int] = await get_response_item_count( favorites, done, pending, 'Error getting user favorites.') return web.json_response({ 'cart_items': cart_item_count, 'favorite_items': favorite_item_count, 'products': product_results })
async def login_required(self, request: Request, handler: Any) -> Response: """ Запрос токена при необходимости авторизации @param request: данные запроса @param handler: данные обработчика @return: ответ после прохождения авторизации """ if self.enabled: # получение аккаунта из заголовка header = request.headers.get('Authorization') result = await self._execute(header) # в случае успеха присвоение bearer-токена request.bearer_token = 'Bearer {}'.format( result.get('access_token')) response = await handler(request) return response
async def generate(request: Request) -> Response: """ The function gets html file from a request as a text, generates uuid and store this html file by the uuid in the application context, calls another function to get pdf file from html, and returns the pdf file :param request: request object with html file to be processed :return: web.Response object with either pdf file as bytes or with error message """ logger.debug('Got request to generate pdf...') # Getting client's html file as a string text = await request.text() logger.debug('Saving the html in app by unique uuid...') uuid = str(uuid4()) request.app['htmls'][uuid] = text try: response = await get_pdf(uuid, request.app['addresses']) except aiohttp.ClientResponseError as e: error_message = f"Athenapdf returned an error ({e})" logger.error(error_message) return web.Response(text=error_message, status=500) except aiohttp.client_exceptions.ClientConnectorError as e: error_message = ("The app cannot connect to the Athenapdf, " "check whether it's alive and on the right " f"host and port. Reason: {e}") logger.error(error_message) return web.Response(text=error_message, status=500) del request.app['htmls'][uuid] logger.debug('Returning pdf to the user...') return web.Response(body=response, status=200, content_type='application/pdf')
async def ws_chat(request: Request) -> web.WebSocketResponse: """ Chat backend. Add it to the route like this: - app.add_routes([web.get('/chat', handler=ws_chat)]) #Input/Response API Note that you will *not* receive the broadcast message about your changes, only your confirmation or error. **Change Nick**: * Input: `{'action': 'set_nick', 'nick': '<my nickname>'}` * Fail: `{'action': 'set_nick', 'success': False, 'message': 'Nickname is already in use'}` * OK: `{'action': 'set_nick', 'success': True, 'message': ''}` **Join a room**: * Input: `{'action': 'join_room', 'room': '<room name>'}` * Fail: `{'action': 'join_room', 'success': False, 'message': 'Name already in use in this room.'}` * OK: `{'action': 'join_room', 'success': True, 'message': ''}` **Send a message**: * Input: `{'action': 'chat_message', 'message': '<my message>'}` * OK: `{'action': 'chat_message', 'success': True, 'message': '<chat_message>'}` **Room user list**: * Input: `{'action': 'user_list', 'room': '<room_name>'}` * OK:`{'action': 'user_list', 'success': True, 'room': '<room_name>', 'users': ['<user1>', '<user2>']}` # Broadcast messages Bodies this server may broadcast to your client at any time: - When your client is connecting: - `{'action': 'connecting', 'room': room, 'user': user}` - When someone joins the room: - `{'action': 'joined', 'room': room, 'user': user}` - When someone leaves the room: - `{'action': 'left', 'room': room, 'user': user, 'shame': False}` - When someone disconnects without using `.close()` (e.g. using CTRL+C to stop their client): - `{'action': 'left', 'room': room, 'user': user, 'shame': True}` - When someone changes their nick name: - `{'action': 'nick_changed', 'room': room, 'from_user': user, 'to_user': user}` - When someone sends a message: - `{'action': 'chat_message', 'message': message, 'user': user}` :param request: Request object :return: Websocket response """ current_websocket = web.WebSocketResponse( autoping=True, heartbeat=60) # Create a websocket response object # Check that everything is OK, if it's not, close the connection. ready = current_websocket.can_prepare(request=request) if not ready: await current_websocket.close(code=WSCloseCode.PROTOCOL_ERROR) await current_websocket.prepare(request) # Load it with the request object # Set default room name room = 'Default' # Set default user name. # Note: Can technically fail, and if it does we'll just close the connection and make them retry later. user = f'User{random.randint(0, 999999)}' logger.info('%s connected to room %s', user, room) # Inform current WS subscription that he's connecting: await current_websocket.send_json({ 'action': 'connecting', 'room': room, 'user': user }) # Check that the user does not exist in the room already if request.app['websockets'][room].get(user): logger.warning('User already connected. Disconnecting.') await current_websocket.close(code=WSCloseCode.TRY_AGAIN_LATER, message=b'Username already in use') return current_websocket else: # {'websockets': {'<room>': {'<user>': 'obj', '<user2>': 'obj'}}} request.app['websockets'][room][user] = current_websocket # Inform everyone that user has joined for ws in request.app['websockets'][room].values(): await ws.send_json({'action': 'join', 'user': user, 'room': room}) # Send out messages whenever they are received try: async for message in current_websocket: # for each message in the websocket connection if isinstance(message, WSMessage): if message.type == web.WSMsgType.text: # If it's a text, process it as a message # Parse incoming data message_json = message.json() action = message_json.get('action') if action not in ALLOWED_USER_ACTIONS: await current_websocket.send_json({ 'action': action, 'success': False, 'message': 'Not allowed.' }) if action == 'set_nick': return_body, success = await change_nick( app=request.app, room=room, new_nick=message_json.get('nick'), old_nick=user) if not success: logger.warning( 'Failed to set nick %s for %s. Reason %s', message_json.get('nick'), user, return_body['message'], ) await current_websocket.send_json(return_body) else: logger.info('%s: %s is now known as %s', room, user, message_json.get('nick')) await current_websocket.send_json(return_body) await broadcast( app=request.app, room=room, message={ 'action': 'nick_changed', 'room': room, 'from_user': user, 'to_user': message_json.get('nick'), }, ignore_user=message_json.get('nick'), ) # Customized return body to the user is sent, so we ignore it. user = message_json.get('nick') elif action == 'join_room': return_body, success = await change_room( app=request.app, new_room=message_json.get('room'), old_room=room, nick=user) if not success: logger.info( '%s: Unable to change room for %s to %s, reason: %s', room, user, message_json.get('room'), return_body['message'], ) await current_websocket.send_json(return_body) else: logger.info('%s: User %s joined the room', user, message_json.get('room')) await broadcast( app=request.app, room=room, message={ 'action': 'left', 'room': room, 'user': user, 'shame': False }, ) await broadcast( app=request.app, room=message_json.get('room'), message={ 'action': 'joined', 'room': room, 'user': user }, ignore_user=user, ) room = message_json.get('room') elif action == 'user_list': logger.info('%s: %s requested user list', room, user) user_list = await retrieve_users( app=request.app, room=message_json['room']) await current_websocket.send_json(user_list) elif action == 'chat_message': logger.info('%s: Message: %s', room, message_json.get('message')) await current_websocket.send_json({ 'action': 'chat_message', 'success': True, 'message': message_json.get('message') }) await broadcast( app=request.app, room=room, message={ 'action': 'chat_message', 'message': message_json.get('message'), 'user': user }, ignore_user=user, ) finally: # When a connection is stopped, remove the connection request.app['websockets'][room].pop(user) if current_websocket.closed: # This only happens if a close signal is received. await broadcast(app=request.app, room=room, message={ 'action': 'left', 'room': room, 'user': user, 'shame': False }) else: # Abrupt disconnect without close signal (e.g. `ctrl`+`c`) await broadcast(app=request.app, room=room, message={ 'action': 'left', 'room': room, 'user': user, 'shame': True }) return current_websocket
def parse(self, response): referer = response.css('h2 > a ::attr(href)').get() Request(referer) #####COMENTARIOS##### '''print('\n########Pagina ' + str(self._num_pagina) + '########')
async def manage_requests(self, request: Request, hapic_data: HapicData) -> Description: # TODO BS: only chief (or ability) can display this affinity = self._kernel.affinity_lib.get_affinity( hapic_data.path.affinity_id) relation = self._kernel.affinity_lib.get_character_relation( affinity_id=hapic_data.path.affinity_id, character_id=hapic_data.path.character_id) requests: typing.List[ AffinityRelationDocument] = self._kernel.server_db_session.query( AffinityRelationDocument).filter( AffinityRelationDocument.affinity_id == affinity.id, AffinityRelationDocument.accepted == False, AffinityRelationDocument.request == True, ).all() data = {} try: data = await request.json() except JSONDecodeError: pass request: AffinityRelationDocument if data: for request in list(requests): choose = data.get(request.character_id) if choose: if choose == "Accepter": request.accepted = True request.request = False request.status_id = affinity.default_status_id elif choose == "Refuser": request.accepted = False request.request = False request.disallowed = True self._kernel.server_db_session.add(request) self._kernel.server_db_session.commit() requests.remove(request) form_parts = [] for request in requests: character = self._kernel.character_lib.get_document( request.character_id) form_parts.append( Part( label=f"{character.name}", name=character.id, choices=["Ne rien décider", "Accepter", "Refuser"], value="Ne rien décider", )) return Description( title=f"Demande(s) d'adhésion pour {affinity.name}", items=[ Part( is_form=True, submit_label="Enregistrer", form_action=(f"/affinity/{hapic_data.path.character_id}" f"/manage-requests/{affinity.id}"), items=form_parts, ) ], footer_links=[ Part(is_link=True, go_back_zone=True, label="Retourner à l'écran de déplacements"), Part( is_link=True, label=f"Voir la fiche de {affinity.name}", form_action= f"/affinity/{hapic_data.path.character_id}/see/{affinity.id}", classes=["primary"], ), Part( is_link=True, label="Voir les affinités", form_action=f"/affinity/{hapic_data.path.character_id}", ), ], can_be_back_url=True, )
async def handler(request: Request): data = await request.read() request.app['event'].set() request.app['data'] = data return Response(status=204)