简体   繁体   中英

Passing JSON from Nginx to Gunicorn

I am using nginx as a proxy server for a Django app using gunicorn. The Django app is binded to http://127.0.0.1:8000 . And here's my nginx setup from etc/nginx/sites-enabled/parkitbackend:

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

I am using python requests module:

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

to post JSON objects to my django app called dashboard, where I have a function in dashboard/views.py called checkin to process the JSON object.

I did not receive any errors from running JSON posting script. However, Nginx does not seem to be able to pass the request to gunicorn binded at 127.0.0.1:8000. What should I do so I can use Nginx to pass the JSON to my django app? Thank you!


Additional notes: I am very sure JSON posting code and my django app work properly since I tested it by binding Django app to http://AA.BB.CC.DD:8000 and ran this code in python:

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

and my django app received the JSON as expected.

I checked the error.log located at /var/log/nginx/. It turns out that the JSON I was sending was too large and was giving this error:

[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"

After reading up on this link: http://gunicorn-docs.readthedocs.org/en/19.3/deploy.html#nginx-configuration

I reduced the size of the JSON and modified etc/nginx/sites-enabled/parkitbackend to be like this:

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/;
    }

}

and replaced this line in /etc/nginx/nginx.conf:

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

with this:

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

And the problem is resolved.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM