Python+VS CodePythonインストール中程序猿阵线联盟-汇总各类技术干货

为IIS + wfastcgi + flask + python

2018-04-12  本文已影响10人  gomibako

前言

笔者搭建环境 IIS + wfastcgi + flask + python3.6,因为flask作为主站的一个应用程序,故访问诸如:http://localhost/flaskweb时,app.route('/')会发生404错误。

Site
  |-Appliction_via_aspnet
  |-Appliction_via_php
  |-flaskweb
    |-app.py
    |-web.config
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()
<?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()

以上

上一篇 下一篇

猜你喜欢

热点阅读