栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

django --获取用户真实ip、中间件

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

django --获取用户真实ip、中间件

获取用户真实ip(中间件)

app下新建一个py文件

from django.utils.deprecation import MiddlewareMixin
from requests import Response
import requests
import threading


class GETAddressMiddleWare(MiddlewareMixin):
    '''获取用户IP的中间件'''

    def process_request(self, request):
        '''执行请求前的中间件'''
        ip = request.meta.get("HTTP_X_FORWARDED_FOR", "")
        if not ip:
            ip = request.meta.get('REMOTE_ADDR', "")
        client_ip = ip.split(",")[-1].strip() if ip else ""
        print('当前请求IP为-->{}'.format(client_ip))
        # t = threading.Timer(0, get_ip, (str(client_ip), ))
        # t.start()

    def process_response(self, request, response):
        # 基于请求响应
        return response

    def process_view(self, request, view_func, view_args, view_kwargs):
        '''
        #在视图之前执行 顺序执行
        #return view_func(request)
        '''

    def process_exception(self, request, exception):
        '''自定义异常处理器'''
        print(exception)
        # return HttpResponse(exception) #返回错误信息


def get_ip(ip: str):
    key = 'a90f24c2491eb***8'
    url = f'http://apis.juhe.cn/ip/ipNewV3?ip={ip}&key={key}'
    res = requests.get(url)
    try:
        dict_res: dict = res.json().get('result')
        print(f'国家  -->{dict_res.get("Country")}')
        print(f'省份  -->{dict_res.get("Province")}')
        print(f'市区  -->{dict_res.get("City")}')
        print(f'运营商-->{dict_res.get("Isp")}')
        print('=' * 20)
    except Exception as ext:
        pass

settings中加

MIDDLEWARE = [
	...
    'backstage.get_address_ip.GETAddressMiddleWare'
]

nginx代理如下配置

server中加

	proxy_set_header Host $http_host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/700879.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号