我有一个使用 python 编写的基于 api 的 Web 应用程序,使用 FastApi ,它使用 Uvicorn 或 Hypercorn 进行部署。这些都是基于 ASGI 的服务器。有没有办法在此基础上运行 IIS?
你绝对可以通过IIS运行。这是您有的两个可能的选择(我使用 Hypercorn):
HTTPPlaformHandler
<configuration>
<system.webServer>
<rewrite>
<rules>
<rule name="HTTPS force" enabled="true" stopProcessing="true">
<match url="(.*)" />
<conditions>
<add input="{HTTPS}" pattern="^OFF$" />
</conditions>
<action type="Redirect" url="https://{HTTP_HOST}{REQUEST_URI}" redirectType="Permanent" />
</rule>
</rules>
</rewrite>
<handlers>
<add name="httpplatformhandler" path="*" verb="*" modules="httpPlatformHandler" resourceType="Unspecified" />
</handlers>
<httpPlatform requestTimeout="00:05:00" startupTimeLimit="120" startupRetryCount="3" stdoutLogEnabled="true" stdoutLogFile=".\logs\python-stdout" processPath="[PATH TO YOUR PYTHON EXE]" arguments="-m hypercorn app.main:app -b 127.0.0.1:%HTTP_PLATFORM_PORT% --keep-alive 5 --worker-class asyncio --workers 9">
<environmentVariables>
<environmentVariable name="PORT" value="%HTTP_PLATFORM_PORT%" />
</environmentVariables>
</httpPlatform>
</system.webServer>
</configuration>
AspNetCoreModuleV2(如果使用这个,则必须有一个 config.py 才能正确绑定 URL 和端口。)
<system.webServer>
<handlers>
<add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
</handlers>
<aspNetCore processPath="[PATH TO PYTHON EXE]" arguments="-m hypercorn app.main:app --config file:config.py" stdoutLogEnabled="true" stdoutLogFile=".\logs\stdout" requestTimeout="00:26:00" /></system.webServer> </location><system.webServer></system.webServer> </configuration>
以下解决方案假设您的快速 api 应用程序在应用程序的根目录中使用
python -m venv venv
创建了一个虚拟环境。我使用了 uvicorn 但类似的参数也适用于 hypercorn。
网络配置
<configuration>
<system.webServer>
<handlers>
<add name="fastapi_app_handler"
path="*"
verb="*"
modules="httpPlatformHandler"
scriptProcessor="C:\fastapi_app\venv\Scripts\python.exe"
resourceType="Unspecified" requireAccess="Script" />
</handlers>
<httpPlatform processPath="C:\fastapi_app\venv\Scripts\python.exe"
arguments="-m uvicorn main:app --host 0.0.0.0 --port %HTTP_PLATFORM_PORT%"
stdoutLogEnabled="true" stdoutLogFile="C:\fastapi_app\iis_logs\python-stdout.log">
<environmentVariables>
<environmentVariable name="SERVER_PORT" value="HTTP_PLATFORM_PORT" />
</environmentVariables>
</httpPlatform>
</system.webServer>
主.py
import uvicorn
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def root():
a = "a"
b = "b" + a
return {"hello world": b}
if __name__ == "__main__":
uvicorn.run('main:app',reload=True)
目录:
您可以通过 IIS 管理器检查相应站点的 Handler Mappings,以查看您的处理程序是否在列表中,在此示例中,处理程序为“fastapi_app_handler”。在 IIS 中部署网站的一般步骤可以在此处找到。