在centos7.6 下,安装了python3.8 版本,同时与python2 共存,因此安装fastapi的时候,应该使用pip3 进行安装
pip3 install fastapi
pip3 install uvicron
pip3 install gunicorn #管理uvicron应用
[root@iZh pytest]# cat main.py
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)
[root@iZh pytest]# python main.py
Traceback (most recent call last):
File "main.py", line 1, in <module>
from fastapi import FastAPI
ImportError: No module named fastapi
[root@iZhppytest]# python3 main.py
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.
[root@iZh pytest]# uvicorn main:app --reload
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]# pstree -ap|grep gunicorn
|-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]# kill -9 9362
[root@iZhp3blin25ak7ob1v9hfeZ pytest]# kill -9 9363
[root@iZhp3blin25ak7ob1v9hfeZ pytest]# kill -9 9364
[root@iZhp3blin25ak7ob1v9hfeZ pytest]# kill -9 9365
使用curl测试工具进行测试:
安装curl 工具:
yum -y install curl
访问测试:
curl 127.0.0.1:8000
[root@iZhp3b local]# curl 127.0.0.1:8000
{"message":"ok"} #返回测试数据
[root@iZ local]#
from fastapi import APIRouter
router = APIRouter()
#tags为表明这个方法的用途等等
@router.get('/index',tags=['myorder'])
async def readOrders():
return {"message":"allorders"}
from fastapi import FastAPI
from order import index
#导入router
app = FastAPI()
#配置router和api访问前缀路径
app.include_router(index.router,prefix="/order")
127.0.0.1:8000/order/index
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=["*"],
)