Mar*_*sta 5 python request fastapi
我正在开发一个 API,它从本地文件夹返回一些文件,以模拟我们为开发人员环境提供的系统。
大多数系统的工作原理是输入识别人员的代码并返回他的文件。但是,该系统的一条路径具有独特的行为:它使用 POST 方法(请求正文包含 Id 代码),我正在努力使其工作。
这是我当前的代码:
import json
from pathlib import Path
import yaml
from fastapi import FastAPI
from pydantic.main import BaseModel
app = FastAPI()
class RequestModel(BaseModel):
assetId: str
@app.get("/{group}/{service}/{assetId}")
async def return_json(group: str, service: str, assetId: str):
with open("application-dev.yml", "r") as config_file:
output_dir = yaml.load(config_file)['path']
path = Path(output_dir + f"{group}/{service}/")
file = [f for f in path.iterdir() if f.stem == assetId][0]
if file.exists():
with file.open() as target_file:
return json.load(target_file)
@app.post("/DataService/ServiceProtocol")
async def return_post_path(request: RequestModel):
return return_json("DataService", "ServiceProtocol", request.msisdn)
Run Code Online (Sandbox Code Playgroud)
我想从 API 本身调用另一个路径/函数来返回所需的值,但我收到此错误:
ValueError: [TypeError("'coroutine' object is not iterable"), TypeError('vars() argument must have __dict__ attribute')]
Run Code Online (Sandbox Code Playgroud)
您的return_json函数返回一个协程(请注意async其定义中的关键字)。请注意,@app.post(...)需要一个返回数据的协程,而不是返回另一个协程的协程。最直接的改变是:
@app.post("/DataService/ServiceProtocol")
async def return_post_path(request: RequestModel):
# unpack return_json into a non-coroutine object before returning it
return await return_json("DataService", "ServiceProtocol", request.msisdn)
Run Code Online (Sandbox Code Playgroud)
@app.post("/DataService/ServiceProtocol")
def return_post_path(request: RequestModel):
# return the coroutine directly because we're inside a normal function
return return_json("DataService", "ServiceProtocol", request.msisdn)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10015 次 |
| 最近记录: |