使用中间件和 GeoIP 将用户数据保存在 UserProfile 中

我有一个小问题想问你。我使用 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',

    ...


]


绝地无双
浏览 56回答 2
2回答

婷婷同学_

只需进行一些更改即可:)class LastLoginInfo(MiddlewareMixin):    def process_request(self, request):        if request.user.is_authenticated:

UYOU

首先,你的方法缺少参数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    ...]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python