Linux系统部署python程序
Linux系统部署python程序
- 1.简介
- 2.linux安装python环境
- 3.启动服务
1.简介
本次用到的FastAPI,Uvicorn,Gunicorn
FastAPI:
FastAPI 是一个现代、快速(高性能)的 web 框架,用于构建 APIs,基于 Python 3.6+ 类型提示。主要特性包括:
易于使用: 设计易于使用和学习,尽量减少开发时间。
简洁: 最小化代码复杂性,尽量减少开发者眼中的 bug。
基于标准: 基于(并完全兼容)开放标准:OpenAPI(以前称为 Swagger)和 JSON Schema。
Uvicorn:
Uvicorn 是一个基于 asyncio 的 ASGI 服务器,用于部署 Python 的异步 web 应用,它的目标是成为 Python 异步服务器网关接口(ASGI)规范的最快实现之一。Uvicorn 支持 HTTP/1.1 和 WebSockets,并且可以配合像 Starlette 和 FastAPI 这样的框架使用。
Gunicorn:
Gunicorn ‘Green Unicorn’ 是一个 Python WSGI HTTP 服务器,用于 UNIX。它是 Ruby 的 Unicorn 服务器的 Python 移植版。Gunicorn 的工作模式是预先分叉出多个进程来处理请求,这使得它在处理并发请求时具有较高的效率。然而,由于它基于同步的 WSGI,因此在处理 WebSockets 或长连接时可能不如 Uvicorn 高效。
2.linux安装python环境
miniconda安装包地址
1、下载安装包Miniconda3-latest-Linux-x86_64.sh
2、把安装包上传到服务器上,某个目录下
3、执行安装程序安装
bash Miniconda3-latest-Linux-x86_64.sh
4、一路yes;并且可以设置miniconda安装目录。
5、设置安装目录
Miniconda3 will now be installed into this location:
/root/miniconda3- Press ENTER to confirm the location
- Press CTRL-C to abort the installation
- Or specify a different location below[/root/miniconda3] >>>
/root/miniconda_soft
6.一路yes并初始化
7.更新服务器的配置内容
source ~/.bashrc
8.验证miniconda安装
conda -V
conda -version
9.设置 conda 镜像源
conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free/
conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main
10.设置 pip 镜像
pip config set global.index-url https://mirrors.aliyun.com/pypi/simple/
pip config set install.trusted-host mirrors.aliyun.com
11.创建python环境
conda create --prefix=/usr/local/conda_envirment/ms_iam_space python==3.10.14
进入激活环境
conda activate /usr/local/conda_envirment/ms_iam_space
3.启动服务
配置 Gunicorn 和 Uvicorn Workers
安装 Gunicorn,并配置多进程支持:
在python环境中下载下面的框架依赖
pip install gunicorn uvicorn fastapi
gunicorn app:app -w 4 -k uvicorn.workers.UvicornWorker --bind 0.0.0.0:8000
在项目代码的根目录下
pip install -r requirement.txt
下载完依赖
访问 http://<你的服务器IP>:8000,确认应用正常,Gunicorn正常运行。
-w 4:指定 4 个工作进程。
-k uvicorn.workers.UvicornWorker:使用 Uvicorn Worker。
app:app,第一个app是python文件名,即main文件,第二个是FastAPI的实例化的对象名,fastapi创建的app名称。
gunicorn 后台启动,Gunicorn以守护进程模式运行:,不占用shell;
gunicorn main:app -w 4 -k uvicorn.workers.UvicornWorker --bind 0.0.0.0:8000 -D \--timeout 300 \--access-logfile access.log \--error-logfile error.log
查看gunicorn 启动的线程/进程
ps aux | grep "gunicorn main:app"