fromtypingimportOptional,SetfromfastapiimportFastAPIfrompydanticimportBaseModelapp=FastAPI()classItem(BaseModel):name:strdescription:Optional[str]=Noneprice:floattax:Optional[float]=Nonetags:Set[str]=[]@app.post("/items/",response_model=Item,tags=["items"])asyncdefcreate_item(item:Item):returnitem@...
设置响应状态码 from fastapi import status from fastapi.responses import JSONResponse # 方式一 @router.get("/user", status_code=status.HTTP_202_ACCEPTED) def user_index(): return {"msg": "user_index"} # 方式二 @router.get("/user") def user_index(): return JSONResponse(content={"msg"...
ResponseFail("接口路由不存在~")), status_code=status.HTTP_200_OK, ) elif exc.status_code == status.HTTP_405_METHOD_NOT_ALLOWED: # 处理405错误 return JSONResponse( content=jsonable_encoder(response.ResponseFail("请求方式错误,请查看文档确认~")), status_code=status.HTTP_200_OK, ) else: ...
return JSONResponse( status_code=ex.status_code, content={"message": f'error: {ex.detail}'} ) app.include_router(router_user, prefix='/api/v1') 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23. 24. 25. 26. 27. 28. 29...
data['sex']=user_name.sex data['age']=user_name.age ifuser.role=="学生": data['studentnum']=user_name.studentnum else: data['jobnum']=user_name.jobnum returnreponse(code=200,message='成功',data=data) 这样我们就返回了登陆用户的信息...
app=FastAPI()@app.post("/items/",status_code=201)asyncdefcreate_item(name:str):return{"name":name} 复制 status_code也可以是IntEnum,比如Python的http.HTTPStatus。 常见响应状态码: 100以上,信息;很少直接使用; 200以上,成功;200是OK,201是Created,204是No Content; ...
JSONResponse class UnicornException(Exception): def __init__(self, name: str): self.name = name app = FastAPI() @app.exception_handler(UnicornException) async def unicorn_exception_handler(request: Request, exc: UnicornException): return JSONResponse( status_code=418, content={"message": f"...
from fastapi.responses import JSONResponse from fastapi import status def my_function(): return JSONResponse( status_code=500, content={ "code": status.HTTP_500_INTERNAL_SERVER_ERROR, "message": "Internal Server Error"} ) 收藏分享票数1 EN ...
from typing import Dict, Optional from fastapi import APIRouter from pydantic import BaseModel router = APIRouter() class CreateRequest(BaseModel): number: int ttl: Optional[float] = None @router.post("/create") async def create_users(body: CreateRequest) -> Dict: return { "msg": f"{bo...
For example, when there is a é, in a CSV it will be transformed to é, and in a JSON to \u00e9. My code looks something like this: For JSON # API CONTENT # ... return StreamingResponse(io.StringIO(json.dumps(data)), headers={"Content-Disposition": "...