簡體   English   中英

使用中間件和 GeoIP 將用戶數據保存在 UserProfile 中

[英]Save user data in UserProfile with Middleware and GeoIP

我有一個小問題想問你。 我使用 GEO IP 來定位我的用戶,我想在用戶每次登錄時記錄這些信息,以改善應用程序的用戶體驗。 問題是它不會在每次連接時完全不保存任何內容。 UserProfile 模型為空...

有人對此有想法嗎?

用戶/中間件.py

from .models import UserProfile
from django.contrib.gis.geoip2 import GeoIP2
from django.utils.deprecation import MiddlewareMixin

class LastLoginInfo(MiddlewareMixin):
  def geolocalisation(request):
    if request.user.is_authenticated():
        x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
        if x_forwarded_for:
            ip = x_forwarded_for.split(',')[0]
        else:
            ip = request.META.get('REMOTE_ADDR')
        
        device_type = ""
        browser_type = ""
        browser_version = ""
        os_type = ""
        os_version = ""
        
        if request.user_agent.is_mobile:
            device_type = "Mobile"
        if request.user_agent.is_tablet:
            device_type = "Tablet"
        if request.user_agent.is_pc:
            device_type = "PC"
        
        browser_type = request.user_agent.browser.family
        browser_version = request.user_agent.browser.version_string
        os_type = request.user_agent.os.family
        os_version = request.user_agent.os.version_string
        
        g = GeoIP2()
        location = g.city(ip)
        location_country = location["country_name"]
        location_city = location["city"]
        
        #UserProfile.objects.update_or_create(user=request.user, defaults={'ip_address_ua': request.data['ip']})
        UserProfile.objects.filter(user=request.user.pk).update(ip_address_ua=ip, device_ua=device_type, browser_ua=browser_type, os_device_ua=os_version, city_ua=location_city, country_ua=location_country)

        
      

主要/設置.py

MIDDLEWARE = [
    ...
    'user.middleware.LastLoginInfo',
    ...

]

只需進行一些更改:)

class LastLoginInfo(MiddlewareMixin):
    def process_request(self, request):
        if request.user.is_authenticated:

首先,您的方法缺少self參數。

def process_request(self, request):

如果這不能解決問題,那么我認為這里的問題是您的中間件的順序:

您應該確保您的中間件列在任何身份驗證中間件之后。

否則,這個語句永遠不會捕獲

        if request.user.is_authenticated():

例如,如果您使用django.contrib.auth.middleware.AuthenticationMiddleware ,則需要以下內容:

MIDDLEWARE = [
    ...
    'django.contrib.auth.middleware.AuthenticationMiddleware'
    'user.middleware.LastLoginInfo', # this must come AFTER auth middleware
    ...

]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM