You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

无法在IIS中以应用程序形式托管Flask应用,出现404错误

在IIS默认网站下部署Flask子应用(解决404问题)

我已经成功把Flask应用作为独立网站部署在IIS上,但现在想把它改成默认网站下的子应用,这样就能通过服务器名/应用别名访问,还能在默认网站下部署其他测试应用。尝试过相关配置但一直报404错误,提示“请求的URL在服务器上未找到”。

我的Flask应用代码如下:

from flask import Flask, render_template, request
import subprocess
import pandas as pd

app = Flask(__name__, template_folder='.')

pd.set_option('display.max_columns', None)

@app.route('/')
def index():
    return render_template('test.html')


@app.route('/execute_script', methods=['POST'])
def execute_script():
    foldersf = request.form['foldersf']
    datef = request.form['datef']
    folderss = request.form['folderss']
    dates = request.form['dates']

    # 调用Python脚本并传入参数
    try:
        result = subprocess.run(
            [r'C:\Python\python.exe', 'job.py', foldersf, datef,
             folderss, dates],
            stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)

        # 检查脚本执行是否成功
        if result.returncode == 0:
            output = result.stdout.strip()
            additional_message = "Script executed successfully"
            combined_output = output + '\n' + additional_message
            return combined_output, 200, {'Content-Type': 'text/plain'}
        else:
            error_message = result.stderr.strip()
            return f'Error executing script: {error_message}', 500, {'Content-Type': 'text/plain'}
    except Exception as e:
        return f'Error executing script: {str(e)}'

if __name__ == '__main__':
    app.run(debug=True)

解决步骤

1. 调整Flask应用的路由前缀

作为IIS子应用部署时,Flask需要识别子应用的别名路径,否则路由匹配会失败导致404。修改app.py添加前缀支持:

from flask import Flask, render_template, request
import subprocess
import pandas as pd
import os

# 从环境变量获取子应用别名,或者直接指定(比如'/flask-app')
app_root = os.environ.get('SCRIPT_NAME', '/flask-app')
app = Flask(__name__, template_folder='.', static_url_path=f'{app_root}/static', static_folder='static')
app.config['APPLICATION_ROOT'] = app_root

pd.set_option('display.max_columns', None)

@app.route('/')
def index():
    return render_template('test.html')

# 其他路由保持不变

2. 配置IIS默认网站下的子应用

  • 打开IIS管理器,找到Default Web Site,右键选择添加应用程序
  • 别名:输入子应用名称(比如flask-app)
  • 应用程序池:选择之前为Flask创建的应用池(确保池的.NET CLR版本设置为无托管代码)
  • 物理路径:指向包含app.py和test.html的应用文件夹

3. 修正Web.config配置

确保应用目录下的web.config配置正确,重点匹配子应用别名:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <system.webServer>
    <handlers>
      <add name="Python FastCGI" path="*" verb="*" modules="FastCgiModule" scriptProcessor="C:\Python\python.exe|C:\Python\Lib\site-packages\wfastcgi.py" resourceType="Unspecified" requireAccess="Script" />
    </handlers>
    <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="app.py/{R:0}" />
        </rule>
      </rules>
    </rewrite>
    <httpErrors errorMode="Detailed" />
  </system.webServer>
  <appSettings>
    <add key="WSGI_HANDLER" value="app.app" />
    <add key="PYTHONPATH" value="你的应用文件夹绝对路径" />
    <add key="SCRIPT_NAME" value="/flask-app" /> <!-- 必须和子应用别名一致 -->
  </appSettings>
</configuration>

4. 权限检查

  • 给应用程序池标识(比如IIS AppPool\你的池名称)授予应用文件夹的读取和执行权限
  • 确保C:\Python目录、job.py所在目录也有对应权限
  • 如果test.html引用静态文件,静态文件目录也要配置相同权限

5. 测试与排查

重启IIS应用池和默认网站,访问http://服务器名/flask-app。若仍报错,开启IIS的失败请求跟踪,查看具体错误日志定位问题。


内容的提问来源于stack exchange,提问作者NewTech

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 20:57:03