python - 如何使用 python 获取 DJANGO 中的客户端 IP 地址?

标签 python django

我有一个用python编程开发的django网站。当有人访问我的网站时,我想存储观看者唯一的 IP 地址。为此,我添加了如下代码。

def get_client_ip(request):
    """get the client ip from the request
    """
    #remote_address = request.META.get('REMOTE_ADDR')
    remote_address = request.META.get('HTTP_X_FORWARDED_FOR')or request.META.get('REMOTE_ADDR')
    # set the default value of the ip to be the REMOTE_ADDR if available
    # else None
    ip = remote_address
    # try to get the first non-proxy ip (not a private ip) from the
    # HTTP_X_FORWARDED_FOR
    x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
    if x_forwarded_for:
        proxies = x_forwarded_for.split(',')
        # remove the private ips from the beginning
        while (len(proxies) > 0 and proxies[0].startswith(PRIVATE_IPS_PREFIX)):
            proxies.pop(0)
            # take the first ip which is not a private one (of a proxy)
            if len(proxies) > 0:
                ip = proxies[0]
            print"IP Address",ip
    return ip

但它总是返回以下IP地址“127.0.0.1”。我究竟做错了什么?请有人帮我解决我的客户 IP 地址获取问题。提前致谢

最佳答案

您得到127.0.0.1,因为您正在本地计算机上使用环回地址访问该页面

当您部署应用程序并在浏览器中打开它时,您将获得您的公共(public)IP。

关于python - 如何使用 python 获取 DJANGO 中的客户端 IP 地址?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27702217/

相关文章:

python - Django 对于从 View 中识别移动请求您有什么建议?

python - Django: AttributeError - 对象没有属性

python - Spark -nlp : DocumentAssembler initializing failing with 'java.lang.NoClassDefFoundError: org/apache/spark/ml/util/MLWritable$class'

python - Django 的 Db2 驱动程序?

Python 开发环境

python - Django 休息 + Jinja2 : ValueError: dictionary update sequence element #0 has length 0; 2 is required

django - 来自数据字典的值 : hard to understand

python - 在最近的关键条件下加入 Spark DataFrames

python - 为什么我在导入时不必指定子模块?

python - 将现有的 Django 应用程序导入 Pycharm