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

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

Django 1.11:為經過身份驗證的用戶禁用緩存

Django 1.11:為經過身份驗證的用戶禁用緩存

MM們 2023-03-08 14:23:38
我們有一個用 python 2.7 和 django 1.11 編寫的遺留應用程序(沒有要遷移的資源)。它還用于grappelli授權。我們嘗試Edit為一些頁面添加鏈接(每個頁面顯示一個Round對象的詳細信息),這些頁面應該只對有權編輯回合的授權用戶可見(APPNAME | round | Can change round在grappelli網絡界面中)。在模板中,權限檢查如下:{% if perms.round.can_change_round %}    &emsp;<a href="{{link_to_change_round}}" class="stuff-only-link">{% trans 'Edit' %}</a>{% endif %}當以下事件在很短的時間間隔內發生時,就會出現問題:有權編輯回合的用戶訪問頁面 - 并看到鏈接Edit。無權編輯回合的用戶(例如匿名用戶)訪問同一頁面 - 并且還看到了鏈接!相關設置 ( settings.py) 是:CACHES = {    'default': {    #   'BACKEND': 'django.core.cache.backends.dummy.DummyCache',        'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',    }}SOLO_CACHE = 'default'SOLO_CACHE_TIMEOUT = 5*60當我將緩存更改為 時dummy,問題就消失了。因此,完全禁用授權用戶的緩存似乎是一個顯而易見的解決方案。更準確地說:a) 如果用戶是匿名的(大多數真實站點用戶)——請求的頁面可以寫入緩存,也可以從緩存中讀??;b) 如果一個用戶被授權(大約 5-7 個用戶)——請求的頁面不能寫入緩存也不能從緩存中讀取。我如何實現這一目標?
查看完整描述

2 回答

?
慕妹3146593

TA貢獻1820條經驗 獲得超9個贊

您可以對模板的緩存部分進行分段,并從與用戶相關的緩存部分中省略,或者根據記錄的片段變量狀態緩存它們


查看完整回答
反對 回復 2023-03-08
?
臨摹微笑

TA貢獻1982條經驗 獲得超2個贊

經過一個小時的谷歌搜索后,找到并調整了答案。代碼是:


編輯:最初,緩存是基于功能的。因此,“/rounds/1”給出了與“/rounds/2”相同的(緩存的)值。我們將完整的 URL 添加到緩存鍵來解決這個問題。


# -*- encoding: utf-8 -*-

'''

Python >= 2.4

Django >= 1.0


Author: [email protected]

'''

# https://djangosnippets.org/snippets/2524/

# https://stackoverflow.com/questions/20146741/django-per-user-view-caching

# https://stackoverflow.com/questions/62913281/django-1-11-disable-cache-for-authentificated-users


from django.core.cache import cache


def cache_per_user(ttl=None, prefix=None):

    '''Decorador que faz cache da view pra cada usuario

    * ttl - Tempo de vida do cache, n?o enviar esse parametro significa que o

      cache vai durar até que o servidor reinicie ou decida remove-lo 

    * prefix - Prefixo a ser usado para armazenar o response no cache. Caso nao

      seja informado sera usado 'view_cache_'+function.__name__

    * cache_post - Informa se eh pra fazer cache de requisicoes POST

    * O cache para usuarios anonimos é compartilhado com todos

    * A chave do cache será uma das possiveis opcoes:

        '%s_%s'%(prefix, user.id)

        '%s_anonymous'%(prefix)

        'view_cache_%s_%s'%(function.__name__, user.id)

        'view_cache_%s_anonymous'%(function.__name__)

    '''

    def decorator(function):

        def apply_cache(request, *args, **kwargs):


            # No caching for authorized users:

            # they have to see the results of their edits immideately!


            can_cache = request.user.is_anonymous() and request.method == 'GET'


            # Gera a chave do cache

            if prefix:

                CACHE_KEY = '%s_%s'%(prefix, 'anonymous')

            else:

                CACHE_KEY = 'view_cache_%s_%s_%s'%(function.__name__, request.get_full_path(), 'anonymous')


            if can_cache:

                response = cache.get(CACHE_KEY, None)

            else:

                response = None


            if not response:

                print 'Not in cache: %s'%(CACHE_KEY)

                response = function(request, *args, **kwargs)

                if can_cache:

                    cache.set(CACHE_KEY, response, ttl)

            return response

        return apply_cache

    return decorator

然后在views.py:


from cache_per_user import cache_per_user as cache_page

#...

#

#

@cache_page(cache_duration)

def round_detail(request, pk):


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

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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