按照fastAPI教程
安装
pip install fastapi
pip install uvicorn
from typing import Optional
import uvicorn
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"Hello": "World"}
@app.get("/items/{item_id}")
def read_item(item_id: int, q: Optional[str] = None):
return {"item_id": item_id, "q": q}
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=8000, loop="asyncio")
运行python main.py,hello world
async
/ await??
可以查看 127.0.0.1:8000/docs(可以作为前端调试的接口) 和 127.0.0.1:8000/redoc
使用pydantic写请求体
from typing import Optional
from fastapi import FastAPI
from pydantic import BaseModel
import uvicorn
app = FastAPI()
class Item(BaseModel):
name: str
price: float
is_offer: Optional[bool] = None
@app.put("/items/{item_id}")
def update_item(item_id: int, item: Item):
return {"item_name": item.name, "item_id": item_id, "item_price": item.price}
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=8000, loop="asyncio")
利用pydantic声明请求后,如何赋值
from typing import List, Dict
from datetime import date
from pydantic import BaseModel
# Declare a variable as a str
# and get editor support inside the function
def main(user_id: str):
return user_id
# A Pydantic model
class User(BaseModel):
id: int
name: str
joined: date
my_user: User = User(id=3, name="John Doe", joined="2018-07-19")
second_user_data = {
"id": 4,
"name": "Mary",
"joined": "2018-11-30",
}
my_second_user: User = User(**second_user_data)
print(my_user, my_second_user)
# 无自动补全机制
def get_full_name(first_name, last_name):
full_name = first_name.title() + " " + last_name.title()
return full_name
print(get_full_name("john", "doe"))
# 自动补全
def get_full_name_1(first_name: str, last_name: str):
full_name = first_name.title() + " " + last_name.title()
return full_name
print(get_full_name_1("john", "doe"))
# 类型检查机制
def get_name_with_age(name: str, age: int):
name_with_age = name + " is this old: " + str(age)
return name_with_age
print(get_name_with_age("json", 12))
# 其余基础数据类型
def get_items(item_a: str, item_b: int, item_c: float, item_d: bool, item_e: bytes):
return item_a, item_b, item_c, item_d, item_d, item_e
from typing import List
def process_items(items: List[str]):
for item in items:
print(item)
print(process_items(['1', '2', '3']))
from typing import Set, Tuple
def process_items_1(items_t: Tuple[int, int, str], items_s: Set[bytes]):
return items_t, items_s
print(process_items_1((1,2,1), {bytes(5)}))
from typing import Dict
def process_items_2(prices: Dict[str, float]):
for item_name, item_price in prices.items():
print(item_name)
print(item_price)
process_items_2({'2': 1.2, '3':3.4})
from typing import Optional
def say_hi(name: Optional[str] = None):
if name is not None:
print(f"Hey {name}!")
else:
print("Hello World")
say_hi()
say_hi('fastapi')
from typing import Optional
class Person:
def __init__(self, name: str):
self.name =name
def get_person_name(one_person: Person):
return one_person.name
person = Person('xiaoming')
get_person_name(person)