使用mongodb的Flask/uWSGI/nginx应用程序超时

6
我有一个使用uWSGI/nginx的Flask Python Web应用程序,在使用pymongo时会出现问题,特别是在初始化MongoClient类时。当我尝试在使用pymongo时访问应用程序时,会出现以下nginx错误:
2019/02/19 21:58:13 [error] 16699#0: *5 recv() failed (104: Connection reset by peer) while reading response header from upstream, client: 127.0.0.1, server: example.com, request: "GET /api/test HTTP/1.1", upstream: "uwsgi://unix:/var/www/html/myapp/myapp.sock:”, host: “example.com”
这是我的小测试应用程序:
from flask import Flask
from flask_cors import CORS
from bson.json_util import dumps
import pymongo

DEBUG = True
app = Flask(__name__)
app.config.from_object(__name__)
CORS(app)

client = pymongo.MongoClient() # This line
db = client.myapp

@app.route('/api/test')
def test():
    item = db.items.find_one()
    return item['name']

def create_app(app_name='MYAPP'):
    return app

# if __name__ == '__main__':
#   app.run(debug=True, threaded=True, host='0.0.0.0')

如果我从命令行运行这个应用程序(python app.py),并且访问0.0.0.0:5000/api/test时它可以正常工作,所以我相信这只是uWSGI配置问题。我的第一个想法是在我的nginx配置文件中增加uwsgi_read_timeout参数:

uwsgi_read_timeout 3600

server {
    listen 80 default_server;
    listen [::]:80 default_server;

    server_name example.com www.example.com;

    location /api {
        include uwsgi_params;
        uwsgi_read_timeout 3600;
        uwsgi_pass unix:/var/www/html/myapp/myapp.sock;
    }

    location / {
      root /var/www/html/myapp;
      try_files $uri $uri/ /index.html;
    }

    #return 301 https://$server_name$request_uri;
}

但是它没有明显的效果。我的uWSGI应用作为服务运行,使用以下配置(myapp.ini):

[uwsgi]
module = wsgi:app

master = true
processes = 4
enable-threads = True

socket = /var/www/html/myapp/myapp.sock
chmod-socket = 660
vacuum = true

die-on-term = true

再次,所有的东西似乎都可以正常工作,除了当我尝试初始化pymongo时。最后,我的应用程序服务文件:

[Unit]
Description=uWSGI Python container server
After=network.target

[Service]
User=pi
Group=www-data
WorkingDirectory=/var/www/html/myapp
ExecStart=/usr/bin/uwsgi --ini /etc/uwsgi/apps-available/myapp.ini

[Install]
WantedBy=multi-user.target
1个回答

5

我认为问题在于你正在使用fork,这会导致PyMongo出现问题。

PyMongo是线程安全的,但不是进程安全的。一旦你以守护进程模式运行应用程序,就会进行fork处理。你需要在应用程序内部创建一个MongoClient,这样在进程启动后,你的线程才能看到它。

你可以尝试以下方法(我没有尝试过,通常我会将这样的内容包装在一个类中,并在init方法中进行处理):

def create_app(app_name='MYAPP'):
   app.client = pymongo.MongoClient(connect=False) # this will prevent connecting until you need it.
   app.db = app.client.myapp
   return app

阅读此文档:http://api.mongodb.com/python/current/faq.html#id3


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接