Parse X-Forwarded-For to get ip with werkzeug on Heroku

旧时模样 提交于 2019-11-30 20:27:50

Werkzeug (and Flask) store headers in an instance of werkzeug.datastructures.Headers. You should be able to do something like this:

provided_ips = request.headers.getlist("X-Forwarded-For")
# The first entry in the list should be the client's IP.

Alternately, you could use request.access_route (thanks @Bastian for pointing that out!):

provided_ips = request.access_route
# First entry in the list is the client's IP
David Dehghan

This is what I use in Django. See this https://docs.djangoproject.com/en/dev/ref/request-response/#django.http.HttpRequest.get_host

Note: At least on Heroku HTTP_X_FORWARDED_FOR will be an array of IP addresses. The first one is the client IP the rest are proxy server IPs.

in settings.py:

USE_X_FORWARDED_HOST = True

in your views.py:

if 'HTTP_X_FORWARDED_FOR' in request.META:
    ip_adds = request.META['HTTP_X_FORWARDED_FOR'].split(",")   
    ip = ip_adds[0]
else:
    ip = request.META['REMOTE_ADDR']
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!