小编典典

如何在Apache和mod_wsgi中使用Flask路由?

flask

我已经安装了Apache服务器,并且正在通过mod_wsgi处理Flask响应。我已经通过别名注册了WSGI脚本:

[httpd.conf]

WSGIScriptAlias /service "/mnt/www/wsgi-scripts/service.wsgi"

我在上面的路径中添加了相应的WSGI文件:

[/mnt/www/wsgi-scripts/service.wsgi]

import sys
sys.path.insert(0, "/mnt/www/wsgi-scripts")

from service import application

我有一个简单的Flask Python测试脚本,提供了服务模块:

[/mnt/www/wsgi-scripts/service.py]

from flask import Flask

app = Flask(__name__)

@app.route('/')
def application(environ, start_response):
        status = '200 OK'
        output = "Hello World!"
        response_headers = [('Content-type', 'text/plain'),
                            ('Content-Length', str(len(output)))]
        start_response(status, response_headers)
        return [output]

@app.route('/upload')
def upload(environ, start_response):
        output = "Uploading"
        status = '200 OK'
        response_headers = [('Content-type', 'text/plain'),
                            ('Content-Length', str(len(output)))]
        start_response(status, response_headers)
        return [output]

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

当我转到我的网站URL [主机名] /服务时,它可以按预期运行,并且显示“ Hello World!”。问题是我不知道如何使其他路由正常工作,例如上例中的“上传”。这在独立的Flask中可以正常工作,但是在mod_wsgi下我很困惑。我能想象的唯一一件事就是在httpd.conf中为我想要的每个端点注册一个单独的WSGI脚本别名,但这剥夺了Flask的高级路由支持。有没有办法使这项工作?


阅读 486

收藏
2020-04-07

共1个答案

小编典典

在wsgi文件中,你正在执行from service import application,该操作仅导入你的application方法。

更改为from service import app as application,一切将按预期工作。

在你发表评论后,我想我会扩大答案:

你的wsgi文件是python代码-你可以在此文件中包含任何有效的python代码。安装在Apache中的wsgi“处理程序”正在此文件中查找应用程序名称,它将把请求传递给该文件。Flask类实例- app = Flask(__name__)提供了这样的接口,但是由于调用了app not application,因此在导入时必须为它加上别名-这就是from行的作用。

你可以-这样做很好-只需执行此操作application = Flask(__name__),然后将Apache中的wsgi处理程序指向你的service.py文件即可。如果service.py是可导入的(表示在中的某处PYTHONPATH),则不需要中间的wsgi脚本。

尽管以上方法可行,但实践不佳。wsgi文件需要Apache进程的许可才能工作。并且通常将其与实际源代码分开,后者应具有适当的权限,该源代码应位于文件系统上的其他位置。

2020-04-07