前言:
根据微软的官方文档,共有两种方式部署Python Web项目,分别是FastCGI 和HttpPlatform 。由于 WFastCGI(FastCGI部署方式需要使用到的Python包)不再维护,微软建议使用HttpPlatform来部署Python web项目。
使用IIS部署FastAPI
一、下载依赖包(需激活虚拟环境)
pip freeze >> requirements.txt
pip download -r .\requirements.txt -d packages
(注意:Fastapi项目的requirements.txt中需包含uvicorn)
二、上传代码
将代码和下载的packages复制到服务器
三、 在modules中查找,确认IIS是否已安装httpPlatformHandler,否则需要手动安装。
httpPlatformHandler 下载地址:httpPlatformHandler_amd64.msi
四、创建虚拟环境
1)在服务器上创建虚拟环境,以管理员权限打开CMD或Powershell,然后执行以下命令
cd {your project folder}
virtualenv -p {python解释器路径/python.exe} venv
若服务器上不存在virtualenv,请手动安装(也可使用Pipenv、Poetry等创建虚拟环境)。C:\Software\Python311\python.exe为Python解析器地址,请根据具体情况进行修改。
2)安装依赖包
.\venv\Scripts\activate
pip install --no-index --find-links=packages -r requirements.txt
3)新建logs文件夹(IIS日志存放目录),并修改web.config文件。
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.webServer>
<handlers>
<add name="httpPlatformHandler" path="*" verb="*" modules="httpPlatformHandler" resourceType="Unspecified" />
</handlers>
<httpPlatform processPath=".\venv\Scripts\python.exe"
arguments="-m uvicorn app:app --port %HTTP_PLATFORM_PORT%"
stdoutLogEnabled="true"
stdoutLogFile=".\logs\log.log"
startupTimeLimit="120"
requestTimeout="00:05:00"
startupRetryCount="3"
processesPerApplication="8">
<environmentVariables>
<environmentVariable name="PORT" value="%HTTP_PLATFORM_PORT%" />
</environmentVariables>
</httpPlatform>
</system.webServer>
</configuration>
可通过查阅官方文档了解各个配置项的含义。
五、修改应用程序池标识及进程回收相关配置
-
修改程序池标识(可选,若文件夹的权限不足,可将程序池标识设置为local System)
关于应用程序池标识可以查阅官方文档来了解相关概念。 -
进程回收相关配置
长时间不访问API时,IIS会将站点的进程回收,下次访问时再重新启动进程,从而导致首次(或前几次,与web.config中配置的进程数量有关)访问较慢。可修改进程回收相关配置。
六、日志输出的中文乱码或出现中文时程序报错
- 在app.py或入口文件处加入下列代码:
import sys,io
sys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding='utf8')
- 配置日志信息时指明存储的编码:
def init_api_log():
log_path = "./logs"
Path(log_path).mkdir(exist_ok=True)
logger = logging.getLogger()
logger.setLevel(logging.INFO)
ch = logging.StreamHandler()
# 日志文件天循环
fh = TimedRotatingFileHandler(filename=Path(log_path).joinpath("server.log"), when='MIDNIGHT',
interval=1, backupCount=30, encoding='utf-8')
# 设置生成日志文件名的格式,以年-月-日来命名
# suffix设置,会生成文件名为log.2020-02-25.log
fh.suffix = "%Y-%m-%d.log"
# extMatch是编译好正则表达式,用于匹配日志文件名后缀
# 需要注意的是suffix和extMatch一定要匹配的上,如果不匹配,过期日志不会被删除。
fh.extMatch = re.compile(r"^\d{4}-\d{2}-\d{2}.log$")
formatter = logging.Formatter(
"%(asctime)s - %(module)s - %(funcName)s - line:%(lineno)d - %(levelname)s - %(message)s"
)
ch.setFormatter(formatter)
fh.setFormatter(formatter)
logger.addHandler(ch) # 将日志输出至屏幕
logger.addHandler(fh) # 将日志输出至文件
logger = logging.getLogger(__name__)
return logger
使用IIS部署Flask项目
前言:
根据Flask官方文档,Flask的部署方式有以下方式:Gunicorn、Waitress、mod_wsgi、uWSGI、gevent、eventlet、ASGI。由于Gunicorn无法在windows环境中使用,因此我们采用Waitress来部署Flask Web项目。
Flask和FastAPI的部署步骤一样,仅仅只是web.config不一样。
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.webServer>
<handlers>
<add name="httpPlatformHandler" path="*" verb="*" modules="httpPlatformHandler" resourceType="Unspecified" />
</handlers>
<httpPlatform processPath=".\venv\Scripts\python.exe"
arguments="-m waitress --port %HTTP_PLATFORM_PORT% app:app"
stdoutLogEnabled="true"
stdoutLogFile=".\logs\log.log"
startupTimeLimit="120"
requestTimeout="00:05:00"
startupRetryCount="3"
processesPerApplication="8">
<environmentVariables>
<environmentVariable name="PORT" value="%HTTP_PLATFORM_PORT%" />
</environmentVariables>
</httpPlatform>
</system.webServer>
</configuration>
(注意:Flask项目的requirements.txt中需包含waitress)
浙公网安备 33010602011771号