starlette

starlette, using a synchronous function inside a web socket

无人久伴 提交于 2021-01-07 03:33:07
问题 I'm trying to build a web socket using starlette which receives a message, runs calculations in a synchronous function and returns a response. @app.websocket("/ws") async def websocket_endpoint(websocket: WebSocket): await websocket.accept() while True: stock = await websocket.receive_text() stock = stock.upper() data = sentiment_analysis(stock=stock) await websocket.send_json({"score": data}) the sentiment analysis is a synchronous function. so the text is received and the calculations are

FastAPI middleware peeking into responses

时光怂恿深爱的人放手 提交于 2020-08-25 09:16:32
问题 I try to write a simple middleware for FastAPI peeking into response bodies. In this example I just log the body content: app = FastAPI() @app.middleware("http") async def log_request(request, call_next): logger.info(f'{request.method} {request.url}') response = await call_next(request) logger.info(f'Status code: {response.status_code}') async for line in response.body_iterator: logger.info(f' {line}') return response However it looks like I "consume" the body this way, resulting in this

Starlette + asyncio.create_task() doesn't log error if task object is stored in instance variable [duplicate]

社会主义新天地 提交于 2020-03-04 18:43:23
问题 This question already has answers here : When asyncio task gets stored after creation, exceptions from task get muted (2 answers) Closed 13 days ago . Okay, this is very weird, but here goes - import asyncio from starlette.applications import Starlette class MyTasks: def __init__(self): self.task = None async def main(self): self.task = asyncio.create_task(self.hello()) async def hello(self): raise ValueError async def main(): await MyTasks().main() app = Starlette(on_startup=[main]) $