如何使用 FastAPI 访问路由器功能中的请求对象?
How to access request object in router function using FastAPI?
我是 FastAPI 框架的新手,我想打印响应。例如,在 Django 中:
@api_view(['POST'])
def install_grandservice(req):
print(req.body)
在 FastAPI 中:
@app.post('/install/grandservice')
async def login():
//print out req
我试着喜欢这个
@app.post('/install/grandservice')
async def login(req):
print(req.body)
但我收到此错误:127.0.0.1:52192 - “POST /install/login HTTP/1.1” 422 无法处理的实体
请帮帮我:(
你可以在路由函数中定义一个Request
类型的参数,如
from fastapi import FastAPI, <b>Request</b>
app = FastAPI()
@app.post('/install/grandservice')
async def login(<b>request: Request</b>):
<b>print(request)</b>
return {"foo": "bar"}
这也包含在文档中,在 Use the Request object directly 部分
下
这里是一个示例,它将为 fastAPI 打印 Request
的内容。
它将请求的主体打印为 json(如果它是 json 可解析的)否则打印原始字节数组。
async def print_request(request):
print(f'request header : {dict(request.headers.items())}' )
print(f'request query params : {dict(request.query_params.items())}')
try :
print(f'request json : {await request.json()}')
except Exception as err:
# could not parse json
print(f'request body : {await request.body()}')
@app.post("/printREQUEST")
async def create_file(request: Request):
try:
await print_request(request)
return {"status": "OK"}
except Exception as err:
logging.error(f'could not print REQUEST: {err}')
return {"status": "ERR"}
我是 FastAPI 框架的新手,我想打印响应。例如,在 Django 中:
@api_view(['POST'])
def install_grandservice(req):
print(req.body)
在 FastAPI 中:
@app.post('/install/grandservice')
async def login():
//print out req
我试着喜欢这个
@app.post('/install/grandservice')
async def login(req):
print(req.body)
但我收到此错误:127.0.0.1:52192 - “POST /install/login HTTP/1.1” 422 无法处理的实体
请帮帮我:(
你可以在路由函数中定义一个Request
类型的参数,如
from fastapi import FastAPI, <b>Request</b>
app = FastAPI()
@app.post('/install/grandservice')
async def login(<b>request: Request</b>):
<b>print(request)</b>
return {"foo": "bar"}
这也包含在文档中,在 Use the Request object directly 部分
下这里是一个示例,它将为 fastAPI 打印 Request
的内容。
它将请求的主体打印为 json(如果它是 json 可解析的)否则打印原始字节数组。
async def print_request(request):
print(f'request header : {dict(request.headers.items())}' )
print(f'request query params : {dict(request.query_params.items())}')
try :
print(f'request json : {await request.json()}')
except Exception as err:
# could not parse json
print(f'request body : {await request.body()}')
@app.post("/printREQUEST")
async def create_file(request: Request):
try:
await print_request(request)
return {"status": "OK"}
except Exception as err:
logging.error(f'could not print REQUEST: {err}')
return {"status": "ERR"}