【问题标题】:Python Django call_command permissions gunicorn+nginxPython Django call_command 权限 gunicorn+nginx
【发布时间】:2019-08-03 15:08:26
【问题描述】:

问题

当我尝试通过 gunicorn 执行 django 管理命令时收到 502 bad gateway

逻辑线

我认为问题出在权限上,像 gunicorn 这样的东西无法调用该命令。我这么说是因为我可以在本地不使用 gunicorn 的地方运行它。

我可以通过这两种方式运行它:

  • python manage.py runserver 之后,使用 Postman 触发它就可以了。

  • 第二个是终端调用python manage.py command_name,也可以。

  • 在生产中,我也可以使用python manage.py command_name 运行。但不是邮递员,因为它返回 502(主要问题)

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

代码

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) })

返回样本

<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 会议

[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 日志错误

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"

我试过的

  • 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 的错误日志吗?
  • 是的@Mahendra 我会用日志更新问题
  • gunicorn 本身的日志呢?他们说什么?
  • 我意识到这是gunicorn+nginx超时的问题。谢谢大家的帮助

标签: nginx permissions gunicorn manage.py django-commands


【解决方案1】:

我意识到这是超时的问题

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

Doc. 静默超过这么多秒的工人被杀死并重新启动。

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

解决方案

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

独角兽

我在 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;

重新启动 nginxgunicorn 效果很好

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-10-20
    • 1970-01-01
    • 2013-03-25
    • 2013-03-01
    • 2017-08-07
    • 1970-01-01
    • 2021-03-19
    • 2017-12-08
    相关资源
    最近更新 更多