框架与类库:FastAPI
FastAPIで外部APIリクエストやI/O処理を行う際に気をつけること
FastAPI的高性能依赖于正确理解和使用异步处理。在async def
中直接使用同步I/O操作会阻塞事件循环,导致性能下降。通过run_in_threadpool
将同步任务放入线程池,或使用httpx
等异步库,可避免阻塞。同步端点虽不阻塞事件循环,但需注意线程数限制。生产环境中,Gunicorn虽能缓解阻塞问题,但异步处理仍是最佳实践。
Dockerize Your FastAPI and Celery Application
本文教你如何将FastAPI与Celery结合的应用通过Docker进行容器化部署。首先,介绍了应用的基本结构,包括FastAPI和Celery的任务文件。接着,详细讲解了如何编写Dockerfile和Docker Compose文件,分别用于构建容器镜像和定义服务。最后,通过docker compose up
命令一键启动整个应用栈,简化了部署流程。整个过程清晰易懂,适合开发者快速上手。
Asynchronous Tasks with FastAPI and Celery
使用Celery在FastAPI中实现异步任务处理,可有效避免长时间运行函数导致的API超时。通过定义Celery任务并配置Redis作为消息代理,将耗时函数(如计算平方根)放入后台执行。FastAPI提供两个端点:一个用于启动任务并返回任务ID,另一个用于查询任务状态和结果。结合Docker部署,可简化应用管理。
How to use Server-Sent Events with FastAPI, React, and Langgraph
Learn all you need to implement streaming in production using SSE and how to handle streaming errors.
How to profile a FastAPI asynchronous request
I have been experimenting with FastAPI recently, a Python API framework self-describing as "high performance, easy to learn, fast to code, ready for production".
One of the features I wanted my project to have is to be fully asynchronous, from the app server to the SQL requests. As the API is mostly I/O bound, this would allow it to handle many concurrent requests with a single server process, instead of starting a thread per request, as one commony seen with Flask/Gunicorn.
However, this poses a challenge when it comes to profiling the code and interpreting the results.
- «
- 1
- »