update
This commit is contained in:
97
dt_course_fastapi/main.py
Normal file
97
dt_course_fastapi/main.py
Normal file
@@ -0,0 +1,97 @@
|
||||
from enum import Enum
|
||||
from typing import Union
|
||||
|
||||
from fastapi import FastAPI
|
||||
from pydantic import BaseModel
|
||||
|
||||
app = FastAPI()
|
||||
|
||||
|
||||
@app.get("/")
|
||||
async def root():
|
||||
return {"message": "Hello World"}
|
||||
|
||||
|
||||
@app.get("/hello/{name}")
|
||||
async def say_hello(name: str):
|
||||
return {"message": f"Hello {name}"}
|
||||
|
||||
|
||||
# 路径参数
|
||||
@app.get("/items/{item_id}")
|
||||
async def read_item(item_id):
|
||||
return {"item_id": item_id}
|
||||
|
||||
|
||||
# 有类型的数据参数
|
||||
@app.get("/itemsint/{item_id}")
|
||||
async def read_item(item_id: int):
|
||||
return {"item_id": item_id}
|
||||
|
||||
|
||||
class ModelName(str, Enum):
|
||||
alexnet = "alexnet"
|
||||
resnet = "resnet"
|
||||
lenet = "lenet"
|
||||
|
||||
|
||||
# Enum类
|
||||
@app.get("/models/{model_name}")
|
||||
async def get_model(model_name: ModelName):
|
||||
if model_name is ModelName.alexnet:
|
||||
return {"model_name": model_name, "message": "Deep Learning FTW!"}
|
||||
|
||||
if model_name is ModelName.resnet:
|
||||
return {"model_name": model_name, "message": "LeCNN all the images"}
|
||||
|
||||
if model_name is ModelName.lenet:
|
||||
return {"model_name": model_name, "message": "Have some residuals"}
|
||||
|
||||
|
||||
# 查询参数
|
||||
fake_item_db = [{"item_name": "Foo"}, {"item_name": "Bar"}, {"item_name": "Baz"}]
|
||||
|
||||
|
||||
@app.get("/items/")
|
||||
async def read_item(skip: int = 0, limit: int = 10):
|
||||
return fake_item_db[skip:skip + limit]
|
||||
|
||||
|
||||
# 查询参数类型转换
|
||||
@app.get("/items/{item_id}")
|
||||
async def read_item(item_id: str, q: Union[str, None] = None, short: bool = False):
|
||||
item = {"item_id": item_id}
|
||||
if q:
|
||||
item.update({"q": q})
|
||||
if not short:
|
||||
item.update(
|
||||
{"description": "This is an amazing item that has long description"}
|
||||
)
|
||||
return item
|
||||
|
||||
|
||||
@app.get("/users/{user_id}/items/{item_id}")
|
||||
async def read_user_item(
|
||||
user_id: int, item_id: int, q: Union[str, None] = None, short: bool = False
|
||||
):
|
||||
item = {"item_id": item_id, "owner_id": user_id}
|
||||
if q:
|
||||
item.update({"q": q})
|
||||
if not short:
|
||||
item.update(
|
||||
{"description": "This is an amazing item that has long description"}
|
||||
)
|
||||
return item
|
||||
|
||||
|
||||
# 数据模型
|
||||
class Item(BaseModel):
|
||||
name: str
|
||||
description: Union[str, None] = None
|
||||
price: float
|
||||
tax: Union[float, None] = None
|
||||
|
||||
|
||||
@app.post("/items/")
|
||||
async def create_item(item: Item):
|
||||
return item
|
||||
Reference in New Issue
Block a user