-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfastapi_main.py
76 lines (57 loc) · 2.01 KB
/
fastapi_main.py
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
from typing import Optional, Union, List, Set
from fastapi import FastAPI, Query, Cookie, Header, Body, Path, Form, File, UploadFile, Depends, HTTPException, status
from fastapi.responses import HTMLResponse, JSONResponse, PlainTextResponse, RedirectResponse, FileResponse
from pydantic import BaseModel
app = FastAPI()
data_list = [{'a': 1}, {'b': 4}, {'c': 5}]
class Image(BaseModel):
url: str
name: str
class Item(BaseModel):
name: str = None
# Optional[X] is equivalent to Union[X, None]
# You can use Optional[X] as a shorthand for Union[X, None]
type: Optional[str] = None
description: Union[str, int, None] = None
price: List[float] = []
tax: float
image: List[Union[Image, None]] = []
class Success(BaseModel):
status: int = 1
msg: str = '请求成功'
data: dict
@app.get("/")
def read_root():
return {"Hello": "World"}
# 接收路径参数与查询参数
@app.get("/items/{item_id}")
def read_item(imp: str = None,
q: Optional[str] = None,
item_id: int = Path(...)
): # imp: bool 为必传参数, q: Optional[str] = None 为可选参数
return {"item_id": item_id, "q": q, "imp": imp}
# 接收路径参数
@app.get("/data/{key}")
async def get_data(key: Optional[str] = Path(..., title='key')):
for data in data_list:
if key in data:
return data
return {'error': 'not found'}
# 接收body参数
@app.post("/items")
async def read_items(item: Item):
return [{"name": item.name}, {"description": item.description}, {"price": item.price}, {"tax": item.tax}, {"type": item.type},
{"image": item.image}]
# 接收header信息
@app.post("/header")
async def read_header(user_agent: Optional[str] = Header(None)):
return JSONResponse(
Success(data={'user_agent': user_agent}).dict(),
status_code=status.HTTP_200_OK,
headers={'sign': ''},
# {
# 'code': 200,
# 'message': "Success",
# 'data': user_agent,
# }
)