【问题标题】:Passing JSON from Nginx to Gunicorn将 JSON 从 Nginx 传递到 Gunicorn
【发布时间】:2015-08-21 20:22:54
【问题描述】:

我使用 nginx 作为使用 gunicorn 的 Django 应用程序的代理服务器。 Django 应用程序绑定到http://127.0.0.1:8000。这是我从 etc/nginx/sites-enabled/parkitbackend 设置的 nginx:

server {

    server_name AA.BB.CC.DD;

    access_log off;

    location /static/ {
        autoindex on;
        alias /home/zihe/parkitbackend/parkitbackend/common-static/;
    }

    location / {
        proxy_pass http://127.0.0.1:8000;
    }
}

我正在使用 python 请求模块:

requests.post("http://AA.BB.CC.DD/dashboard/checkin/", data=unicode(json.dumps(payload), "utf8"))

将 JSON 对象发布到我的名为仪表板的 django 应用程序中,我在仪表板/views.py 中有一个名为 checkin 的函数来处理 JSON 对象。

我没有收到运行 JSON 发布脚本的任何错误。但是,Nginx 似乎无法将请求传递给绑定在 127.0.0.1:8000 的 gunicorn。我应该怎么做才能使用 Nginx 将 JSON 传递给我的 django 应用程序?谢谢!


补充说明: 我非常确定 JSON 发布代码和我的 django 应用程序可以正常工作,因为我通过将 Django 应用程序绑定到 http://AA.BB.CC.DD:8000 并在 python 中运行此代码来测试它:

requests.post("http://AA.BB.CC.DD:8000/dashboard/checkin/", data=unicode(json.dumps(payload), "utf8"))

我的 django 应用程序按预期收到了 JSON。

【问题讨论】:

  • 你的 gunicorn 是否真的绑定到了 8000 端口?你跑gunicorn --bind 127.0.0.1:8000 myapp了吗?
  • 其他请求是否通过 nginx 工作?
  • @charlesreid1 是的。我跑了 gunicorn parkitbackend.wsgi:application --bind 127.0.0.1:8000.
  • @DanielRoseman 似乎 nginx 能够很好地提供静态文件。这意味着一些 GET 请求通过了。
  • 不,这根本不是这个意思。静态文件不通过 gunicorn/Django。所以问题显然在于 nginx 和 gunicorn 之间的连接。这是你的完整配置吗?

标签: python django nginx gunicorn


【解决方案1】:

我检查了位于 /var/log/nginx/ 的 error.log。事实证明,我发送的 JSON 太大并出现此错误:

[error] 3450#0: *9 client intended to send too large body: 1243811 bytes, client: 127.0.0.1, server: _, request: "POST /dashboard/checkin/ HTTP/1.1", host: "127.0.0.1"

阅读此链接后:http://gunicorn-docs.readthedocs.org/en/19.3/deploy.html#nginx-configuration

我减小了 JSON 的大小并修改了 etc/nginx/sites-enabled/parkitbackend 如下:

upstream app_server {
    server 127.0.0.1:8000;
}

server {
    listen AA.BB.CC.DD:80;
    server_name = _;

    location / {
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_redirect off;

        proxy_pass http://app_server;
    }

    location /static/ {
        autoindex on;
        alias /home/username/parkitbackend/parkitbackend/common-static/;
    }

}

并在 /etc/nginx/nginx.conf 中替换了这一行:

include /etc/nginx/sites-enabled/*;

用这个:

include /etc/nginx/sites-enabled/parkitbackend;

问题就解决了。

【讨论】:

    猜你喜欢
    • 2023-03-15
    • 2021-05-02
    • 1970-01-01
    • 1970-01-01
    • 2011-07-03
    • 2011-02-03
    • 1970-01-01
    • 1970-01-01
    • 2011-02-26
    相关资源
    最近更新 更多