Flask应用部署IIS后主路由正常,其他路由及请求报HTTP 404错误
我将Python Flask应用部署至IIS Server,访问主URL(http://<myserverip>:8080/)时运行正常,但访问其他路由(如http://<myserverip>:8080/process)或发送GET/POST请求时,会返回以下404错误:
This error (HTTP 404 Not Found) means that Internet Explorer was able to connect to the website, but the page you wanted was not found. It’s possible that the webpage is temporarily unavailable. Alternatively, the website might have changed or removed the webpage
该应用在localhost环境下运行完全正常,我怀疑是IIS Server配置存在遗漏,相关代码示例如下:
main.py
from website import create_app app = create_app() if __name__ == '__main__': from waitress import serve serve(app)
web.config
<?xml version="1.0" encoding="utf-8"?> <configuration> <system.webServer> <handlers> <add name="PythonHandler" path="*" verb="*" modules="httpPlatformHandler" resourceType="Unspecified" requireAccess="Script"/> </handlers> <httpPlatform processPath="C:\Python\Python39\python.exe" arguments="-m waitress --port %HTTP_PLATFORM_PORT% wsgi:application" stdoutLogEnabled="true" stdoutLogFile="c:\home\LogFiles\python.log" startupTimeLimit="60" processesPerApplication="16"> <environmentVariables> <environmentVariable name="SERVER_PORT" value="%HTTP_PLATFORM_PORT%" /> </environmentVariables> </httpPlatform> </system.webServer> </configuration>
view.py 示例
from flask import Blueprint, render_template, request,jsonify,redirect,url_for,session from json import dumps import pandas as pd views = Blueprint('create_flow_chart', __name__) @views.route('/') def home(): <do something> return render_template("create-flow-chart.html",category=category, steps =dumps(text),product=product) @views.route('/process', methods=['POST','GET']) def send_selection(): <dosomething> return redirect(url_for('.do_create',steps=steps)) @views.route('/create') def do_create(): <dosomething> return render_template("create-flow-chart.html",category=category, steps = dumps(steps),product=product)
问题排查与解决方法
修正WSGI入口匹配
你的web.config中指定的WSGI入口是wsgi:application,但实际应用入口是main.py里的app对象。两种解决方式:- 创建
wsgi.py文件,内容为:from main import app as application - 直接修改
web.config的arguments参数,将wsgi:application改为main:app,让IIS正确定位Flask应用实例。
- 创建
添加IIS URL重写规则
IIS默认不会将所有路径请求转发给Flask应用,需配置重写规则确保非文件/目录请求都传递给httpPlatformHandler:
在web.config的<system.webServer>节点下添加:<rewrite> <rules> <rule name="Flask Routes" stopProcessing="true"> <match url=".*" /> <conditions logicalGrouping="MatchAll"> <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" /> <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" /> </conditions> <action type="Rewrite" url="/" /> </rule> </rules> </rewrite>注意:需先在IIS服务器上安装URL重写模块(可通过Web平台安装程序获取)。
确认Blueprint注册配置
检查create_app()方法中Blueprint的注册代码,确保已正确挂载到根路径:from .views import views app.register_blueprint(views) # 默认前缀为/,若指定前缀需确保路由匹配验证Waitress环境
在服务器上执行pip list确认Waitress模块已安装,同时检查web.config中Python路径C:\Python\Python39\python.exe是否正确指向部署环境的Python解释器。
内容的提问来源于stack exchange,提问作者yyii mm

