當咱們須要翻譯文檔時首先要考慮的是文檔的託管,本身作是一種辦法,但使用服務提供商的服務可讓咱們更專一的進行文檔翻譯而不用關心其餘操做。html
好比我在打算翻譯 django redis 文檔時先考慮本身搭,後來想到以前本身讀過的不少文檔都託管在 readthedocs 上,因而就決定使用它啦。python
使用方式很簡單,首先,咱們須要使用文檔生成工具生成文檔,我這裏使用的是 sphinx,安裝方式很簡單:git
pip install sphinx
而後新建一個目錄存放文檔,在此目錄下輸入:github
sphinx-quickstart
一路回車肯定便可,一個簡單的文檔管理目錄就生成好啦,而後咱們在 idex.rst
中進行書寫即。redis
conf.py
中是一些輸出的配置,這裏咱們打算在 readthedocs 託管文檔,因此就用 readthedocs 的主題,首先安裝主題:數據庫
pip install sphinx_rtd_theme
而後在 conf.py 中更改主題配置:django
html_theme = 'sphinx_rtd_theme'
此時咱們就能夠開始寫文章啦,寫完後,在當前目錄下執行:json
make html
就能夠看到生成的 html 效果啦。 到這裏若是是打算本身託管,咱們能夠將生成的 html 放到本身服務器或者 github pages。 而我打算用 readthedocs 的服務,因此此時首先要把當前目錄的內容都上傳到 github。後端
上傳後在相應的倉庫內選擇 settings
-> Integrations & services
-> add service
, 而後搜索 readthedocs 添加便可。緩存
而後登錄readthedocs,註冊帳號綁定 github,選擇相應倉庫,生成文檔便可~
這是筆者生成的文檔: django-redis 中文文檔
Andrey Antukh, niwi@niwi.be 4.7.0
翻譯: RaPoSpectre
django-redis 基於 BSD 許可, 是一個使 Django 支持 Redis cache/session 後端的全功能組件.
由於:
版本號像 3.6, 3.7 … 等的是主要發行版本, 會包含向後不兼容的內容. 跟多信息請在升級前閱讀升級日誌.
版本號像 3.7.0, 3.7.1… 等的是小更新或者 bug 修復版本, 通常只會包含 bug 修復, 沒有功能更新.
全部版本的 django-redis 基於 redis-py >= 2.10.0.
安裝 django-redis 最簡單的方法就是用 pip :
pip install django-redis
爲了使用 django-redis , 你應該將你的 django cache setting 改爲這樣:
CACHES = {
"default": {
"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": "redis://127.0.0.1:6379/1",
"OPTIONS": {
"CLIENT_CLASS": "django_redis.client.DefaultClient",
}
}
}
爲了更好的互操做性並使鏈接字符串更加 「標準」, 從 3.8.0 開始 django-redis 使用 redis-py native url notation 做爲鏈接字符串.
URL 格式舉例
redis://[:password]@localhost:6379/0
rediss://[:password]@localhost:6379/0
unix://[:password]@/path/to/socket.sock?db=0
支持三種 URL scheme :
指定數據庫數字的方法:
在某些環境下鏈接密碼不是 url 安全的, 這時你能夠忽略密碼或者使用方便的 OPTIONS 設置:
CACHES = {
"default": {
"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": "redis://127.0.0.1:6379/1",
"OPTIONS": {
"CLIENT_CLASS": "django_redis.client.DefaultClient",
"PASSWORD": "mysecret"
}
}
}
注意, 這樣配置不會覆蓋 uri 中的密碼, 因此若是你已經在 uri 中設置了密碼, 此設置將被忽略.
Django 默承認以使用任何 cache backend 做爲 session backend, 將 django-redis 做爲 session 儲存後端不用安裝任何額外的 backend
SESSION_ENGINE = "django.contrib.sessions.backends.cache"
SESSION_CACHE_ALIAS = "default"
django-redis 支持定製基於 Redis 的客戶端 ( 參考 可擴展 redis 客戶端 ) 能夠用來測試, 例如: 替換默認的客戶端爲 fakerdis (https://github.com/jamesls/fakeredis) 或者 mockredis (https://github.com/locationlabs/mockredis). 這樣作能夠不用依賴真的 redis server 作集成測試.
使用 fakeredis 舉例:
import fakeredis
CACHES = {
"default": {
"OPTIONS": {
"REDIS_CLIENT_CLASS": "fakeredis.FakeStrictRedis",
}
}
}
若是在測試完畢後想清理全部數據, 在你的 TestCase 中加入以下代碼:
def tearDown(self):
from django_redis import get_redis_connection
get_redis_connection("default").flushall()
django-redis 使用 pickle 序列化幾乎全部數據.
默認使用最新的 pickle. 若是你想設置其餘版本, 使用 PICKLE_VERSION 參數:
CACHES = {
"default": {
# ...
"OPTIONS": {
"PICKLE_VERSION": -1 # Use the latest protocol version
}
}
}
套接字超時設置使用 SOCKET_TIMEOUT 和 SOCKET_CONNECT_TIMEOUT 參數:
CACHES = {
"default": {
# ...
"OPTIONS": {
"SOCKET_CONNECT_TIMEOUT": 5, # in seconds
"SOCKET_TIMEOUT": 5, # in seconds
}
}
}
SOCKET_CONNECT_TIMEOUT : socket 創建鏈接超時設置
SOCKET_TIMEOUT : 鏈接創建後的讀寫操做超時設置
django-redis 支持壓縮, 但默認是關閉的. 你能夠激活它:
CACHES = {
"default": {
# ...
"OPTIONS": {
"COMPRESSOR": "django_redis.compressors.zlib.ZlibCompressor",
}
}
}
使用 lzma 壓縮的例子:
import lzma
CACHES = {
"default": {
# ...
"OPTIONS": {
"COMPRESSOR": "django_redis.compressors.lzma.LzmaCompressor",
}
}
}
在某些狀況下, redis 只做爲緩存使用, 當它關閉時若是你不但願觸發異常. 這是 memcached backend 的默認行爲, 你可使用 django-redis 模擬這種狀況.
爲了設置這種相似memcached 的行爲 ( 忽略鏈接異常 ), 使用 IGNORE_EXCEPTIONS 參數:
CACHES = {
"default": {
# ...
"OPTIONS": {
"IGNORE_EXCEPTIONS": True,
}
}
}
Also, you can apply the same settings to all configured caches, you can set the global flag in your settings:
固然,你也能夠給全部緩存配置相同的忽略行爲:
DJANGO_REDIS_IGNORE_EXCEPTIONS = True
當使用 IGNORE_EXCEPTIONS 或者 DJANGO_REDIS_IGNORE_EXCEPTIONS 參數忽略異常時, 你也許會用到 DJANGO_REDIS_LOG_IGNORED_EXCEPTIONS 參數來配置日誌異常:
DJANGO_REDIS_LOG_IGNORED_EXCEPTIONS = True
若是你想設置指定的 logger 輸出異常, 只須要設置全局變量 DJANGO_REDIS_LOGGER 爲 logger 的名稱或其路徑便可. 若是沒有 logger 被設置而且 DJANGO_REDIS_LOG_IGNORED_EXCEPTIONS=True 時此參數將取 name :
DJANGO_REDIS_LOGGER = 'some.specified.logger'
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 指定的相同:
cache.set("key", "value", timeout=None)
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 的函數:
它返回:
以 keys 搜索過時:
>>> from django.core.cache import cache
>>> cache.set("foo", "value", timeout=25)
>>> cache.ttl("foo")
25
>>> cache.ttl("not-existent")
0
除了簡單的 ttl 查詢, 你可使用 persist 或者 expire 方法讓一個值永久存在或者指定一個新的過時時間:
使用 persist 的例子:
>>> cache.set("foo", "bar", timeout=22)
>>> cache.ttl("foo")
22
>>> cache.persist("foo")
>>> cache.ttl("foo")
None
使用 expire 的例子:
>>> cache.set("foo", "bar", timeout=22)
>>> cache.expire("foo", timeout=5)
>>> cache.ttl("foo")
5
django-redis 支持 redis 分佈式鎖. 鎖的線程接口是相同的, 所以你可使用它做爲替代.
使用 python 上下文管理器分配鎖的例子:
with cache.lock("somekey"):
do_some_thing()
django-redis 支持使用全局通配符的方式來檢索或者刪除鍵.
使用通配符搜索的例子
>>> from django.core.cache import cache
>>> cache.keys("foo_*")
["foo_1", "foo_2"]
這個簡單的寫法將返回全部匹配的值, 但在擁有很大數據量的數據庫中這樣作並不合適. 在 redis 的 server side cursors 2.8 版及以上, 你可使用 iter_keys
取代 keys
方法, iter_keys
將返回匹配值的迭代器, 你可使用迭代器高效的進行遍歷.
使用 server side cursors 搜索
>>> from django.core.cache import cache
>>> cache.iter_keys("foo_*")
<generator object algo at 0x7ffa9c2713a8>
>>> next(cache.iter_keys("foo_*"))
"foo_1"
若是要刪除鍵, 使用 delete_pattern
方法, 它和 keys
方法同樣也支持全局通配符, 此函數將會返回刪掉的鍵的數量
使用 delete_pattern 的例子
>>> from django.core.cache import cache
>>> cache.delete_pattern("foo_*")
django-redis 有限制的支持一些 Redis 原子操做, 例如 SETNX
和 INCR
命令.
你能夠在 set() 方法中加上 nx
參數使用來使用 SETNX
命令
例子:
>>> from django.core.cache import cache
>>> cache.set("key", "value1", nx=True)
True
>>> cache.set("key", "value2", nx=True)
False
>>> cache.get("key")
"value1"
當值 (value) 有合適的鍵 (key) 時, incr
和 decr
也可使用 Redis 原子操做
在某些狀況下你的應用須要進入原生 Redis 客戶端使用一些 django cache 接口沒有暴露出來的進階特性. 爲了不儲存新的原生鏈接所產生的另外一份設置, django-redis 提供了方法 get_redis_connection(alias)
使你得到可重用的鏈接字符串.
>>> from django_redis import get_redis_connection
>>> con = get_redis_connection("default")
>>> con
<redis.client.StrictRedis object at 0x2dc4510>
警告 不是全部的擴展客戶端都支持這個特性.
django-redis 使用 redis-py 的鏈接池接口, 並提供了簡單的配置方式. 除此以外, 你能夠爲 backend 定製化鏈接池的產生.
redis-py 默認不會關閉鏈接, 儘量重用鏈接
配置默認鏈接池很簡單, 你只須要在 CACHES
中使用 CONNECTION_POOL_KWARGS
設置鏈接池的最大鏈接數量便可:
CACHES = {
"default": {
"BACKEND": "django_redis.cache.RedisCache",
...
"OPTIONS": {
"CONNECTION_POOL_KWARGS": {"max_connections": 100}
}
}
}
你能夠得知鏈接池已經打開多少鏈接:
from django.core.cache import get_cache
from django_redis import get_redis_connection
r = get_redis_connection("default") # Use the name you have defined for Redis in settings.CACHES
connection_pool = r.connection_pool
print("Created connections so far: %d" % connection_pool._created_connections)
有時你想使用本身的鏈接池子類. django-redis 提供了 CONNECTION_POOL_CLASS
來配置鏈接池子類
myproj/mypool.py
from redis.connection import ConnectionPool
class MyOwnPool(ConnectionPool):
# Just doing nothing, only for example purpose
pass
setting.py
# Omitting all backend declaration boilerplate code.
"OPTIONS": {
"CONNECTION_POOL_CLASS": "myproj.mypool.MyOwnPool",
}
若是以前的方法都不合適, 你能夠定製 django-redis 的 connection factory 過程甚至徹底重寫.
django-redis 默認使用Django setting 中 DJANGO_REDIS_CONNECTION_FACTORY
參數指定的 django_redis.pool.ConnectionFactory
類產生鏈接.
ConnectionFactory 類的部分接口
# Note: Using Python 3 notation for code documentation ;)
class ConnectionFactory(object):
def get_connection_pool(self, params:dict):
# Given connection parameters in the `params` argument,
# return new connection pool.
# It should be overwritten if you want do something
# before/after creating the connection pool, or return your
# own connection pool.
pass
def get_connection(self, params:dict):
# Given connection parameters in the `params` argument,
# return a new connection.
# It should be overwritten if you want to do something
# before/after creating a new connection.
# The default implementation uses `get_connection_pool`
# to obtain a pool and create a new connection in the
# newly obtained pool.
pass
def get_or_create_connection_pool(self, params:dict):
# This is a high layer on top of `get_connection_pool` for
# implementing a cache of created connection pools.
# It should be overwritten if you want change the default
# behavior.
pass
def make_connection_params(self, url:str) -> dict:
# The responsibility of this method is to convert basic connection
# parameters and other settings to fully connection pool ready
# connection parameters.
pass
def connect(self, url:str):
# This is really a public API and entry point for this
# factory class. This encapsulates the main logic of creating
# the previously mentioned `params` using `make_connection_params`
# and creating a new connection using the `get_connection` method.
pass
redis-py (django-redis 使用的 Redis 客戶端) 支持的純淨 Python Redis 解析器能夠知足大部分普通任務, 但若是你想要性能更好, 可使用 hiredis
hiredis 是一個用 C 寫的 Redis 客戶端, 而且他的解析器能夠用在 django-redis 中:
"OPTIONS": {
"PARSER_CLASS": "redis.connection.HiredisParser",
}
django_redis 設計的很是靈活和可配置。它提供了可擴展的後端,擁有易擴展的特性.
咱們已經說明了默認客戶端幾乎全部的特色, 但有一個例外: 默認客戶端支持主從配置.
若是須要主從設置, 你須要更改 LOCATION
參數:
"LOCATION": [
"redis://127.0.0.1:6379/1",
"redis://127.0.0.1:6378/1",
]
第一個字段表明 master 服務器, 第二個字段表明 slave 服務器.
警告 主從設置沒有在生產環境中通過大量測試
此可擴展客戶端實現了客戶端分片, 它幾乎繼承了默認客戶端的所有功能. 若是須要使用, 請將配置改爲這樣:
CACHES = {
"default": {
"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": [
"redis://127.0.0.1:6379/1",
"redis://127.0.0.1:6379/2",
],
"OPTIONS": {
"CLIENT_CLASS": "django_redis.client.ShardClient",
}
}
}
警告 分片客戶端仍處於試驗階段, 請在生產環境中謹慎使用
咱們同時也在嘗試解決驚羣問題, 更多信息請閱讀Wikipedia
和上文講的同樣, 客戶端基本繼承了默認客戶端全部功能, 增長額外的方法以獲取/設置鍵 (keys)
設置舉例
CACHES = {
"default": {
"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": "redis://127.0.0.1:6379/1",
"OPTIONS": {
"CLIENT_CLASS": "django_redis.client.HerdClient",
}
}
}
一些其餘的設置:
客戶端在將數據發給服務器以前先會序列化數據. django-redis 默認使用 Python pickle 序列化數據.
若是須要使用 json 序列化數據, 使用 JSONSerializer
設置舉例
CACHES = {
"default": {
"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": "redis://127.0.0.1:6379/1",
"OPTIONS": {
"CLIENT_CLASS": "django_redis.client.DefaultClient",
"SERIALIZER": "django_redis.serializers.json.JSONSerializer",
}
}
}
使用 MsgPack http://msgpack.org/ 進行序列化 (須要 msgpack-python 庫支持)
設置舉例
CACHES = {
"default": {
"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": "redis://127.0.0.1:6379/1",
"OPTIONS": {
"CLIENT_CLASS": "django_redis.client.DefaultClient",
"SERIALIZER": "django_redis.serializers.msgpack.MSGPackSerializer",
}
}
}
django-redis 默認使用 redis.client.StrictClient
做爲 Redis 客戶端, 你可使用其餘客戶端替代, 好比以前在講測試時咱們用 fakeredis 代替真實客戶端.
使用 REDIS_CLIENT_CLASS in the CACHES
來配置你的客戶端, 使用 REDIS_CLIENT_KWARGS
提供配置客戶端的參數 (可選).
設置舉例
CACHES = {
"default": {
"OPTIONS": {
"REDIS_CLIENT_CLASS": "my.module.ClientClass",
"REDIS_CLIENT_KWARGS": {"some_setting": True},
}
}
}