How do I get user IP address in django?

后端 未结 11 1330
野趣味
野趣味 2020-11-22 15:33

How do I get user\'s IP in django?

I have a view like this:

# Create your views
from django.contrib.gis.utils import GeoIP
from django.template impor         


        
11条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-22 16:35

    In my case none of above works, so I have to check uwsgi + django source code and pass static param in nginx and see why/how, and below is what I have found.

    Env info:
    python version: 2.7.5
    Django version: (1, 6, 6, 'final', 0)
    nginx version: nginx/1.6.0
    uwsgi: 2.0.7

    Env setting info:
    nginx as reverse proxy listening at port 80 uwsgi as upstream unix socket, will response to the request eventually

    Django config info:

    USE_X_FORWARDED_HOST = True # with or without this line does not matter
    

    nginx config:

    uwsgi_param      X-Real-IP              $remote_addr;
    // uwsgi_param   X-Forwarded-For        $proxy_add_x_forwarded_for;
    // uwsgi_param   HTTP_X_FORWARDED_FOR   $proxy_add_x_forwarded_for;
    
    // hardcode for testing
    uwsgi_param      X-Forwarded-For        "10.10.10.10";
    uwsgi_param      HTTP_X_FORWARDED_FOR   "20.20.20.20";
    

    getting all the params in django app:

    X-Forwarded-For :       10.10.10.10
    HTTP_X_FORWARDED_FOR :  20.20.20.20
    

    Conclusion:

    So basically, you have to specify exactly the same field/param name in nginx, and use request.META[field/param] in django app.

    And now you can decide whether to add a middleware (interceptor) or just parse HTTP_X_FORWARDED_FOR in certain views.

提交回复
热议问题