To get the client's IP address in Django, you can use the request.META dictionary, which contains metadata about the request. The key for the client's IP address is REMOTE_ADDR. Here's an example function that gets the client's IP address:

def get_client_ip(request):
    x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
    if x_forwarded_for:
        # X-Forwarded-For header may contain multiple IP addresses,
        # the client's IP address is the first one in the list
        ip = x_forwarded_for.split(',')[0]
    else:
        ip = request.META.get('REMOTE_ADDR')
    return ip

This function first checks if the HTTP_X_FORWARDED_FOR header is present, which is used by proxies to forward the client's IP address. If it's present, it splits the header value by commas and returns the first IP address in the list. Otherwise, it returns the value of the REMOTE_ADDR key.

get_client_iprequest get ip django

原文地址: https://www.cveoy.top/t/topic/838 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录