如何在IIS 10上运行Python+FastAPI?配置出错求排查
环境配置信息
- 系统:Windows Server 2019
- 已安装x64版本的httpPlatformHandler
- 为所有用户在
C:\python312-32\路径下安装了32位Python 3.12.1 - 已安装FastAPI库
- 创建了新应用程序池(Pool-A):以自定义账户(User-A)为标识,无托管代码,集成管道模式
- 创建
C:\python-logs\文件夹用于存储日志 - 创建
C:\python-app\文件夹,内含main.py文件 - 为User-A账户配置了
python312-32、python-logs、python-app三个文件夹的完全控制权限 - 将应用程序添加至路由
/python-app,关联Pool-A应用程序池
代码与配置文件
C:\python-app\main.py代码:
from fastapi import FastAPI app = FastAPI() @app.get("/") async def read_root(): return {"message": "Sample app"}
C:\python-app\web.config配置文件:
<?xml version="1.0" encoding="utf-8"?> <configuration> <system.webServer> <handlers> <add name="PythonHandler" path="*" verb="*" modules="httpPlatformHandler" resourceType="Unspecified"/> </handlers> <httpPlatform processPath="c:\python312-32\python.exe" arguments="c:\python-app\main.py --port %HTTP_PLATFORM_PORT%" stdoutLogEnabled="true" stdoutLogFile="c:\python-app\python.log" startupTimeLimit="60" processesPerApplication="16"> <environmentVariables> <environmentVariable name="SERVER_PORT" value="%HTTP_PLATFORM_PORT%" /> </environmentVariables> </httpPlatform> </system.webServer> </configuration>
报错信息
- HTTP Error 500.19 - 内部服务器错误
- 错误代码:0x80070003
- 配置错误:无法读取配置文件
问题根源与解决方法
错误代码0x80070003对应系统级错误"找不到指定路径",结合你的配置,主要问题集中在以下三点:
1. 应用程序池位数与Python不匹配
你安装的是x64版本的httpPlatformHandler,但Python是32位版本。默认情况下IIS应用程序池为64位模式,这会导致64位的httpPlatformHandler无法正确加载32位Python环境,触发路径找不到的错误。
解决: 打开IIS管理器,找到Pool-A应用程序池的高级设置,将"启用32位应用程序"选项设置为True。
2. 日志文件路径配置不一致
web.config中stdoutLogFile指定为c:\python-app\python.log,但你专门创建了C:\python-logs\用于存储日志。虽然User-A对python-app有权限,但系统可能对应用目录的日志写入有额外限制,导致配置读取失败。
解决: 将web.config中的stdoutLogFile修改为c:\python-logs\python.log,确保路径与实际日志文件夹一致。
3. FastAPI启动参数错误
直接运行main.py不会启动FastAPI的Web服务,需要通过uvicorn来启动。当前的arguments配置无法正确启动服务,进而触发配置加载异常。
解决: 修改web.config中httpPlatform节点的arguments为:
-m uvicorn main:app --port %HTTP_PLATFORM_PORT%
(注:httpPlatform默认工作目录为应用根目录C:\python-app\,无需指定main.py的全路径)
内容的提问来源于stack exchange,提问作者Daniel

