基本包:
在centos7.6 下,安装了python3.8 版本,同时与python2 共存,因此安装fastapi的时候,应该使用pip3 进行安装
安装的模块:
pip3
install fastapi
pip3
install uvicron
pip3
install gunicorn
基本main.py 文件
[root@iZh pytest
]
from fastapi
import FastAPI
import uvicorn
app
= FastAPI
()
@app.get
("/")
def read_root
():
return {"message":"ok"}
if __name__
=='__main__':
uvicorn.run
(app
='main:app',host
="127.0.0.1",port
=8000,reload
=True,debug
=True
)
启动
python3 main.py 默认python为2的版本,系统自带不支持
[root@iZh pytest
]
Traceback
(most recent call last
):
File
"main.py", line
1, in <module
>
from fastapi
import FastAPI
ImportError
: No module named fastapi
[root@iZhppytest
]
INFO
: Uvicorn running on http
://127.0.0.1:8000 (Press CTRL
+C to quit
)
INFO
: Started reloader process
[9591] using statreload
INFO
: Started server process
[9599]
INFO
: Waiting
for application startup
.
INFO
: Application startup complete
.
uvicorn main:app --reload
[root@iZh pytest
]
INFO: Uvicorn running on http://127.0.0.1:8000
(Press CTRL+C to quit
)
INFO: Started reloader process
[9626
] using statreload
INFO: Started server process
[9633
]
INFO: Waiting
for application startup.
INFO: Application startup complete.
3.前两个都是阻塞式的,并且在控制台关闭之后,程序也就关闭了。使用gunicron 解决
gunicorn main:app -b 127.0.0.1:8000 -w 4 -k uvicorn.workers.UvicornH11Worker --daemon
关闭gunicron 进程 1. 查询进程pid
[root@iZh pytest
]
|-gunicorn,9362 /usr/local/bin/gunicorn main:app -b 127.0.0.1:8000 -w 4 -k uvicorn.workers.UvicornH11Worker --daemon
|-gunicorn,9363 /usr/local/bin/gunicorn main:app -b 127.0.0.1:8000 -w 4 -k uvicorn.workers.UvicornH11Worker --daemon
|-gunicorn,9364 /usr/local/bin/gunicorn main:app -b 127.0.0.1:8000 -w 4 -k uvicorn.workers.UvicornH11Worker --daemon
|-gunicorn,9365 /usr/local/bin/gunicorn main:app -b 127.0.0.1:8000 -w 4 -k uvicorn.workers.UvicornH11Worker --daemon
| `-
{gunicorn
},9377
| |-grep,9479 --color
=auto gunicorn
关闭进程
[root@iZhp3blin25ak7ob1v9hfeZ pytest
]
[root@iZhp3blin25ak7ob1v9hfeZ pytest
]
[root@iZhp3blin25ak7ob1v9hfeZ pytest
]
[root@iZhp3blin25ak7ob1v9hfeZ pytest
]
测试访问
使用curl测试工具进行测试:
安装curl 工具:
yum -y install curl
访问测试:
curl 127.0.0.1:8000
[root@iZhp3b local
]
{"message":"ok"}
[root@iZ local
]
fastapi 多文件
在项目目录下新建python包,例如orders包,即带有 init.py 文件的目录在python中新建普通的python文件:index.pyindex.py 文件中导入fastapi的路由,使用路由进行api的配置
from fastapi
import APIRouter
router
= APIRouter
()
@router.get
('/index',tags
=['myorder'])
async def readOrders
():
return {"message":"allorders"}
在项目入口文件中,将路由文件全部进行导入,并配置api路径
from fastapi
import FastAPI
from order
import index
app
= FastAPI
()
app.include_router
(index.router,prefix
="/order")
调用方法与主入口中app修饰下的方法相同调用即可
127.0.0.1:8000/order/index
fastapi 跨域设置
使用中间件进行设置,入口文件中进行设置即可。 CORSMiddleware
from fastapi.middleware.cors
import CORSMiddleware
基本配置,可跨域的域名,请求的方法等等
origins
= [
"http://localhost",
"http://localhost:8080",
]
app.add_middleware
(
CORSMiddleware,
allow_origins
=origins,
allow_credentials
=True,
allow_methods
=["*"],
allow_headers
=["*"],
)