在 Django 中获取 POST 请求 IP 地址

server side programmingpythonprogramming

在本文中,我们将了解如何获取 POST 请求的 IP 地址。有时检查安全参数很重要。有时您可能需要禁止某些 IP,或者您可能需要检查是否有人从单个 IP 发送了太多请求。让我们看看如何使用第三方包轻松完成此操作。

示例

创建一个 Django 项目和一个应用程序。设置 urls 并执行一些基本操作,例如在 INSTALLED_APPS 中添加应用程序。

我们不会使用任何 Django 表单或模型。

首先,安装 django-ipware 包 −

pip install django-ipware

您不需要为此进行任何配置。

现在,转到 模板 → 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>

在这里,我们简单地为我们的表单创建了一个前端,它将用于检查 IP。

在应用程序的 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":
      # 我们在这里获取 ip
      client_ip, is_routable = get_client_ip(request)
      # 客户端 IP 是 IP 地址
print(client_ip, is_routable)
   return render(request,'home.html')

在这里,在 POST 请求中,我们使用 get_client_ip() 来查看请求来自哪个 IP,它返回两个值。

输出

请记住,我们使用的是 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

相关文章