背景:有一个项目需要模拟用户服务接收数据,并且需要保存Body,Body的数据结构是动态的,并不是固定格式。用于统计数据是否缺失。
最简单的实现方法:
import uvicorn
from typing import Union
from fastapi import FastAPI, Request
import os
from starlette.requests import Request
from starlette.responses import Response
from fastapi.exceptions import RequestValidationError
from pydantic import BaseModel
from starlette.types import Scope, Receive, Send
app = FastAPI()
@app.post("/cc/{item_id}")
async def read_item(item_id: str, item: dict, request: Request):
print(item)
with open('test.json', "a+") as f:
f.write(str(item) + "\n")
return {"item": item, "path": item_id}
# return {"scope": str(request.scope)}
if __name__ == '__main__':
name_app = os.path.splitext(os.path.basename(__file__))[0]
uvicorn.run(app=f"{name_app}:app", host="0.0.0.0", port=8000)