首页 文章

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

提问于
浏览
15

我已经安装了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 [hostname] / service时,它按预期工作,我得到“Hello World!”背部 . 问题是我不知道如何使其他路由工作,如上例中的“上传” . 这在独立的Flask中工作正常但在mod_wsgi下我很难过 . 我唯一可以想象的是在httpd.conf中为我想要的每个 endpoints 注册一个单独的WSGI脚本别名,但这会消除Flask的奇特路由支持 . 有没有办法让这项工作?

1 回答

  • 17

    在你的wsgi文件中,你正在做 from service import application ,它只导入你的 application 方法 .

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

    在你的评论之后,我想我会稍微扩展一下答案:

    你的wsgi文件是python代码 - 你可以在这个文件中包含任何有效的python代码 . 安装在Apache中的wsgi "handler"正在查找此文件中的应用程序名称,它将把请求移交给 . Flask类实例 - app = Flask(__name__) - 提供了这样的接口,但由于它的名称为 app 而不是 application ,因此在导入时必须使用别名 - 这就是from行所做的 .

    你可以 - 这完全没问题 - 只需执行此操作 application = Flask(__name__) 然后将Apache中的wsgi处理程序指向您的 service.py 文件 . 如果 service.py 是可导入的(即 PYTHONPATH 中的某个地方),则不需要中间的wsgi脚本 .

    虽然上述作品,但其做法不好 . wsgi文件需要Apache进程的权限才能工作;并且您通常将其与实际源代码(应该是文件系统中的其他位置)分开,并具有适当的权限 .

相关问题