前言
筆者搭建環(huán)境 IIS + wfastcgi + flask + python3.6票渠,因為flask作為主站的一個應用程序,故訪問諸如:http://localhost/flaskweb時芬迄,app.route('/')
會發(fā)生404錯誤问顷。
- 網(wǎng)站結構
Site
|-Appliction_via_aspnet
|-Appliction_via_php
|-flaskweb
|-app.py
|-web.config
- app.py
from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
return "Hello from FastCGI via IIS!"
@app.errorhandler(404)
def not_found(error):
return "not found page"
if __name__ == "__main__":
app.run()
- web.config
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<handlers>
<add name="Python FastCGI" path="*" verb="*" modules="FastCgiModule" scriptProcessor="C:\Python36\python.exe|C:\flaskweb\wfastcgi.py" resourceType="Unspecified" />
</handlers>
</system.webServer>
<appSettings>
<add key="WSGI_HANDLER" value="app.app" />
<add key="PYTHONPATH" value="D:\flaskweb" />
<add key="WSGI_LOG" value="D:\flaskweb\web.log" />
</appSettings>
</configuration>
解決方法出自Stack Overflow: https://stackoverflow.com/a/36033627
添加middleware解決 flask 的 url prefix / subpath 問題。
from flask import Flask
class PrefixMiddleware(object):
def __init__(self, app, prefix=''):
self.app = app
self.prefix = prefix
def __call__(self, environ, start_response):
if environ['PATH_INFO'].startswith(self.prefix):
environ['PATH_INFO'] = environ['PATH_INFO'][len(self.prefix):]
environ['SCRIPT_NAME'] = self.prefix
return self.app(environ, start_response)
else:
start_response('404', [('Content-Type', 'text/plain')])
return ["This url does not belong to the app.".encode()]
prefix = '/flaskweb' # 改成你需要的URL前綴
app = Flask(__name__)
app.wsgi_app = PrefixMiddleware(app.wsgi_app, prefix=prefix)
@app.route('/')
def index():
return "Hello from FastCGI via IIS!"
@app.errorhandler(404)
def not_found(error):
return "not found page"
if __name__ == "__main__":
app.run()
以上