[英]How do I use Flask routes with Apache and mod_wsgi?
我已经安装了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中为我想要的每个端点注册一个单独的WSGI脚本别名,但这会消除Flask的奇特路由支持。 有没有办法让这项工作?
在您的wsgi文件中,您正在from service import application
,该application
仅导入您的application
方法。
将其from service import app as 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进程的权限才能工作; 并且您通常将其与实际源代码(应该是文件系统中的其他位置)分开,并具有适当的权限。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.