为IIS + wfastcgi + flask + python

作者: gomibako | 来源:发表于2018-04-12 20:58 被阅读10次

前言

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

  • 网站结构
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()

以上

相关文章

网友评论

    本文标题:为IIS + wfastcgi + flask + python

    本文链接:https://www.haomeiwen.com/subject/bawfkftx.html