當前位置:首頁 » 文件管理 » django緩存

django緩存

發布時間: 2022-01-16 18:00:47

1. 如何清理django產生的緩存

你是使用多進程的方式啟動的吧,應該是部分進程更新了,刷新後會隨機使用某個進程執行代碼,所以會有舊的和新的同時出現,你重啟下django吧。

不過也有另一種可能你做了頁面換成,在view上使用了django的cache修飾器,這樣的話需要先刪除所有伺服器上的緩存。

如果解決了您的問題請採納!
如果未解決請繼續追問

2. django redis-cache服務重啟後,緩存還在嗎

還在,這個存儲在redis裡面,redis本身帶持久化機制,正常的伺服器重啟對這個沒有影響,除非你的redis 碰到突然crash這類的問題,可能會影響短時間內的數據正常。

3. django 怎麼先走緩存沒有數據在走views

用@cache_page裝飾器定義view級緩存,前提是定義好Cache的相關配置。

4. Django中app文件夾中的文件都是干什麼用的

C:\Users\用戶名\AppData裡面一般有三個文件夾,分別是Local,LocalLow,Roaming,簡單地來說,都是用來存放軟體的配置文件和臨時文件的,裡面有很多以軟體名稱或軟體公司命名的文件夾,理論上都可以刪除。例如,如果安裝了PhotoshopCS5,在AppData搜索Adobe,將搜到的文件和文件夾全部刪除,然後啟動Photoshop,已刪除的文件又會重新生成,但體積變小。刪除文件的時候千萬要小心,因為AppData同時存放了用戶帳戶的配置文件。隨著系統使用時間的增加和安裝軟體的增多,AppData佔用的空間會越來越大。有一個非常簡單的方法可以安全刪除AppData整個文件夾,就是刪除帳戶!更換用戶帳戶有一個好處是可以「重置」系統,減少垃圾文件,但也會帶來不少麻煩,系統好像回到了新安裝的狀態,某些軟體需要重新激活,極個別軟體需要重新安裝。附:其中三個文件夾的作用,裡面的文件可以隨心所欲地刪除。C:\Users\用戶名\AppData\Local\Temp裡面是臨時文件。C:\Users\用戶名\AppData\Local\Microsoft\Windows\TemporaryInternetFiles裡面是IE緩存文件(默認是隱藏的)。C:\Users\用戶名\AppData\Local\Microsoft\Windows\History裡面是瀏覽器歷史記錄(默認是隱藏的)。

5. Django什麼情況

在朋友和同事的極力推薦下最近開始看上了python,其實主要是還是因為python是2007年度語言,怎麼的也要與時俱進呀.最近一路看來有些心得,希望能與大家分享,小弟其實也只接觸不到一周的python,有說錯的地方還望大家指出改正.

不打算從py的語法基礎說起了,直接說說對django的心得:

接觸django首先需要了解可能就是他那個model,建立一個model就什麼都有了,這對於搞java得人員來說還是挺有吸引力的(當然貌似對於動態語言這都是小兒科),那麼讓我們先看一個model的例子:

偷懶了,直接拿django-admin裡面的User出來了

class User(models.Model):
username = models.CharField(_('username'), maxlength=30, unique=True, validator_list=[validators.isAlphaNumeric]))
first_name = models.CharField(_('first name'), maxlength=30, blank=True)
last_name = models.CharField(_('last name'), maxlength=30, blank=True)
email = models.EmailField(_('e-mail address'), blank=True)
password = models.CharField(_('password'), maxlength=128))
class Meta:
ordering = ('username',)
每個屬性就是一個庫表的欄位,定義起來非常簡單明了,models裡面提供了很多種類的Field類似上面的EmailField。不同的Field有不同的設置,可以看相應的原來來了解相關的設置.

在model class內部還有一個class Meta,這個Class的屬性制定了這個表的一些存取策略,例如這里的ordering。MetaClass裡面的屬性可以用model的_meta屬性取得。OK,那麼這樣一個model怎麼就能實現對資料庫表的靈活操作了呢。讓我們來看看吧。

首先先分析一下/django/django/db/models/base.py這個文件,其中包含了models.Model這類的定義:

看看class定義的第一行吧,第一行就夠我琢磨一陣子的了:

class Model(object):
__metaclass__ = ModelBase
Model採用了new style class定義,關於這個內容大家可以放狗看一下,第一行是一個__metaclass__屬性的定義,該屬性的值是ModelBase,這是一個類。__metaclass__的意思是,指定一個class,這個class的實例就是本class,相信您已經暈了。那麼就拿這個Model的例子來說明一下,如果沒有__metaclass__這個屬性,產生一個實例就是正常的流程,有了這個屬性流程會有改變:

首先調用BaseModel.__new__(cls, name, bases, attrs)這個方法,回返回的值是一個class類型,然後用這個class來創建實例。其實BaseModel就是Model的元類,來制定Model這個類的最終樣子。關於元類的更多信息請看這里

那麼我們的目光一下轉移到BaseModel這個類上,我有種直覺,Meta這個class最後可以用_meta來取就是在這里做的手腳,看一下BaseModel的定義吧,有點長:

class ModelBase(type):
"Metaclass for all models"
def __new__(cls, name, bases, attrs):
# If this isn't a subclass of Model, don't do anything special.
if name == 'Model' or not filter(lambda b: issubclass(b, Model), bases): #1
return super(ModelBase, cls).__new__(cls, name, bases, attrs)

# Create the class.
new_class = type.__new__(cls, name, bases, {'__mole__': attrs.pop('__mole__')}) #2
new_class.add_to_class('_meta', Options(attrs.pop('Meta', None))) #3
new_class.add_to_class('DoesNotExist', types.ClassType('DoesNotExist', (ObjectDoesNotExist,), {}))

# Build complete list of parents #4
for base in bases:
# TODO: Checking for the presence of '_meta' is hackish.
if '_meta' in dir(base):
new_class._meta.parents.append(base)
new_class._meta.parents.extend(base._meta.parents)

model_mole = sys.moles[new_class.__mole__]

if getattr(new_class._meta, 'app_label', None) is None:
# Figure out the app_label by looking one level up.
# For 'django.contrib.sites.models', this would be 'sites'.
new_class._meta.app_label = model_mole.__name__.split('.')[-2] #5

# Bail out early if we have already created this class.
m = get_model(new_class._meta.app_label, name, False) #6
if m is not None:
return m

# Add all attributes to the class.
for obj_name, obj in attrs.items():
new_class.add_to_class(obj_name, obj) #7

# Add Fields inherited from parents
for parent in new_class._meta.parents:
for field in parent._meta.fields:
# Only add parent fields if they aren't defined for this class.
try:
new_class._meta.get_field(field.name)
except FieldDoesNotExist:
field.contribute_to_class(new_class, field.name) #8

new_class._prepare()

register_models(new_class._meta.app_label, new_class) #9
# Because of the way imports happen (recursively), we may or may not be
# the first class for this model to register with the framework. There
# should only be one class for each model, so we must always return the
# registered version.
return get_model(new_class._meta.app_label, name, False) #10
簡單分析一下這個代碼:

1. 檢查class是否為Model的子類,不是的話,不做任何處理,直接傳給父類處理,也就相當於正常的處理了class,注意super在多重繼承的時候應該嚴格使用

2. 用type來創建類,創建的就是正常的ModelClass

3. 這句很重要,add_to_class是Model裡面的class方法,這個方法其實就是傳入name和value,給Model添加class屬性.看到了,原來神奇的_meta就是這么來的. 提到add_to_class方法,簡單看一下它的代碼:

def add_to_class(cls, name, value):
if name == 'Admin':
assert type(value) == types.ClassType, "%r attribute of %s model must be a class, not a %s object" % (name, cls.__name__, type(value))
value = AdminOptions(**dict([(k, v) for k, v in value.__dict__.items() if not k.startswith('_')]))
if hasattr(value, 'contribute_to_class'):
value.contribute_to_class(cls, name)
else:
setattr(cls, name, value)
add_to_class = classmethod(add_to_class)
最後一句是制定這個方法是class方法,特點就是方法的第一個參數是本class,其實classmethod就是一個裝飾器,在2。4之後可以使用@來簡寫。這里不得不提的是他對Admin的特殊處理,雖然AdminOption不是在admin模塊裡面的,但是這么做還是跟一個Admin的東東綁定起來了,在java的世界解耦是一件大事,看到下面還有對'contribute_to_class'這個方法的特殊處理,django為啥不弄的解耦點呢。而且同樣是包裝成Option,一個是在BaseModel裡面弄(那個Meta的包裝),一個在add_to_class方法裡面弄,實在有點不優雅,可能還沒了解太多,不知道他的深度用意吧。
4. Meta的集成,Option的這個類提供繼承方法

5. 取得applabel,就是把model的名字分割取到數第二個,我很喜歡-2這樣的設定

6. get_model方法取得緩存裡面的東西。

7. 把所有的class attr拿出來搞一遍,一般的屬性就setattr弄回去了,要是這個屬性有contribute_to_class這個callable屬性,那就執行之(Admin的處理完全也可以這樣,其實我們常用的objects就是用這個方法弄的)

8. 每個Field調用自己的contribute_to_class方法來進行特殊的處理

9. 進入緩存,,暫且叫緩存吧,裡面的東西大家看看很簡單 文件在 /django/django/db/models/loading.py 裡面還是有很多內容的

10.看注釋說的很清楚了,我們一定要在緩存裡面拿model。

6. 如何django中用redis緩存伺服器,求詳細教程。

django-redis 中文文檔
Andrey Antukh, [email protected] 4.7.0

翻譯: RaPoSpectre

1. 介紹

django-redis 基於 BSD 許可, 是一個使 Django 支持 Redis cache/session 後端的全功能組件.

1.1 為何要用 django-redis ?
因為:

持續更新
本地化的 redis-py URL 符號連接字元串
可擴展客戶端
可擴展解析器
可擴展序列器
默認客戶端主/從支持
完善的測試
已在一些項目的生產環境中作為 cache 和 session 使用
支持永不超時設置
原生進入 redis 客戶端/連接池支持
高可配置 ( 例如模擬緩存的異常行為 )
默認支持 unix 套接字
支持 Python 2.7, 3.4, 3.5 以及 3.6
1.2 可用的 django-redis 版本
穩定版本: 4.7.0
穩定版本: 3.8.4
1.3 我該使用哪個版本
版本號像 3.6, 3.7 … 等的是主要發行版本, 會包含向後不兼容的內容. 跟多信息請在升級前閱讀升級日誌.

版本號像 3.7.0, 3.7.1… 等的是小更新或者 bug 修復版本, 一般只會包含 bug 修復, 沒有功能更新.

1.4 依賴
1.4.1 Django 版本支持
django-redis 3.8.x 支持 django 1.4, 1.5, 1.6, 1.7 (或許會有 1.8)
django-redis 4.4.x 支持 django 1.6, 1.7, 1.8, 1.9 和 1.10
1.4.2 Redis Server 支持
django-redis 3.x.y 支持 redis-server 2.6.x 或更高
django-redis 4.x.y 支持 redis-server 2.8

7. 如何對django的model對象緩存

直接利用python提供的json包,在django model的定義中增加一個方法toJSON,利用django model 能訪問 _meta.fields 得到相關屬性而得到,例子如下: class Category(models.Model): autoid = models.AutoField(primary_key=True) email=models.Ch

8. 震驚,Django緩存中的數據頻頻丟失,究竟誰是幕後黑手

1.起因

昨天晚上嘗試使用celery對Django緩存進行定時任務的更新,
但是發現定時任務並不能刷新到Django中,
由此開始了一陣debug

2.經過

2.1問題出現的場景

想使用一個後台任務在緩存中存放一些信息,然後在Django中有request的時候可以快速獲取到頁面信息,
但是失敗了,用戶在進入主頁的時候並沒有獲取到後台任務在緩存中存放的信息

2.2嘗試解決問題經過

首先使用celery打出cache對象的內存地址以及一些簡單信息

原因: 不同py進程在from django.core.cache import cache中獲取的 cache 只是原型的復製品,並不是同一塊內存

2.3 解決問題的過程

當然,我們的問題並沒有解決,真正的原因是因為我一開始使用的是

CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'LOCATION': 'unique-snowflake',
}
}

我所使用的LocMemCache它的機制是不能做同步緩存的 (*見第三小節)

在更改為DatabaseCache之後,問題解決

CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.db.DatabaseCache', 'LOCATION': 'django_cache',
}
}

3.結論與文檔

廢話不多說,直接上官方文檔吧:

Local-memory caching

This is the default cache if another is not specified in your settings file. If you want the speed advantages of in-memory caching but don』t have the capability of running Memcached, consider the local-memory cache backend. This cache is per-process (see below) and thread-safe. To use it, set BACKEND to 「django.core.cache.backends.locmem.LocMemCache」. For example:

CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'LOCATION': 'unique-snowflake',
}
}

The cache LOCATION is used to identify indivial memory stores. If you only have one locmem cache, you can omit the LOCATION; however, if you have more than one local memory cache, you will need to assign a name to at least one of them in order to keep them separate.

Note that each process will have its own private cache instance, which means no cross-process caching is possible. This obviously also means the local memory cache isn』t particularly memory-efficient, so it』s probably not a good choice for proction environments. It』s nice for development.

著重標記最後一段文檔:

Note that each process will have its own private cache instance, which means no cross-process caching is possible.
注意每個進程都有自己的私有緩存實例,這意味著不可能有跨進程緩存

所以說,LocMemCache是不能用來做同步緩存的! 請使用別的任意Cache!

9. django 製作web網站,動態頁面數據已更新,但是無法刷新,這是怎麼回事是頁面緩存嗎

「再次刷新頁面時應該顯示該用戶已注冊過的提示」,我覺著似乎有些別扭:

通常注冊時應該包括這幾個邏輯:
1.需要認證登陸的頁面,自動跳轉到登陸頁
2.用戶登陸不成功,則重復登陸,提示注冊,
3.如果注冊時用戶名重復,提示繼續注冊,注冊成功後,
4.注冊成功後有兩種處理,一種與登陸成功一樣跳轉,或者是提示注冊成功
5.用戶登陸成功後自動跳轉到前面的那個需要認證的history url的頁
或者是登陸到系統主頁,並在上面提示欄里顯示用戶名,以及登陸狀態

你這種情況應該是注冊成功後如果是通常客戶端跳轉到了主頁面,你再刷新,刷新的是主頁面的URL,而不是post請求。所以仍然會顯示主頁信息。

如果你服務端用的是302 location的辦法,則瀏覽器仍然保留注冊的那個URL,再刷新應該是提示了post請求則既然是是刷新的post請求,這個時候應該提示已注冊過的信息。

如果你現在仍然顯示注冊成功信息,說明服務端可以重復注冊相同的用戶名。需要改一下業務邏輯。

10. 如何在django中使用redis做緩存伺服器

實現緩存的方式,有多種,本地內存緩存,資料庫緩存,文件系統緩存。這里介紹使用Redis資料庫進行緩存。

環境

  • redis

  • django-redis

  • 配置

  • settings.py

  • CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://127.0.0.1:6379/1", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", "PASSWORD": "mysecret"

  • }

  • }

  • }

  • python manage.py createcachetable1

  • 緩存有站點緩存,和單個view緩存

  • 站點緩存:

  • settings.py

  • MIDDLEWARE = [ # 站點緩存 , 注意必須在第一個位置

  • 'django.middleware.cache.UpdateCacheMiddleware',

  • ... # 站點緩存, 注意必須在最後一個位置

  • 'django.middleware.cache.FetchFromCacheMiddleware',

  • ]

  • 視圖緩存:

  • views.py

  • from django.shortcuts import renderfrom django.views.decorators.cache import cache_pagefrom cache.models import Foo# 在需要緩存的視圖上添加裝飾器, 參數是設置timeout 超時時間, 單位是秒, @cache_page(60)def index(request):

  • bar = Foo.objects.all() return render(request, 'cache/index.html', {'bar': bar})

熱點內容
提供華為雲雲資料庫 發布:2024-04-25 10:12:32 瀏覽:591
演算法設計手冊 發布:2024-04-25 10:03:24 瀏覽:80
linuxapache緩存 發布:2024-04-25 10:03:12 瀏覽:109
內務櫃密碼鎖去哪裡買 發布:2024-04-25 10:03:07 瀏覽:820
androidtimestamp 發布:2024-04-25 09:06:07 瀏覽:608
玩火影筆記本要什麼配置 發布:2024-04-25 08:34:59 瀏覽:209
sql性能監視器 發布:2024-04-25 08:21:48 瀏覽:832
吃雞ak配置什麼最好 發布:2024-04-25 08:15:46 瀏覽:447
firefox緩存目錄 發布:2024-04-25 08:00:31 瀏覽:940
我的世界國服怎麼免費弄伺服器 發布:2024-04-25 08:00:16 瀏覽:540