1. 程式人生 > 其它 >FastAPI學習筆記(二)-3.請求引數和驗證

FastAPI學習筆記(二)-3.請求引數和驗證

FastAPI的demo

 1 '''
 2 @author:invoker
 3 @project:fastapi202108
 4 @file: hello_world.py
 5 @contact:[email protected]
 6 @descript:
 7 @Date:2021/8/5 11:31
 8 @version: Python 3.7.8
 9 '''
10 from fastapi import FastAPI
11 from pydantic import BaseModel
12 from typing import Optional
13 
14 app = FastAPI()
15 16 class CityInfo(BaseModel): 17 province: str 18 country: str 19 is_affected: Optional[bool] = None 20 21 22 # 1.重點:使用裝飾器把方法變成介面 23 @app.get('/') 24 async def hello_world(): 25 return {'hello': 'world'} 26 27 # 2.被裝飾的函式中的引數若出現在路由的路徑中且用大括號,則為路徑引數 {city} 28 # 3.被裝飾的函式中的引數若沒有出現在路由的路徑中,則為查詢引數,query_string
29 @app.get('/city/{city}') 30 async def result(city: str, query_string: Optional[str] = None): 31 return {'city': city, 'query_string': query_string} 32 33 # 4.被裝飾的函式中的引數若沒有出現在路由的路徑中,且引數又不是普通型別,則該引數不為查詢引數,而是請求體的內容,CityInfo 34 35 @app.put('/city/{city}') 36 async def result(city: str, city_info: CityInfo):
37 return {'city': city, 'province':city_info.province,'country': city_info.country, 'is_affected': city_info.is_affected} 38 39 # 啟動命令: uvicorn hello_world:app --reload
View Code
啟動命令: uvicorn hello_world:app --reload
reload表示修改後可以及時響應,有點像VUE

在瀏覽器中輸入服務地址進行測試。
http://127.0.0.1:8000/docs#/

本文來自部落格園,作者:kaer_invoker,轉載請註明原文連結:https://www.cnblogs.com/invoker2021/p/15103716.html