fromfastapiimportFastAPIfromfastapi.responsesimportStreamingResponse some_file_path="large-video-file.mp4"app=FastAPI()@app.get("/")defmain():file_like=open(some_file_path,mode="rb")returnStreamingResponse(file_like,media_type="video/mp4") 7.FileResponse 异步流式输出一个文件 不同于其他response...
使用fastAPI框架返回JSONResponse TypeError: Object of type datetime is not JSON serializable,使用fastAPI框架返回JSONResponseTypeError:ObjectoftypedatetimeisnotJSONserializable返回之前将datetime单独处理一下。
type="car"classPlaneItem(BaseItem): type="plane"size: intitems={"item1": {"description":"All my friends drive a low rider","type":"car"},"item2": {"description":"Music is my aeroplane, it's my aeroplane","type":"plane","size": 5, }, } @app.get("/items/{item_id}",re...
app = FastAPI() @app.get("/legacy/") def get_legacy_data(): data = """<?xml ve rsion="1.0"?> <shampoo> <Header> Apply shampoo here. </Header> <Body> You'll have to use soap here. </Body> </shampoo> """ # 重点就是指定 media_type return Response(content=data, media_typ...
docs 里的 media_type 是通过 response_class 实现的,需要自定义 response_class 才能修改。 from fastapi import FastAPI from fastapi.responses import StreamingResponse app = FastAPI() class MyCustomResponse(StreamingResponse): media_type = "image/jpeg" # 将文件类型写在这里 @app.get("/img", response...
参数response_class也会用来定义响应的「媒体类型」。 在这个例子中,HTTP 头的Content-Type会被设置成application/json。 并且在 OpenAPI 文档中也会这样记录。 小贴士 ORJSONResponse目前只在 FastAPI 中可用,而在 Starlette 中不可用。 HTML 响应¶ 使用HTMLResponse来从FastAPI中直接返回一个 HTML 响应。
import uvicornfrom fastapi import FastAPI, Responseapp = FastAPI()@app.get("/legacy/")def get_legacy_data():data = """<?xml ve rsion="1.0"?><shampoo><Header>Apply shampoo here.</Header><Body>You'll have to use soap here.</Body></shampoo>"""# 重点就是指定 media_typereturn Respo...
app=FastAPI()@app.get("/legacy/")defget_legacy_data():data="""<?xml ve rsion="1.0"?><shampoo><Header>Apply shampoo here.</Header><Body>You'll have to use soap here.</Body></shampoo>""" # 重点就是指定 media_typereturnResponse(content=data,media_type="application/xml")if__name...
{'Content-Type':'application/json',# 指定请求内容类型'X-Auth-Token':'token_000'# 替换为您的实际 Token}# 发送 POST 请求try:response=requests.post(url,json=data,headers=headers)response.raise_for_status()# 如果响应状态码不是 200-299,则引发异常print("状态码:",response.status_code)print("...
class FileUploadResponse(BaseModel): filename: str content_type: str @app.post('/upload-file', response_model=FileUploadResponse) async def upload_file(file: UploadFile = File(...)): return FileUploadResponse(filename=file.filename, content_type=file.content_type) ...