-
First Check
Commit to Help
Example Codeimport time
from fastapi import FastAPI, BackgroundTasks, Request, Response
from loguru import logger
app = FastAPI()
@app.middleware("http")
async def logger_request(request: Request, call_next) -> Response:
logger.debug(f"http middleware [{request.url}]")
response = await call_next(request)
return response
class Worker:
def __init__(self, arg):
self.arg = arg
logger.debug(f"worker[{arg}] init")
def work(self):
for i in range(10):
logger.debug(f"worker[{self.arg}] work[{i}]")
time.sleep(1)
@app.get("/")
async def root():
return {"message": "Hello World"}
@app.get("/work/{worker_id}")
async def work(back_task: BackgroundTasks, worker_id: int):
worker = Worker(worker_id)
back_task.add_task(worker.work)
return {"message": f"work[{worker_id}] created"}
@app.get("/hello/{name}")
async def say_hello(name: str):
return {"message": f"Hello {name}"} Description
Operating SystemWindows Operating System DetailsNo response FastAPI Version0.74.1 Python VersionPython 3.7.10 Additional ContextNo response |
Beta Was this translation helpful? Give feedback.
Replies: 5 comments 1 reply
-
You are blocking event loop by calling Of course there are option to scale it, for example see some fresh reddit discussion, https://www.reddit.com/r/Python/comments/sxovwp/async_io_tasks_vs_threads/ If you are using uvicorn, type in
Having more workers (processes) would give you power to have multiple CPU bound code running in parallel (max is number of processes). Some other - maybe better setups are workers in very different host/processes/containers and some queue. You add job to be done to Redis for example and 'worker' instance collect and execute them one after another. This requires some more complex system so if your requirement is to have MAX of few background task at once, more processes should be enough for you |
Beta Was this translation helpful? Give feedback.
-
it's on me that i forgot to say that i had already use multi workers, even 16 workers(16 cores of my AMD cpu), it still stuck. |
Beta Was this translation helpful? Give feedback.
-
Hi, I might be stuck with some similar situation, what's wrong with my code: @app.middleware("http")
async def signature(request: Request, call_next):
try:
signature = request.headers.get('X-Coding-Signature')
except AttributeError:
return Response(status_code=status.HTTP_403_FORBIDDEN, content='Authentification failed.')
content = await request.body()
sha1 = hmac.new(bytes(SECRET_TOKEN, encoding="utf8"), content, 'sha1')
sha1 = sha1.hexdigest()
calculate_signature = 'sha1=' + sha1
if not calculate_signature == signature:
return Response(status_code=status.HTTP_403_FORBIDDEN, content='Authentification failed.')
else:
return await call_next(request) and the route @app.post('/hook')
def simple_hook(json: dict[str, Any]):
try:
id = json['sender']['id']
name = json['sender']['name']
# eventName = json['eventName']
print("[coding.net] %s(%d): %s. " % (name, id, 'eventName'))
except Error as e:
print("ERROR: %s" % e)
return {'code': -1}
return {'code': 0,'message':'done!'} Everything was just fine without the |
Beta Was this translation helpful? Give feedback.
-
More about your issue: encode/starlette#1441 |
Beta Was this translation helpful? Give feedback.
-
Subscribed, thank you. |
Beta Was this translation helpful? Give feedback.
More about your issue: encode/starlette#1441