django-redis 文檔翻譯

一. 文檔管理

當咱們須要翻譯文檔時首先要考慮的是文檔的託管,本身作是一種辦法,但使用服務提供商的服務可讓咱們更專一的進行文檔翻譯而不用關心其餘操做。html

好比我在打算翻譯 django redis 文檔時先考慮本身搭,後來想到以前本身讀過的不少文檔都託管在 readthedocs 上,因而就決定使用它啦。python

使用方式很簡單,首先,咱們須要使用文檔生成工具生成文檔,我這裏使用的是 sphinx,安裝方式很簡單:git

  1. pip install sphinx

而後新建一個目錄存放文檔,在此目錄下輸入:github

  1. sphinx-quickstart

一路回車肯定便可,一個簡單的文檔管理目錄就生成好啦,而後咱們在 idex.rst 中進行書寫即。redis

conf.py 中是一些輸出的配置,這裏咱們打算在 readthedocs 託管文檔,因此就用 readthedocs 的主題,首先安裝主題:數據庫

  1. pip install sphinx_rtd_theme

而後在 conf.py 中更改主題配置:django

  1. html_theme = 'sphinx_rtd_theme'

此時咱們就能夠開始寫文章啦,寫完後,在當前目錄下執行:json

  1. make html

就能夠看到生成的 html 效果啦。 到這裏若是是打算本身託管,咱們能夠將生成的 html 放到本身服務器或者 github pages。 而我打算用 readthedocs 的服務,因此此時首先要把當前目錄的內容都上傳到 github。後端

上傳後在相應的倉庫內選擇 settings-> Integrations & services -> add service, 而後搜索 readthedocs 添加便可。緩存

而後登錄readthedocs,註冊帳號綁定 github,選擇相應倉庫,生成文檔便可~

這是筆者生成的文檔: django-redis 中文文檔

二. 翻譯

django-redis 中文文檔

Andrey Antukh, niwi@niwi.be 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.x 或更高

1.4.3 其餘依賴

全部版本的 django-redis 基於 redis-py >= 2.10.0.

2. 用戶指南

2.1 安裝

安裝 django-redis 最簡單的方法就是用 pip :

  1. pip install django-redis

2.2 做爲 cache backend 使用配置

爲了使用 django-redis , 你應該將你的 django cache setting 改爲這樣:

  1. CACHES = {
  2. "default": {
  3. "BACKEND": "django_redis.cache.RedisCache",
  4. "LOCATION": "redis://127.0.0.1:6379/1",
  5. "OPTIONS": {
  6. "CLIENT_CLASS": "django_redis.client.DefaultClient",
  7. }
  8. }
  9. }

爲了更好的互操做性並使鏈接字符串更加 「標準」, 從 3.8.0 開始 django-redis 使用 redis-py native url notation 做爲鏈接字符串.

URL 格式舉例

  1. redis://[:password]@localhost:6379/0
  2. rediss://[:password]@localhost:6379/0
  3. unix://[:password]@/path/to/socket.sock?db=0

支持三種 URL scheme :

  • redis://: 普通的 TCP 套接字鏈接
  • rediss://: SSL 包裹的 TCP 套接字鏈接
  • unix://: Unix 域套接字鏈接

指定數據庫數字的方法:

  • db 查詢參數, 例如: redis://localhost?db=0
  • 若是使用 redis:// scheme, 能夠直接將數字寫在路徑中, 例如: redis://localhost/0

在某些環境下鏈接密碼不是 url 安全的, 這時你能夠忽略密碼或者使用方便的 OPTIONS 設置:

  1. CACHES = {
  2. "default": {
  3. "BACKEND": "django_redis.cache.RedisCache",
  4. "LOCATION": "redis://127.0.0.1:6379/1",
  5. "OPTIONS": {
  6. "CLIENT_CLASS": "django_redis.client.DefaultClient",
  7. "PASSWORD": "mysecret"
  8. }
  9. }
  10. }

注意, 這樣配置不會覆蓋 uri 中的密碼, 因此若是你已經在 uri 中設置了密碼, 此設置將被忽略.

2.3 做爲 session backend 使用配置

Django 默承認以使用任何 cache backend 做爲 session backend, 將 django-redis 做爲 session 儲存後端不用安裝任何額外的 backend

  1. SESSION_ENGINE = "django.contrib.sessions.backends.cache"
  2. SESSION_CACHE_ALIAS = "default"

2.4 使用 django-redis 進行測試

django-redis 支持定製基於 Redis 的客戶端 ( 參考 可擴展 redis 客戶端 ) 能夠用來測試, 例如: 替換默認的客戶端爲 fakerdis (https://github.com/jamesls/fakeredis) 或者 mockredis (https://github.com/locationlabs/mockredis). 這樣作能夠不用依賴真的 redis server 作集成測試.

使用 fakeredis 舉例:

  1. import fakeredis
  2. CACHES = {
  3. "default": {
  4. "OPTIONS": {
  5. "REDIS_CLIENT_CLASS": "fakeredis.FakeStrictRedis",
  6. }
  7. }
  8. }

若是在測試完畢後想清理全部數據, 在你的 TestCase 中加入以下代碼:

  1. def tearDown(self):
  2. from django_redis import get_redis_connection
  3. get_redis_connection("default").flushall()

3. 進階使用

3.1 Pickle 版本

django-redis 使用 pickle 序列化幾乎全部數據.

默認使用最新的 pickle. 若是你想設置其餘版本, 使用 PICKLE_VERSION 參數:

  1. CACHES = {
  2. "default": {
  3. # ...
  4. "OPTIONS": {
  5. "PICKLE_VERSION": -1 # Use the latest protocol version
  6. }
  7. }
  8. }

3.2 套接字超時

套接字超時設置使用 SOCKET_TIMEOUT 和 SOCKET_CONNECT_TIMEOUT 參數:

  1. CACHES = {
  2. "default": {
  3. # ...
  4. "OPTIONS": {
  5. "SOCKET_CONNECT_TIMEOUT": 5, # in seconds
  6. "SOCKET_TIMEOUT": 5, # in seconds
  7. }
  8. }
  9. }

SOCKET_CONNECT_TIMEOUT : socket 創建鏈接超時設置

SOCKET_TIMEOUT : 鏈接創建後的讀寫操做超時設置

3.3 壓縮支持

django-redis 支持壓縮, 但默認是關閉的. 你能夠激活它:

  1. CACHES = {
  2. "default": {
  3. # ...
  4. "OPTIONS": {
  5. "COMPRESSOR": "django_redis.compressors.zlib.ZlibCompressor",
  6. }
  7. }
  8. }

使用 lzma 壓縮的例子:

  1. import lzma
  2. CACHES = {
  3. "default": {
  4. # ...
  5. "OPTIONS": {
  6. "COMPRESSOR": "django_redis.compressors.lzma.LzmaCompressor",
  7. }
  8. }
  9. }

3.4 memcached 異常行爲

在某些狀況下, redis 只做爲緩存使用, 當它關閉時若是你不但願觸發異常. 這是 memcached backend 的默認行爲, 你可使用 django-redis 模擬這種狀況.

爲了設置這種相似memcached 的行爲 ( 忽略鏈接異常 ), 使用 IGNORE_EXCEPTIONS 參數:

  1. CACHES = {
  2. "default": {
  3. # ...
  4. "OPTIONS": {
  5. "IGNORE_EXCEPTIONS": True,
  6. }
  7. }
  8. }

Also, you can apply the same settings to all configured caches, you can set the global flag in your settings:

固然,你也能夠給全部緩存配置相同的忽略行爲:

  1. DJANGO_REDIS_IGNORE_EXCEPTIONS = True

3.5 日誌忽略異常

當使用 IGNORE_EXCEPTIONS 或者 DJANGO_REDIS_IGNORE_EXCEPTIONS 參數忽略異常時, 你也許會用到 DJANGO_REDIS_LOG_IGNORED_EXCEPTIONS 參數來配置日誌異常:

  1. DJANGO_REDIS_LOG_IGNORED_EXCEPTIONS = True

若是你想設置指定的 logger 輸出異常, 只須要設置全局變量 DJANGO_REDIS_LOGGER 爲 logger 的名稱或其路徑便可. 若是沒有 logger 被設置而且 DJANGO_REDIS_LOG_IGNORED_EXCEPTIONS=True 時此參數將取 name :

  1. DJANGO_REDIS_LOGGER = 'some.specified.logger'

3.6 永不超時設置

django-redis comes with infinite timeouts support out of the box. And it behaves in same way as django backend contract specifies:

django-redis 支持永不超時設置. 其表現和 django backend 指定的相同:

  • timeout=0 當即過時
  • timeout=None 永不超時
  1. cache.set("key", "value", timeout=None)

3.7 經過值 (value) 獲取 ttl (time to live)

With redis, you can access to ttl of any stored key, for it, django-redis exposes ttl function.

It returns:

在 redis 中, 你能夠獲取任何 key 的 ttl, django-redis 也支持獲取 ttl 的函數:

它返回:

  • 0 key 不存在 (或已過時).
  • None key 存在但沒有設置過時.
  • ttl 任何有超時設置的 key 的超時值.

以 keys 搜索過時:

  1. >>> from django.core.cache import cache
  2. >>> cache.set("foo", "value", timeout=25)
  3. >>> cache.ttl("foo")
  4. 25
  5. >>> cache.ttl("not-existent")
  6. 0

3.8 expire & persist

除了簡單的 ttl 查詢, 你可使用 persist 或者 expire 方法讓一個值永久存在或者指定一個新的過時時間:

使用 persist 的例子:

  1. >>> cache.set("foo", "bar", timeout=22)
  2. >>> cache.ttl("foo")
  3. 22
  4. >>> cache.persist("foo")
  5. >>> cache.ttl("foo")
  6. None

使用 expire 的例子:

  1. >>> cache.set("foo", "bar", timeout=22)
  2. >>> cache.expire("foo", timeout=5)
  3. >>> cache.ttl("foo")
  4. 5

3.9 locks

django-redis 支持 redis 分佈式鎖. 鎖的線程接口是相同的, 所以你可使用它做爲替代.

使用 python 上下文管理器分配鎖的例子:

  1. with cache.lock("somekey"):
  2. do_some_thing()

3.10 掃描 & 刪除鍵 (keys)

django-redis 支持使用全局通配符的方式來檢索或者刪除鍵.

使用通配符搜索的例子

  1. >>> from django.core.cache import cache
  2. >>> cache.keys("foo_*")
  3. ["foo_1", "foo_2"]

這個簡單的寫法將返回全部匹配的值, 但在擁有很大數據量的數據庫中這樣作並不合適. 在 redis 的 server side cursors 2.8 版及以上, 你可使用 iter_keys 取代 keys 方法, iter_keys 將返回匹配值的迭代器, 你可使用迭代器高效的進行遍歷.

使用 server side cursors 搜索

  1. >>> from django.core.cache import cache
  2. >>> cache.iter_keys("foo_*")
  3. <generator object algo at 0x7ffa9c2713a8>
  4. >>> next(cache.iter_keys("foo_*"))
  5. "foo_1"

若是要刪除鍵, 使用 delete_pattern 方法, 它和 keys 方法同樣也支持全局通配符, 此函數將會返回刪掉的鍵的數量

使用 delete_pattern 的例子

  1. >>> from django.core.cache import cache
  2. >>> cache.delete_pattern("foo_*")

3.11 Redis 本地命令

django-redis 有限制的支持一些 Redis 原子操做, 例如 SETNXINCR 命令.

你能夠在 set() 方法中加上 nx 參數使用來使用 SETNX 命令

例子:

  1. >>> from django.core.cache import cache
  2. >>> cache.set("key", "value1", nx=True)
  3. True
  4. >>> cache.set("key", "value2", nx=True)
  5. False
  6. >>> cache.get("key")
  7. "value1"

當值 (value) 有合適的鍵 (key) 時, incrdecr 也可使用 Redis 原子操做

3.12 原生客戶端使用

在某些狀況下你的應用須要進入原生 Redis 客戶端使用一些 django cache 接口沒有暴露出來的進階特性. 爲了不儲存新的原生鏈接所產生的另外一份設置, django-redis 提供了方法 get_redis_connection(alias) 使你得到可重用的鏈接字符串.

  1. >>> from django_redis import get_redis_connection
  2. >>> con = get_redis_connection("default")
  3. >>> con
  4. <redis.client.StrictRedis object at 0x2dc4510>

警告 不是全部的擴展客戶端都支持這個特性.

3.13 鏈接池

django-redis 使用 redis-py 的鏈接池接口, 並提供了簡單的配置方式. 除此以外, 你能夠爲 backend 定製化鏈接池的產生.

redis-py 默認不會關閉鏈接, 儘量重用鏈接

3.13.1 配置默認鏈接池

配置默認鏈接池很簡單, 你只須要在 CACHES 中使用 CONNECTION_POOL_KWARGS 設置鏈接池的最大鏈接數量便可:

  1. CACHES = {
  2. "default": {
  3. "BACKEND": "django_redis.cache.RedisCache",
  4. ...
  5. "OPTIONS": {
  6. "CONNECTION_POOL_KWARGS": {"max_connections": 100}
  7. }
  8. }
  9. }

你能夠得知鏈接池已經打開多少鏈接:

  1. from django.core.cache import get_cache
  2. from django_redis import get_redis_connection
  3. r = get_redis_connection("default") # Use the name you have defined for Redis in settings.CACHES
  4. connection_pool = r.connection_pool
  5. print("Created connections so far: %d" % connection_pool._created_connections)

3.13.2 使用你本身的鏈接池子類

有時你想使用本身的鏈接池子類. django-redis 提供了 CONNECTION_POOL_CLASS 來配置鏈接池子類

myproj/mypool.py

  1. from redis.connection import ConnectionPool
  2. class MyOwnPool(ConnectionPool):
  3. # Just doing nothing, only for example purpose
  4. pass

setting.py

  1. # Omitting all backend declaration boilerplate code.
  2. "OPTIONS": {
  3. "CONNECTION_POOL_CLASS": "myproj.mypool.MyOwnPool",
  4. }

3.13.3 定製化的 connection factory

若是以前的方法都不合適, 你能夠定製 django-redis 的 connection factory 過程甚至徹底重寫.

django-redis 默認使用Django setting 中 DJANGO_REDIS_CONNECTION_FACTORY 參數指定的 django_redis.pool.ConnectionFactory 類產生鏈接.

ConnectionFactory 類的部分接口

  1. # Note: Using Python 3 notation for code documentation ;)
  2. class ConnectionFactory(object):
  3. def get_connection_pool(self, params:dict):
  4. # Given connection parameters in the `params` argument,
  5. # return new connection pool.
  6. # It should be overwritten if you want do something
  7. # before/after creating the connection pool, or return your
  8. # own connection pool.
  9. pass
  10. def get_connection(self, params:dict):
  11. # Given connection parameters in the `params` argument,
  12. # return a new connection.
  13. # It should be overwritten if you want to do something
  14. # before/after creating a new connection.
  15. # The default implementation uses `get_connection_pool`
  16. # to obtain a pool and create a new connection in the
  17. # newly obtained pool.
  18. pass
  19. def get_or_create_connection_pool(self, params:dict):
  20. # This is a high layer on top of `get_connection_pool` for
  21. # implementing a cache of created connection pools.
  22. # It should be overwritten if you want change the default
  23. # behavior.
  24. pass
  25. def make_connection_params(self, url:str) -> dict:
  26. # The responsibility of this method is to convert basic connection
  27. # parameters and other settings to fully connection pool ready
  28. # connection parameters.
  29. pass
  30. def connect(self, url:str):
  31. # This is really a public API and entry point for this
  32. # factory class. This encapsulates the main logic of creating
  33. # the previously mentioned `params` using `make_connection_params`
  34. # and creating a new connection using the `get_connection` method.
  35. pass

3.14 可擴展解析器

redis-py (django-redis 使用的 Redis 客戶端) 支持的純淨 Python Redis 解析器能夠知足大部分普通任務, 但若是你想要性能更好, 可使用 hiredis

hiredis 是一個用 C 寫的 Redis 客戶端, 而且他的解析器能夠用在 django-redis 中:

  1. "OPTIONS": {
  2. "PARSER_CLASS": "redis.connection.HiredisParser",
  3. }

3.15 可擴展客戶端

django_redis 設計的很是靈活和可配置。它提供了可擴展的後端,擁有易擴展的特性.

3.15.1 默認客戶端

咱們已經說明了默認客戶端幾乎全部的特色, 但有一個例外: 默認客戶端支持主從配置.

若是須要主從設置, 你須要更改 LOCATION 參數:

  1. "LOCATION": [
  2. "redis://127.0.0.1:6379/1",
  3. "redis://127.0.0.1:6378/1",
  4. ]

第一個字段表明 master 服務器, 第二個字段表明 slave 服務器.

警告 主從設置沒有在生產環境中通過大量測試

3.15.2 分片客戶端

此可擴展客戶端實現了客戶端分片, 它幾乎繼承了默認客戶端的所有功能. 若是須要使用, 請將配置改爲這樣:

  1. CACHES = {
  2. "default": {
  3. "BACKEND": "django_redis.cache.RedisCache",
  4. "LOCATION": [
  5. "redis://127.0.0.1:6379/1",
  6. "redis://127.0.0.1:6379/2",
  7. ],
  8. "OPTIONS": {
  9. "CLIENT_CLASS": "django_redis.client.ShardClient",
  10. }
  11. }
  12. }

警告 分片客戶端仍處於試驗階段, 請在生產環境中謹慎使用

3.15.3 集羣客戶端

咱們同時也在嘗試解決驚羣問題, 更多信息請閱讀Wikipedia

和上文講的同樣, 客戶端基本繼承了默認客戶端全部功能, 增長額外的方法以獲取/設置鍵 (keys)

設置舉例

  1. CACHES = {
  2. "default": {
  3. "BACKEND": "django_redis.cache.RedisCache",
  4. "LOCATION": "redis://127.0.0.1:6379/1",
  5. "OPTIONS": {
  6. "CLIENT_CLASS": "django_redis.client.HerdClient",
  7. }
  8. }
  9. }

一些其餘的設置:

  • CACHE_HERD_TIMEOUT: 設置集羣超時 (默認值爲: 60s)

3.16 可擴展序列器

客戶端在將數據發給服務器以前先會序列化數據. django-redis 默認使用 Python pickle 序列化數據.

若是須要使用 json 序列化數據, 使用 JSONSerializer

設置舉例

  1. CACHES = {
  2. "default": {
  3. "BACKEND": "django_redis.cache.RedisCache",
  4. "LOCATION": "redis://127.0.0.1:6379/1",
  5. "OPTIONS": {
  6. "CLIENT_CLASS": "django_redis.client.DefaultClient",
  7. "SERIALIZER": "django_redis.serializers.json.JSONSerializer",
  8. }
  9. }
  10. }

使用 MsgPack http://msgpack.org/ 進行序列化 (須要 msgpack-python 庫支持)

設置舉例

  1. CACHES = {
  2. "default": {
  3. "BACKEND": "django_redis.cache.RedisCache",
  4. "LOCATION": "redis://127.0.0.1:6379/1",
  5. "OPTIONS": {
  6. "CLIENT_CLASS": "django_redis.client.DefaultClient",
  7. "SERIALIZER": "django_redis.serializers.msgpack.MSGPackSerializer",
  8. }
  9. }
  10. }

3.17 可擴展 Redis 客戶端

django-redis 默認使用 redis.client.StrictClient 做爲 Redis 客戶端, 你可使用其餘客戶端替代, 好比以前在講測試時咱們用 fakeredis 代替真實客戶端.

使用 REDIS_CLIENT_CLASS in the CACHES 來配置你的客戶端, 使用 REDIS_CLIENT_KWARGS 提供配置客戶端的參數 (可選).

設置舉例

  1. CACHES = {
  2. "default": {
  3. "OPTIONS": {
  4. "REDIS_CLIENT_CLASS": "my.module.ClientClass",
  5. "REDIS_CLIENT_KWARGS": {"some_setting": True},
  6. }
  7. }
  8. }
相關文章
相關標籤/搜索