gpt4 book ai didi

python - 如何将 Flask 路由与 Apache 和 mod_wsgi 一起使用?

转载 作者:太空狗 更新时间:2023-10-29 17:06:09 25 4
gpt4 key购买 nike

我已经设置了 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 对路由的支持。有什么办法可以做到这一点吗?

最佳答案

在您的 wsgi 文件中,您正在执行 from service import application,它仅导入您的 application 方法。

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

在您发表评论后,我想我应该稍微扩展一下答案:

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

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

虽然上面的方法有效,但这是不好的做法。 wsgi 文件需要 Apache 进程的权限才能工作;并且您通常将其与实际源代码分开,实际源代码应该在您的文件系统的其他地方,并具有适当的权限。

关于python - 如何将 Flask 路由与 Apache 和 mod_wsgi 一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9680073/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com