Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Lấy địa chỉ IP từ request POST trong Django


Dùng gói django-ipware để lấy IP client thực sự (xử lý proxy, load balancer).

Cách dùng

  1. pip install django-ipware

  2. View:

    from ipware import get_client_ip
    def home(request):
        if request.method == "POST":
            client_ip, is_routable = get_client_ip(request)
            print(client_ip, is_routable)
        return render(request, 'home.html')

Kết quả

In ra IP (ví dụ 127.0.0.1) và is_routable (True/False cho biết IP công khai hay private).