我有以下代码:
import time
from fastapi import FastAPI, Request
app = FastAPI()
@app.get("/ping")
async def ping(request: Request):
print("Hello")
time.sleep(5)
print("bye")
return {"ping": "pong!"}
Run Code Online (Sandbox Code Playgroud)
如果我在本地主机上运行我的代码 - 例如http://localhost:8501/ping- 在同一浏览器窗口的不同选项卡中,我得到:
Hello
bye
Hello
bye
Run Code Online (Sandbox Code Playgroud)
代替:
Hello
Hello
bye
bye
Run Code Online (Sandbox Code Playgroud)
我已经阅读过有关使用的内容httpx,但仍然无法实现真正的并行化。有什么问题?
python asynchronous concurrent-processing python-asyncio fastapi
我们正在使用 Python FastAPI 编写一个 Web 服务,该服务将托管在 Kubernetes 中。出于审计目的,我们需要保存特定路由的request/的原始 JSON 正文。JSON的主体大小约为1MB,最好这不应该影响响应时间。我们怎样才能做到这一点?responserequestresponse
我有一个 FastAPI 应用程序,我希望将默认日志写入 STDOUT,并使用 JSON 格式的以下数据:
应用程序日志应如下所示:
{
"XYZ": {
"log": {
"level": "info",
"type": "app",
"timestamp": "2022-01-16T08:30:08.181Z",
"file": "api/predictor/predict.py",
"line": 34,
"threadId": 435454,
"message": "API Server started on port 8080 (development)"
}
}
}
Run Code Online (Sandbox Code Playgroud)
访问日志应如下所示:
{
"XYZ": {
"log": {
"level": "info",
"type": "access",
"timestamp": "2022-01-16T08:30:08.181Z",
"message": "GET /app/health 200 6ms"
},
"req": {
"url": "/app/health",
"headers": {
"host": "localhost:8080",
"user-agent": "curl/7.68.0",
"accept": "*/*"
},
"method": "GET",
"httpVersion": "1.1",
"originalUrl": "/app/health",
"query": {}
},
"res": {
"statusCode": 200,
"body": …Run Code Online (Sandbox Code Playgroud) 我正在尝试将后台任务添加到我的中间件中,但尚未在他们的文档中找到任何官方方法来执行此操作,这是我迄今为止尝试过的方法:
async def task1():
logging.info("Waiting ...")
time.sleep(5)
logging.info("Waited.")
@app.middleware("http")
async def add_process_time_header(request, call_next, bt=Depends(BackgroundTasks)):
a = bt.dependency()
a.add_task(task1)
a()
return await call_next(request)
Run Code Online (Sandbox Code Playgroud)
这阻止了我的请求,我是否应该能够在没有等待的情况下调用异步函数?我想完全忽略后台任务的结果,我不需要 bg 任务的结果
Python 版本 3.9,FastAPI 版本 0.78.0
我有一个用于应用程序异常处理的自定义函数。当请求遇到内部逻辑问题时,即由于某种原因我想发送 400 的 HTTP 响应,我会调用实用程序函数。
@staticmethod
def raise_error(error: str, code: int) -> None:
logger.error(error)
raise HTTPException(status_code=code, detail=error)
Run Code Online (Sandbox Code Playgroud)
不喜欢这种方法。所以我看看
from fastapi import FastAPI, HTTPException, status
from fastapi.respones import JSONResponse
class ExceptionCustom(HTTPException):
pass
def exception_404_handler(request: Request, exc: HTTPException):
return JSONResponse(status_code=status.HTTP_404_NOT_FOUND, content={"message": "404"})
app.add_exception_handler(ExceptionCustom, exception_404_handler)
Run Code Online (Sandbox Code Playgroud)
我使用上述方法遇到的问题是无法将消息作为参数传递。
对整个主题有什么想法吗?
fastapi ×5
python ×5
asynchronous ×2
logging ×2
exception ×1
gunicorn ×1
python-3.x ×1
uvicorn ×1