我已经安装了Apache服务器,它正在通过mod_wsgi处理Flask响应。我已经通过别名注册了WSGI脚本:
[httpd.conf]
WSGIScriptAlias /service "/mnt/www/wsgi-scripts/service.wsgi"
我已经在上面的路径添加了相应的WSGI文件:
[/mnt/www/wsgi脚本/service.wsgi]
import sys
sys.path.insert(0, "/mnt/www/wsgi-scripts")
from service import application
我有一个简单的test 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[主机名]/service时,它按预期工作,我得到“Hello World!”回来。问题是,我不知道如何让其他路径工作,比如上面例子中的“上传”。这在独立的烧瓶里很管用,但在mod_wsgi下我被难住了。我唯一能想到的是在httpd.conf中为我想要的每个端点注册一个单独的WSGI脚本别名,但这会占用Flask的高级路由支持。有办法让这一切顺利吗?
在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进程的权限才能工作;通常,您会将其与实际的源代码分离,后者应该位于文件系统中的其他位置,并具有适当的权限。
相关问题 更多 >
编程相关推荐