Home | 简体中文 | 繁体中文 | 杂文 | Github | 知乎专栏 | Facebook | Linkedin | Youtube | 打赏(Donations) | About
知乎专栏

4.4. Post 请求

		
pip install python-multipart
		
		

4.4.1. From 数据

            	
from fastapi import FastAPI, Form
# from starlette.requests import Request
from starlette.responses import Response
from starlette.testclient import TestClient

app = FastAPI()

@app.post("/form")
async def login(username: str = Form(), password: str = Form()):
    return {"username": username, "password": password}

client = TestClient(app)
data = {"username": "netkiller", "password": "123456"}
response = client.post("/form", data=data)
print(response.content.decode())
            	
			

Bool 布尔值

			
@app.post("/test", summary="测试接口", description="测试接口", tags=["web"],
          )
async def test(short: bool = Form(), status: Optional[bool] = Form(False)):
    print(short, status)
    return HTMLResponse(content="OK", status_code=200)
			
			

4.4.2. Json 数据转为 dict

             
from fastapi import FastAPI, Request
from typing import Dict

# from starlette.requests import Request
from starlette.responses import Response
from starlette.testclient import TestClient

app = FastAPI()


@app.post("/json")
async def json(item: dict):
    print(item)
    return "OK"


client = TestClient(app)
data = {"key": "value"}
response = client.post("/json", json=data)
print(response.content.decode())      
            
			

4.4.3. Data 原始数据

		    
from fastapi import FastAPI, Request

# from starlette.requests import Request
from starlette.responses import Response
from starlette.testclient import TestClient

app = FastAPI()


@app.post("/webhook")
async def the_webhook(request: Request):
    return await request.body()


data = b"""EURUSD Less Than 1.09092
{"Condition": "value"}
[3,4,5,]
{}"""

data = b"""EURUSD Less Than 1.09092"""

client = TestClient(app)
response = client.post("/webhook", data=data)
print(response.content.decode())
            
			

4.4.4. POST 接收 JSON 数据

			
@app.post("/android/notification", summary="通知", description=f"通知接口", tags=["android"])
async def notification(request: Request):
    jsonText = (await request.body()).decode()
    print(jsonText)
    print(await request.json())
    return {"status": true, "data": {}, "msg": "成功"}			
			
			

4.4.5. 上传文件

			
@app.post("/file/")
async def create_file(file: bytes = File()):
    filename = f"tmp/{uuid.uuid4()}.png"
    print(filename)
    # filename = uuid.uuid4()
    with open(filename, "wb") as f:
        f.write(file)
    return {"file": filename,"size": len(file)}

@app.post("/uploadfile")
async def create_upload_file(file: UploadFile):
    # uuid5 = uuid.uuid5(uuid.NAMESPACE_DNS, 'netkiller.cn')
    # filename, extension = os.path.splitext(file.filename)
    filename = f"tmp/{file.filename}"
    file_content = await file.read()  # 读取文件
    with open(filename, "wb") as f:
        f.write(file_content)

    return {"filename": file.filename,"content_type": file.content_type}
			
			
			

上传多个文件

			
from typing import List

from fastapi import FastAPI, File, UploadFile

app = FastAPI()

@app.post("/uploadfiles/")
async def create_upload_files(files: List[UploadFile] = File(...)):
    return {"filenames": [file.filename for file in files]}