【django framework】ModelSerializer+GenericAPIView,如何获取HTTP请求头中的信息(远程IP、UA等)

【django framework】ModelSerializer+GenericAPIView,如何获取HTTP请求头中的信息(远程IP、UA等)

某些时候,我们不得不获取调用当前接口的客户端IP、UA等信息,如果是第一次用Django Restframework,可能会有点懵逼,那么如何generics的时候获取请求头中的信息呢,让我们来看看吧。



1 创建接口,继承generics.CreateAPIView时获取

当继承generics.CreateAPIView时,根据RESTful接口标准,意味着我们要用它来创建一条记录,此时我们可以使用以下代码来获取请求头信息。

要在Django的generics.CreateAPIView中获取客户端的IP地址和User-Agent等信息,可以使用django的HttpRequest对象。HttpRequest对象包含了关于当前请求的所有信息,包括客户端IP地址和User-Agent等。

views.py中:

python 复制代码
from rest_framework import generics
from django.http import HttpRequest

class YourCreateAPIView(generics.CreateAPIView):
    def post(self, request, *args, **kwargs):
        # 获取客户端IP地址
        client_ip = self.get_client_ip(request)

        # 获取User-Agent
        user_agent = request.META.get('HTTP_USER_AGENT')

        # 现在可以使用client_ip和user_agent了
        # 具体处理逻辑...

        return super().post(request, *args, **kwargs)

    def get_client_ip(self, request: HttpRequest) -> str:
        """
        获取客户端IP地址的方法
        // 注意:也可以在此获取其他的参数,然后一并返回
        """
        x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
        if x_forwarded_for:
            # 如果使用了代理服务器,X-Forwarded-For会有多个IP,取第一个
            ip = x_forwarded_for.split(',')[0]
        else:
            ip = request.META.get('REMOTE_ADDR')
        return ip

2 读取接口,generics.ListAPIView时获取

在ListAPIView中获取客户端的IP地址和User-Agent等信息的方法与CreateAPIView中类似。你可以通过重写get()方法或者list()方法来获取这些信息。

python 复制代码
from rest_framework import generics
from django.http import HttpRequest

class YourListAPIView(generics.ListAPIView):
    def get(self, request, *args, **kwargs):
        # 获取客户端IP地址
        client_ip = self.get_client_ip(request)

        # 获取User-Agent
        user_agent = request.META.get('HTTP_USER_AGENT')

        # 现在可以使用client_ip和user_agent了
        # 具体处理逻辑...

        return super().get(request, *args, **kwargs)

    def get_client_ip(self, request: HttpRequest) -> str:
        """
        获取客户端IP地址的方法
        // 注意:也可以在此获取其他的参数,然后一并返回
        """
        x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
        if x_forwarded_for:
            # 如果使用了代理服务器,X-Forwarded-For会有多个IP,取第一个
            ip = x_forwarded_for.split(',')[0]
        else:
            ip = request.META.get('REMOTE_ADDR')
        return ip

相关推荐
小园子的小菜1 分钟前
LangChain核心进阶解析:输出解析、聊天记忆与回调机制实战
后端
freewcx5 分钟前
SpringDataRedis的序列化方式
后端
YHL8 分钟前
🚀 NestJS 后端开发实战:从设计模式到 CRUD 全栈
后端
晚安日记wanna8 分钟前
接口幂等性怎么保证
后端·面试
风中的小熊生气9 分钟前
Spring Boot 面试知识(一):从启动流程到 AOP 与事务失效
spring boot·后端·面试
神秘的猪头9 分钟前
Gin 项目为什么要分 Handler、Service、Repository?顺便讲透接口、依赖注入与指针
后端·go
程序员cxuan13 分钟前
DeepSeek V4.1 Flash 正式发布!
人工智能·后端·程序员
特立独行的猫A14 分钟前
AtomMQTT Broker — 用 Rust 实现的轻量级高性能 MQTT 消息代理
前端·后端·架构
the局外人17 分钟前
学习 FastAPI 的 Day 3:企业级目录与数据库迁移
后端·python·fastapi
mldong20 分钟前
AI Agent 不能自己签字:用 Python 工作流引擎给 AI 加一道人类审批闸门
后端·python·agent