บทความนี้สอนดึงที่อยู่ IP ของ POST Request สำคัญสำหรับความปลอดภัย เช่น Ban IP บางตัว หรือตรวจสอบ Request มากเกินไปจาก IP เดียว ใช้แพ็กเกจ協力廠商ง่ายๆ
ตัวอย่าง
สร้างโปรเจกต์และแอป ตั้งค่า urls เพิ่มแอปใน INSTALLED_APPS ไม่ใช้ Forms หรือ Models ของ Django
ติดตั้ง django-ipware:
pip install django-ipware
ไม่ต้องตั้งค่าเพิ่มเติม
ใน templates/home.html:
<!DOCTYPE html> <html>
<head> <title>tut</title> </head>
<body>
<form method="post" action="/" enctype="multipart/form-data">
<input type="text" id="text"/>
<input type="submit" value="submit"/>
</form>
</body> </html>
ใน urls.py ของแอป:
from django.urls import path, include
from . import views
urlpatterns = [
path('', views.home, name='home'),
]
ใน views.py:
from django.shortcuts import render
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')
ใน POST request ใช้ get_client_ip() ดู IP ที่ส่ง request มา คืนค่า 2 ค่า
เอาต์พุต
บน localhost ผลลัพธ์จะเป็น:
[23/Aug/2021 13:34:55] "GET / HTTP/1.1" 200 9999 127.0.0.1 False [23/Aug/2021 13:34:58] "POST / HTTP/1.1" 200 9999