当前位置:   article > 正文

【Python】FastApi框架搭建部署_python fastapi 部署

python fastapi 部署

FastApi 是一个现代、快速(高性能)的 web 框架,用于基于标准Python构建的API。

官方网址:FastAPI

1.安装

1.1 环境信息

  1. # Python版本
  2. 3.8.0

1.2 安装 FastApi

  1. pip install fastapi
  2. # uvicorn 作为服务启动fastapi框架
  3. pip install uvicorn

2.使用

  1. # 导入FastAPI第三方包
  2. from fastapi import FastAPI
  3. # 创建FastAPI对象
  4. app = FastAPI()
  5. # 路由地址
  6. @app.get("/")
  7. # 后端方法
  8. def read_root():
  9.    return {"Hello": "World"}

3.部署

3.1 Gunicorn

Gunicorn 是一个 unix 上被广泛使用的高性能 Python WSGI Unix Http Server,和大多数的 Web 框架兼容,并具有实现简单,轻量级,高性能的特点。

3.1.1 安装 Gunicorn
  1. pip install uvicorn
  2. pip install gunicorn
3.1.2 运行项目
3.1.2.1 以配置文件的方式运行项目

配置文件

  1. # -*- coding=utf-8 -*-
  2. import os
  3. # 设置守护进程
  4. daemon = True
  5. # 监听内网端口
  6. bind = '0.0.0.0:8000'
  7. # 进程文件目录
  8. pidfile = './gunicorn.pid'
  9. chdir = './'
  10. # 工作模式
  11. worker_class='uvicorn.workers.UvicornWorker'
  12. # 并行工作进程数
  13. workers = 3
  14. # 线程数
  15. threads = 2
  16. # 设置最大并发量
  17. worker_connections = 1000
  18. loglevel = 'debug'
  19. access_log_format = '%(t)s %(p)s %(h)s "%(r)s %(s)s %(L)s %(b)s %(f)s" "%(a)s"'
  20. # 设置日志保存路径
  21. log_dir = './log'
  22. if not os.path.exists(log_dir):
  23. os.mkdir(log_dir)
  24. accesslog = './log/gunicorn_access.log'
  25. errorlog = './log/gunicorn_error.log'

运行项目

gunicorn main:app -c gunicorn.py

3.1.2.2 直接运行项目
gunicorn main:app -b 0.0.0.0:8000 -w 4 -k uvicorn.workers.UvicornWorker --daemon

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/weixin_40725706/article/detail/542731
推荐阅读
相关标签
  

闽ICP备14008679号