如何在 FastAPI 中转储 http "Content-type: application/json;"

How to dump http "Content-type: application/json;" in FastAPI

我将编写一个 python 脚本来侦听自定义工具的 webhook,该工具将在我指定的端口上发送 json(它们可能也支持其他格式)。

如何编写类似于 linux 命令的内容:“nc -l 9000” 以转储我在该端口(header 和 body)上获得的输出?

from fastapi import FastAPI

app = FastAPI()

@app.get("/")
async def root():
    print()  <- how to get the data here?
    return {"message": "ok"}

我想在终端打印内容,然后我可以很容易地看到我会得到什么并采取行动。不确定如果需要的话我应该向他们重放什么(需要检查一下,他们还没有完成他们的部分)。

所以我认为您正在寻找 请求

这包含很多关于请求的信息(包括,Body,表单,Headers 等)。

from fastapi import FastAPI, Request

app = FastAPI()


@app.get("/")
def read_root(request: Request):
    print(request.headers)
    return {}

所以现在如果我向这个端点发送请求,这将 return 我

{
    "host":"127.0.0.1:8000",
    "connection":"keep-alive",
    "accept":"application/json",
    "sec-fetch-site":"same-origin",
    "sec-fetch-mode":"cors",
    "sec-fetch-dest":"empty",
    "referer":"http://127.0.0.1:8000/docs",
    "accept-encoding":"gzip, deflate, br",
    "accept-language":"en-US,en;q=0.9,tr;q=0.8",
    "cookie":"csrftoken=sdf6ty78uewfıfehq7y8fuq; _ga=GA.1.11242141,1234423"
}

然后你可以从request.headers

中提取accept

如果你只需要那个,你也可以

@app.get("/")
def read_root(request: Request):
    print(request.headers['accept'])
    return {}

这将 return 仅

Out: application/json