您好,登錄后才能下訂單哦!
django中怎么利用request獲取請求的IP 地址,相信很多沒有經(jīng)驗(yàn)的人對此束手無策,為此本文總結(jié)了問題出現(xiàn)的原因和解決方法,通過這篇文章希望你能解決這個(gè)問題。
pip install django-ipware
一般用法:
from ipware.ip import get_ip # 導(dǎo)入包 def view_test(request): ip = get_ip(request) # 獲取 request 的請求 IP
site-packages/ipware/ip.py 源碼:
from .utils import is_valid_ip from . import defaults as defs NON_PUBLIC_IP_PREFIX = tuple([ip.lower() for ip in defs.IPWARE_NON_PUBLIC_IP_PREFIX]) TRUSTED_PROXY_LIST = tuple([ip.lower() for ip in defs.IPWARE_TRUSTED_PROXY_LIST]) def get_ip(request, real_ip_only=False, right_most_proxy=False): """ Returns client's best-matched ip-address, or None """ best_matched_ip = None for key in defs.IPWARE_META_PRECEDENCE_ORDER: value = request.META.get(key, request.META.get(key.replace('_', '-'), '')).strip() if value is not None and value != '': ips = [ip.strip().lower() for ip in value.split(',')] if right_most_proxy and len(ips) > 1: ips = reversed(ips) for ip_str in ips: if ip_str and is_valid_ip(ip_str): if not ip_str.startswith(NON_PUBLIC_IP_PREFIX): return ip_str if not real_ip_only: loopback = defs.IPWARE_LOOPBACK_PREFIX if best_matched_ip is None: best_matched_ip = ip_str elif best_matched_ip.startswith(loopback) and not ip_str.startswith(loopback): best_matched_ip = ip_str return best_matched_ip def get_real_ip(request, right_most_proxy=False): """ Returns client's best-matched `real` `externally-routable` ip-address, or None """ return get_ip(request, real_ip_only=True, right_most_proxy=right_most_proxy) def get_trusted_ip(request, right_most_proxy=False, trusted_proxies=TRUSTED_PROXY_LIST): """ Returns client's ip-address from `trusted` proxy server(s) or None """ if trusted_proxies: meta_keys = ['HTTP_X_FORWARDED_FOR', 'X_FORWARDED_FOR'] for key in meta_keys: value = request.META.get(key, request.META.get(key.replace('_', '-'), '')).strip() if value: ips = [ip.strip().lower() for ip in value.split(',')] if len(ips) > 1: if right_most_proxy: ips.reverse() for proxy in trusted_proxies: if proxy in ips[-1]: return ips[0] return None
用途:用裝飾器保存 訪問 IP
import re from django.core.cache import cache from django.shortcuts import render from ipware.ip import get_ip def get_ipv4(ip): """ 獲取 IPv4 :param ip: :return: """ # IP patterns ipv4_re = r'(?:25[0-5]|2[0-4]\d|[0-1]?\d?\d)(?:\.(?:25[0-5]|2[0-4]\d|[0-1]?\d?\d)){3}' # ipv6_re = r'\[[0-9a-f:\.]+\]' # (simple regex, validated later) ipv4 = re.search(ipv4_re, ip) if ipv4: return ipv4.group() return ip def save_ip(ip): """ 保存 IP :param ip: :return: """ ip = get_ipv4(ip) cache_ip = cache.get(ip) if not cache_ip: cache.set(ip, int(time.time()), CACHE_TIMEOUT_ARTICLE) visit_status = UserIP.objects.filter(ip=ip).exists() if visit_status: ip_info = UserIP.objects.get(ip=ip) ip_info.visit_num += 1 ip_info.save(update_fields=["visit_num", "time_updated"]) else: ip_info = UserIP( ip=ip, location=get_ip_location(ip), visit_num=1, ) ip_info.save() # 這是一個(gè)裝飾器的函數(shù),外層的函數(shù)是用來接收被裝飾函數(shù)的的 def save_visit_ip(func): """ 訪問視圖函數(shù)時(shí)保存 訪問ip :param func: :return: """ def inner(request, *args, **kwargs): ip = get_ip(request) save_ip(ip) return func(request, *args, **kwargs) return inner @save_visit_ip def status_code(request): code = request.GET.get("code", None) status_code = { "200": "<p>訪問正常<p>", "403": "<p>訪問被拒<p>", "404": "<p>資源未找到<p>", "500": "<p>服務(wù)器內(nèi)部錯(cuò)誤<p>", "503": "<p>服務(wù)器維護(hù)中<p>", } if code in status_code.keys(): response = HttpResponse(status_code[code]) response.status_code = int(code) return response return render(request, "web_status_code.html", locals())
看完上述內(nèi)容,你們掌握django中怎么利用request獲取請求的IP 地址的方法了嗎?如果還想學(xué)到更多技能或想了解更多相關(guān)內(nèi)容,歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。