https://imququ.com/post/four-ways-to-post-data-in-http.html#toc-2
Content-Type: application/x-www-form-urlencoded 最原始表单,参数单一,不能传文件。
Content-Type
/form-data 改进后的表单,能传文件。Content-Type: application/json 倾向于传json,json规范导致前后端传数据都喜欢用这个,数据生产和消费简单。
https://fastapi.tiangolo.com/zh/tutorial/schema-extra-example/
把函数参数改为Body解析即可,而不是FORM解析。
python# -*- coding:utf-8 -*-
import traceback
import uvicorn
from typing import Optional
from fastapi import Body, FastAPI
from pydantic import BaseModel
from fastapi.middleware.cors import CORSMiddleware
app = FastAPI(
title='FastAPI',
description='FastAPI',
version='1.0.0',
docs_url='/docs',
redoc_url='/redocs',
)
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
class Item(BaseModel):
name: str
description: Optional[str] = None
price: float
tax: Optional[float] = None
@app.post("/items/{item_id}")
async def update_item(
item_id: int,
item: Item = Body(
...,
example={
"name": "Foo",
"description": "A very nice Item",
"price": 35.4,
"tax": 3.2,
},
),
):
results = {"item_id": item_id, "item": item}
return results
if __name__ == '__main__':
uvicorn.run('fastapia:app', host='0.0.0.0', port=8001, reload=False, debug=False, workers=1)
修改请求头
写raw的原生json字符串
pythonimport requests
requests.post(url="http://0.0.0.0:8001/items/1",
json={
"name": "Foo",
"description": "A very nice Item",
"price": 35.4,
"tax": 3.2,
},
)
本文作者:Dong
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 CC BY-NC。本作品采用《知识共享署名-非商业性使用 4.0 国际许可协议》进行许可。您可以在非商业用途下自由转载和修改,但必须注明出处并提供原作者链接。 许可协议。转载请注明出处!