Python Django call_command权限gunicorn + nginx

问题描述 投票:0回答:1

Problem

当我尝试通过gunicorn执行django管理命令时,接收502坏网关

Logic Line

我认为问题是关于权限,像gunicorn一样无法调用命令。我这样说是因为我可以在本地运行它,我不使用gunicorn。

我可以用这两种方法运行它:

  • python manage.py runserver然后用邮递员开火,那没关系。
  • 第二个是终端python manage.py command_name呼叫,也没关系。
  • 在制作时,我也可以使用python manage.py command_name。但不是邮递员,因为它返回502(主要问题)

PS。如果我删除call_command它返回200 ok,所以,似乎核心问题是执行此命令。

The code

class TestCommandView(views.APIView):
    def post(self, request):
        id = request.data['id']

        try:
            call_command('command_name', target_id=id)
            return Response({"status": "success"})
        except Exception as error:
            return Response({"status": "error: " + str(error) })

Return sample

<html>
    <head>
        <title>502 Bad Gateway</title>
    </head>
    <body bgcolor="white">
        <center>
            <h1>502 Bad Gateway</h1>
        </center>
        <hr>
        <center>nginx/1.14.0 (Ubuntu)</center>
    </body>
</html>

Gunicorn Conf

[Unit]
Description=gunicorn daemon
After=network.target

[Service]
User=ubuntu
Group=www-data
RuntimeDirectory=gunicorn
WorkingDirectory=/var/www/project
ExecStart=/var/www/project/venv/bin/ddtrace-run /var/www/project/venv/bin/guni$
Environment="DJANGO_SETTINGS_MODULE=project.settings.prod"

[Install]
WantedBy=multi-user.target

Nginx Log error

2019/03/13 13:43:38 [error] 27552#27552: *3128 upstream prematurely closed connection while reading response header from upstream, client: IP, server: api.project.com, request: "POST /api/project/endpoint/ HTTP/1.1", upstream: "http://unix:/tmp/project.sock:/api/project/endpoint/", host: "api.project.com"

What i've tried

  • sudo chown -R www-data:www-data /var/www/project
  • sudo chown -R ubuntu:ubuntu /var/www/project
  • 根据这个问题解决方案改变我在gunicorn配置上的环境值:Django call_command permissions nginx+gunicorn+supervisord。添加PYTHONPATH,但是这个人在supervisor配置上使用它,这个项目不使用supervisor,所以我试着把它放在gunicorn文件上,这只是一个尝试。
nginx permissions gunicorn manage.py django-commands
1个回答
0
投票

I realized it was a problem of timeout

根据其文档,gunicorn的默认超时为30秒。

Doc.沉默超过这么多秒的工人被杀死并重新开始。

我的请求超过30秒,因此,gunicorn杀死了进程,nginx返回502。

Solution

  • 更改gunicorn默认超时
  • 更改nginx超时

Gunicorn

我将超时选项添加到gunicorn ExecStart行

- 超时300

    ExecStart=/var/www/project/venv/bin/ddtrace-run /var/www/project/venv/bin/gunicorn --bind unix:/tmp/project.sock project.wsgi:application --access-logfile /home/ubuntu/gunicorn.log --error-logfile /home/ubuntu/gunicorn.error.log --timeout 720 --workers 3

Nginx

将此选项添加到nginx conf的HTTP部分

proxy_read_timeout 300s;

重新启动了nginx和gunicorn,这就像一个魅力

© www.soinside.com 2019 - 2024. All rights reserved.