FastAPI学习笔记(一)-3.FastAPI初使用

 

 

 FastAPI的demo

 1 '''
 2 @author:invoker
 3 @project:fastapi202108
 4 @file: hello_world.py
 5 @contact:invoker2021@126.com
 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#/

 

 

 

posted @ 2021-08-05 15:58  kaer_invoker  阅读(55)  评论(0编辑  收藏  举报