无法通过uwsgi将Flask模块链接到nginx
我觉得我可能漏掉了什么简单的东西。我能让一部分python/flask脚本通过nginx可用,但重要的部分就是不工作。以下是我的python代码:
#!/usr/bin/python
import flask
from flask import Flask, jsonify, render_template, request
import os
app = flask.Flask(__name__)
app.config['SERVER_NAME']='localhost'
@app.route("/stuff")
def index():
return render_template('index.html')
@app.errorhandler(404)
def page_not_found(e):
return render_template('404.html'), 404
def application(environ, start_response):
start_response("200 OK", [("Content-Type", "text/plain")])
return ["Hello World!"]
这是我启动uwsgi的代码:
sudo -u www-data uwsgi -s /tmp/myApp.sock --module MyApp
socket已经正确连接并且可以被nginx使用。
这是我的nginx配置片段:
location /test {
uwsgi_pass unix:/tmp/myApp.sock;
include uwsgi_params;
}
当我访问我的服务器的/test时,我得到了“Hello World!”这正是我期待的。但是当我访问/myserver/test/stuff时,我也得到了“Hello World!”,而不是我的index.html的内容(这个文件是有效的,我在其他地方也用过)。如果我输入/myserver/test/garbage.html,我得到的是一个通用的nginx 404错误,而不是我自定义的404页面。
有没有人能给我指个方向?
谢谢
--编辑--
谢谢你的回答,这确实有帮助,但并没有解决我所有的问题。
在我的uwsgi启动命令中添加“--callable app”确实把uwsgi服务器和nginx连接起来了。太好了!我可以确认这一点,因为我的自定义404页面确实被nginx返回了。
但是我得到的404是我能得到的全部。我无法访问我的index.html,尽管它和404.html在同一个目录下,拥有相同的所有者和权限。实际上这两个文件几乎是一样的,只是文本稍有不同。
这可能是期望的问题。我期待在http://(myserver)/test/stuff
找到我的index.html,但我却得到了404。
我是在错误的地方查找吗?还是我的flask、uwsgi或nginx有问题?谢谢
1 个回答
你的应用函数没有调用你的 Flask 应用,这就是为什么每个路由都返回“Hello World”,状态码是200。我想你有两个简单的选择。
第一个选择是去掉应用函数,直接用 application = app
来替代。
第二个选择是把 uwsgi 的那一行改成
sudo -u www-data uwsgi -s /tmp/myApp.sock --module MyApp --callable app
这样一来,你的应用函数就没什么用处了。
你可以在这里了解更多关于使用 uwsgi 的信息 这里。
编辑
根据我对 nginx 的了解,你的 nginx 配置应该像这样
location = /test { rewrite ^ /test/; }
location /test { try_files $uri @test; }
location @test {
include uwsgi_params;
uwsgi_param SCRIPT_NAME /test;
uwsgi_modifier1 30;
uwsgi_pass unix:/tmp/myApp.sock;
}
这和上面链接的 uwsgi 页面推荐的配置是一样的。看起来你并不是在根网址上运行,所以基本的配置是行不通的。