亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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

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

絕地無雙 2023-12-29 15:42:15
我有一個小問題想問你。我使用 GEO IP 來定位我的用戶,我希望在用戶每次登錄時記錄此信息,以改善應用程序的用戶體驗。問題是它不會在每個連接上絕對保存任何內容。UserProfile 模型為空...有人對此有什么想法嗎?用戶/中間件.pyfrom .models import UserProfilefrom django.contrib.gis.geoip2 import GeoIP2from django.utils.deprecation import MiddlewareMixinclass 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)              主要/設置.pyMIDDLEWARE = [    ...    'user.middleware.LastLoginInfo',    ...]
查看完整描述

2 回答

?
婷婷同學_

TA貢獻1844條經驗 獲得超8個贊

只需進行一些更改即可:)


class LastLoginInfo(MiddlewareMixin):

    def process_request(self, request):

        if request.user.is_authenticated:


查看完整回答
反對 回復 2023-12-29
?
UYOU

TA貢獻1878條經驗 獲得超4個贊

首先,你的方法缺少參數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

    ...


]


查看完整回答
反對 回復 2023-12-29
  • 2 回答
  • 0 關注
  • 166 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號