由于自己已经使用过很久的fastapi了,但是到现在为止依然不能够非常熟练,多数时候依然会自己造轮子,走不少弯路,因此打算开始对fastapi进行系列总结。

安装

由于fastapi的启动需要uvicorn的配合,因此官方提供两种安装方式,第一种是全部安装,即:

1
pip install fastapi[all]

第二种是分开安装即:

1
2
pip install fastapi
pip install uvicorn[standard]

如果安装太慢的话,添加一个临时源吧,如下:

1
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple pyspide

使用

fastapi服务创建有两种方式,第一种是通过代码启动,第二种是在命令行启动,如果你需要调试代码,建议你使用第一种,当然,某些编辑器提供直接的调试启动方法,但是需要注意配置启动函数与启动对象。这里给出两种启动方式:

1
2
3
4
5
6
7
8
9
10
11
12
13
from fastapi import FastAPI
import uvicorn # 必须添加这个库

app = FastAPI()


@app.get("/")
async def root():
return {"message": "Hello World"}


if __name__ == '__main__':
uvicorn.run(app='main:app', host="127.0.0.1", port=8000, reload=True, debug=True)# 启动命令
1
2
3
4
5
6
7
8
9
10
11
from fastapi import FastAPI

app = FastAPI()


@app.get("/")
async def root():
return {"message": "Hello World"}

# 在文件目录下的命令行中输入以下命令:
# uvicorn main:app --host '0.0.0.0' --port 8080 --reload

uvicorn参数解释:

  • main: 指定主程序文件main.py文件, 如果main.py文件改成test.py 则命令也需要改为uvicorn test:app
  • app:在main.py中使用app = FastAPI()创建的对象
  • –host:远程主机ip,如果是本地则可以不要这个参数
  • –host:端口号
  • –reload:在修改源代码后程序会自动重新加载不用退出重新启动

基础配置

在启动之初,fastapi提供一些关于swagger界面的配置信息:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
from fastapi import FastAPI

app = FastAPI(
title="My Super Project",
description="This is a very fancy project, with auto docs for the API and everything",
version="2.5.0",
)


@app.get("/items/")
async def read_items():
return [{"name": "Foo"}]

if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=8080, access_log=False, debug=True)

同时支持对跨域的配置:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#可跨域访问的域名
origins = [
"http://localhost",
"http://localhost:8080",
]

#可跨域访问的基本请求设置
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)

更多详细的配置可以查看FastAPI的源码进行查看。