Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/288.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在FastApi中从请求读取非json数据_Python_Python 3.x_Python Requests_Fastapi - Fatal编程技术网

Python 如何在FastApi中从请求读取非json数据

Python 如何在FastApi中从请求读取非json数据,python,python-3.x,python-requests,fastapi,Python,Python 3.x,Python Requests,Fastapi,我有下面的代码片段,它只是从表单数据中读取并返回它 @my_app.post("/items2/{item_id}") def read_root(username: str = Form(...), password: str = Form(...)): # return request.body() return {"username": username, "password":password} 我的问题是,有

我有下面的代码片段,它只是从表单数据中读取并返回它

@my_app.post("/items2/{item_id}")
def read_root(username: str = Form(...), password: str = Form(...)):
    # return request.body()
    return {"username": username, "password":password}
我的问题是,有没有其他方法可以从请求对象中提取这些数据?我不想在这里使用表单数据。另外,我的输入数据不是json格式,所以我不想同时使用该模型


我已经浏览了,找不到与此相关的内容。

如果您想从请求正文中读取数据,那么这就是您可以做的

from fastapi import Request, FastAPI
@my_app.post("/items2/{item_id}")
def read_root(request: Request):

    # if want to process request as json
    # return request.json() 
    return request.body() # if want to process request as string

基本上,将数据添加到请求对象中,在api中读取该对象,然后处理它,然后返回它

这样做有效吗?我尝试了这个方法,得到了错误“ValueError:[TypeError('coroutine'object is not iterable”)、TypeError('vars()参数必须具有dict属性')”。如何从Postman向该api发出请求?这是一个基本示例,以请求为参数,然后根据请求处理数据。若您面临错误,则需要了解如何在python中处理请求对象。如果仍然面临错误,您可以发布一个包含所有前提条件和错误的新问题