Python redis-py3.5教程

本人長期招收 Python 一對一學員,歡迎聯繫微信:Jiabcdefhhtml

redis-py

你好,我是悅創。很早以前 ,寫了一篇 Python redis 的教程:還在手動插入 redis 數據?Python 帶你解決!,備用連接:https://blog.csdn.net/qq_33254766/article/details/117221658python

如今準備寫個大規模的異步新聞爬蟲實戰項目,須要控制 url 因此,就順便把看最新版的英文稍微整理出來。因爲本人英文有限,若是有翻譯問題,歡迎指教和評論。linux

The Python interface to the Redis key-value store.git

Redis 鍵值存儲的 Python 接口。github

Python 2 Compatibility Note「Python 2 兼容性說明」

redis-py 3.5.x will be the last version of redis-py that supports Python 2. The 3.5.x line will continue to get bug fixes and security patches that support Python 2 until August 1, 2020. redis-py 4.0 will be the next major version and will require Python 3.5+.redis

redis-py 3.5.x 將是支持 Python 2 的最後一個 redis-py 版本。3.5.x 將繼續得到支持 Python 2 的 bug 修復和安全補丁,直到 2020 年 8月1日。redis-py 4.0 將是下一個主要版本,須要 Python 3.5+。安全

Installation「安裝」

redis-py requires a running Redis server. See Redis’s quickstart for installation instructions.服務器

Redis -py 須要運行 Redis 服務器。參見 Redis 的快速入門安裝說明。:https://redis.io/topics/quickstart微信

redis-py can be installed using pip similar to other Python packages. Do not use sudo with pip. It is usually good to work in a virtualenv or venv to avoid conflicts with other package managers and Python projects. For a quick introduction see Python Virtual Environments in Five Minutes.markdown

redi-py 可使用 pip 安裝,相似於其餘 Python 包。不要使用 sudo 與 pip 。在 virtualenvvenv 中工做一般很好,以免與其餘包管理器和 Python 項目的衝突。有關快速介紹,請參見 Python 虛擬環境五分鐘

要安裝 redis-py,只需:

$ pip install redis

或從源代碼:

$ python setup.py install

Contributing「貢獻」

Want to contribute a feature, bug report, or report an issue? Check out our guide to contributing.

是否要提供功能,錯誤報告或報告問題?查看咱們的貢獻指南

Getting Started「開始」

在開始以前,你要在命令行啓動 redis,命令:

➜  Django_Leraning git:(main) ✗ redis-server
14540:C 24 May 2021 16:09:21.363 # oO0OoO0OoO0Oo Redis is starting oO0OoO0OoO0Oo
14540:C 24 May 2021 16:09:21.363 # Redis version=6.0.7, bits=64, commit=00000000, modified=0, pid=14540, just started
14540:C 24 May 2021 16:09:21.363 # Warning: no config file specified, using the default config. In order to specify a config file use redis-server /path/to/redis.conf
14540:M 24 May 2021 16:09:21.364 * Increased maximum number of open files to 10032 (it was originally set to 256).
                _._
           _.-``__ ''-._
      _.-``    `.  `_.  ''-._           Redis 6.0.7 (00000000/0) 64 bit
  .-`` .-```.  ```\/    _.,_ ''-._
 (    '      ,       .-`  | `,    )     Running in standalone mode
 |`-._`-...-` __...-.``-._|'` _.-'|     Port: 6379
 |    `-._   `._    /     _.-'    |     PID: 14540
  `-._    `-._  `-./  _.-'    _.-'
 |`-._`-._    `-.__.-'    _.-'_.-'|
 |    `-._`-._        _.-'_.-'    |           http://redis.io
  `-._    `-._`-.__.-'_.-'    _.-'
 |`-._`-._    `-.__.-'    _.-'_.-'|
 |    `-._`-._        _.-'_.-'    |
  `-._    `-._`-.__.-'_.-'    _.-'
      `-._    `-.__.-'    _.-'
          `-._        _.-'
              `-.__.-'

14540:M 24 May 2021 16:09:21.365 # Server initialized
14540:M 24 May 2021 16:09:21.365 * Loading RDB produced by version 6.0.7
14540:M 24 May 2021 16:09:21.365 * RDB age 2 seconds
14540:M 24 May 2021 16:09:21.365 * RDB memory usage when created 1.06 Mb
14540:M 24 May 2021 16:09:21.365 * DB loaded from disk: 0.000 seconds
14540:M 24 May 2021 16:09:21.365 * Ready to accept connections
>>> import redis
>>> r = redis.Redis(host='localhost', port=6379, db=0)
>>> r.set('foo', 'bar')
True
>>> r.get('foo')
b'bar'

By default, all responses are returned as bytes in Python 3 and str in Python 2. The user is responsible for decoding to Python 3 strings or Python 2 unicode objects.

默認狀況下,全部響應在 Python 3 中以 字節 形式返回,在 Python 2 中以 str 形式返回。用戶負責解碼到 Python 3 字符串或 Python 2 unicode 對象。

If all string responses from a client should be decoded, the user can specify decode_responses=True to Redis.init. In this case, any Redis command that returns a string type will be decoded with the encoding specified.

若是來自客戶端的全部字符串響應都應該被解碼,用戶能夠指定 decode_responses=True 爲 Redis.__init__。在這種狀況下,任何返回字符串類型的 Redis 命令都將使用指定的編碼進行解碼。

>>> import redis
>>> r = redis.Redis(host='localhost', port=6379, db=0, decode_responses="True")
>>> r.set('foo', 'bar')
True
>>> r.get('foo')
b'bar'

The default encoding is 「utf-8」, but this can be customized with the encoding argument to the redis.Redis class. The encoding will be used to automatically encode any strings passed to commands, such as key names and values. When decode_responses=True, string data returned from commands will be decoded with the same encoding.

默認的編碼是 「utf-8」,可是能夠經過 redis 的 encoding 參數進行自定義。複述, Redis 類。該編碼將用於自動編碼傳遞給命令的任何字符串,好比鍵名和值。當 decode_responses=True 時,命令返回的字符串數據將使用相同的編碼進行解碼。

Redis:

def __init__(self, host='localhost', port=6379,
                 db=0, password=None, socket_timeout=None,
                 socket_connect_timeout=None,
                 socket_keepalive=None, socket_keepalive_options=None,
                 connection_pool=None, unix_socket_path=None,
                 encoding='utf-8', encoding_errors='strict',
                 charset=None, errors=None,
                 decode_responses=False, retry_on_timeout=False,
                 ssl=False, ssl_keyfile=None, ssl_certfile=None,
                 ssl_cert_reqs='required', ssl_ca_certs=None,
                 ssl_check_hostname=False,
                 max_connections=None, single_connection_client=False,
                 health_check_interval=0, client_name=None, username=None):

Upgrading from redis-py 2.X to 3.0「edis-py 從 2.x 升級到 3.0」

redis-py 3.0 introduces many new features but required a number of backwards incompatible changes to be made in the process. This section attempts to provide an upgrade path for users migrating from 2.X to 3.0.

Redis-py 3.0 引入了許多新特性,但在此過程當中須要進行一些向後不兼容的更改。本節試圖爲從 2.X 遷移的用戶提供一個升級路徑 3.0 。

Python Version Support「Python版本支持」

redis-py supports Python 3.5+.

redis-py 支持 Python 3.5+。

Client Classes: Redis and StrictRedis「客戶端類: Redis 和 StrictRedis」

redis-py 3.0 drops support for the legacy 「Redis」 client class. 「StrictRedis」 has been renamed to 「Redis」 and an alias named 「StrictRedis」 is provided so that users previously using 「StrictRedis」 can continue to run unchanged.

Redis-py 3.0 支持傳統的 「Redis」 客戶端類。「StrictRedis」 已改名爲「Redis」,並提供了一個別名 「StrictRedis」 ,以便之前使用 「StrictRedis」 的用戶能夠繼續運行不變。

在這裏插入圖片描述

The 2.X 「Redis」 class provided alternative implementations of a few commands. This confused users (rightfully so) and caused a number of support issues. To make things easier going forward, it was decided to drop support for these alternate implementations and instead focus on a single client class.

2.X「 Redis」類提供了一些命令的替代實現。這使用戶感到困惑(理應如此),並致使了許​​多支持問題。爲了使事情變得更容易,咱們決定放棄對這些替代實現的支持,而將精力集中在單個客戶端類上。

2.X users that are already using StrictRedis don’t have to change the class name. StrictRedis will continue to work for the foreseeable future.

已經使用 StrictRedis的2.X 用戶沒必要更改類名。StrictRedis 將在可預見的將來繼續努力。

2.X users that are using the Redis class will have to make changes if they use any of the following commands:

若是使用 Redis 類的 2.X 用戶必須使用如下任何命令,則必須進行更改:

  • SETEX: The argument order has changed. The new order is (name, time, value). 參數順序已更改。新訂單爲(名稱,時間,值)。
  • LREM: The argument order has changed. The new order is (name, num, value). 參數順序已更改。新的順序是(名稱,數字,值)。
  • TTL and PTTL: The return value is now always an int and matches the official Redis command (>0 indicates the timeout, -1 indicates that the key exists but that it has no expire time set, -2 indicates that the key does not exist) 如今的返回值始終是一個 int,而且與正式的 Redis 命令匹配(> 0 表示超時,-1 表示密鑰存在但未設置過時時間,-2 表示密鑰不存在)

上面一直把原文保留下來,有點小費勁,接下來我就不保留原文了,有興趣的能夠直接去 GitHub 上閱讀。:https://github.com/andymccurdy/redis-py

SSL Connections「SSL 鏈接」

redis-py 3.0 changes the default value of the ssl_cert_reqs option from
None to 'required'. See
Issue 1016 <https://github.com/andymccurdy/redis-py/issues/1016>_. This
change enforces hostname validation when accepting a cert from a remote SSL
terminator. If the terminator doesn’t properly set the hostname on the cert
this will cause redis-py 3.0 to raise a ConnectionError.

redis-py 3.0 將 ssl_cert_reqs 選項的默認值從「無」更改成「必需」。參見 問題1016 。從遠程 SSL 終結器接受證書時,此更改將強制執行主機名驗證。若是終止符未在證書上正確設置主機名,這將致使 redis-py 3.0 引起 ConnectionError。

This check can be disabled by setting ssl_cert_reqs to None. Note that
doing so removes the security check. Do so at your own risk.

能夠經過將 ssl_cert_reqs 設置爲 None 來禁用此檢查。請注意,這樣作會刪除安全檢查。這樣作自擔風險。

Example with hostname verification using a local certificate bundle (linux):

使用本地證書捆綁包(linux)進行主機名驗證的示例:

>>> import redis
>>> r = redis.Redis(host='xxxxxx.cache.amazonaws.com', port=6379, db=0,
                    ssl=True,
                    ssl_ca_certs='/etc/ssl/certs/ca-certificates.crt')
>>> r.set('foo', 'bar')
True
>>> r.get('foo')
b'bar'

Example with hostname verification using certifi:

剩下的有時間就來更新!

相關文章
相關標籤/搜索