1-FastAPI新建服務
阿新 • • 發佈:2021-12-06
建立基礎服務
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI() # 例項化app
# 建立介面函式
@app.get('/')
def hellow_world():
return {'hello_world'}
請求傳參
# 建立校驗類用來校驗傳參 class Hellow(BaseModel): # 必填字串型別 hallow: str # 選填布林型別,有預設值 world: bool = None # 獲取路徑傳參 @app.get('/{parameter}') # 所有的查詢引數(/?queryParameter=dd) def hellow_world(parameter: str, queryParameter: str = None): return {'路徑引數': parameter, '查詢引數': queryParameter} # 獲取路徑傳參 @app.put('/{parameter}') # 所有的查詢引數(/?queryParameter=dd) def hellow_world(parameter: str, queryParameter: Hellow): return {'路徑引數': parameter, '查詢引數': queryParameter.hallow} # 如果想使用非同步api在函式前新增async: # 獲取路徑傳參 @app.get('/{parameter}') # 所有的查詢引數(/?queryParameter=dd) async def hellow_world(parameter: str, queryParameter: str = None): return {'路徑引數': parameter, '查詢引數': queryParameter}
啟動服務
# 啟動命令:uvicorn 檔名:例項名
# 修改檔案自動重啟命令
# 啟動命令:uvicorn hello_world:app --reload