Python 操作 Redis 的客戶端庫 redis-py

Python 操作 Redis 的客戶端庫 redis-py

  • 1. Installation
  • 2. Connect and test
  • 3. Connection Pools
  • 4. Redis Commands
    • 4.1. `set(name, value, ex=None, px=None, nx=False, xx=False, keepttl=False, get=False, exat=None, pxat=None)`
      • 4.1.1. `setnx(name, value)`
      • 4.1.2. `setex(name, time, value)`
      • 4.1.3. `psetex(name, time_ms, value)`
    • 4.2. `flushdb(asynchronous=False, **kwargs)`
    • 4.3. `mset(mapping)`
    • 4.4. `mget(keys, *args)`
  • References

Connect your Python application to a Redis database

redis-py guide (Python)
https://redis.io/docs/latest/develop/clients/redis-py/

redis-py (Redis Python client)
https://github.com/redis/redis-py

The Python interface to the Redis key-value store.

redis-py is the Python client for Redis. redis-py requires a running Redis server.

The sections below explain how to install redis-py and connect your Python application to a Redis database.

1. Installation

To install redis-py, enter:

pip install redis
(base) yongqiang@yongqiang:~$ pip install redis
Collecting redisDownloading redis-6.4.0-py3-none-any.whl (279 kB)━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 279.8/279.8 kB 316.2 kB/s eta 0:00:00
Installing collected packages: redis
Successfully installed redis-6.4.0
(base) yongqiang@yongqiang:~$

For faster performance, install Redis with hiredis support. This provides a compiled response parser, and for most cases requires zero code changes. By default, if hiredis >= 1.0 is available, redis-py attempts to use it for response parsing.

The Python distutils packaging scheme is no longer part of Python 3.12 and greater. If you’re having difficulties getting redis-py installed in a Python 3.12 environment, consider updating to a recent release of redis-py.

pip install redis[hiredis]

2. Connect and test

Connect to localhost on port 6379, set a value in Redis, and retrieve it.

All responses are returned as bytes in Python. To receive decoded strings, set decode_responses=True.
redis 取出的結果默認是字節,可以設定 decode_responses=True 改成字符串。

#!/usr/bin/env python
# coding=utf-8import redisr = redis.Redis(host='localhost', port=6379, decode_responses=True)
r.set('name', 'yongqiang')print(f"name: {r['name']}")print(f"type: {type(r.get('name'))}")
print(f"name: {r.get('name')}")

redis 提供兩個類 Redis 和 StrictRedis, StrictRedis 用于實現大部分官方的命令,Redis 是 StrictRedis 的子類,用于向后兼用舊版本。

#!/usr/bin/env python
# coding=utf-8import redisr = redis.StrictRedis(host='localhost', port=6379, decode_responses=True)
r.set('name', 'yongqiang')print(f"name: {r['name']}")print(f"type: {type(r.get('name'))}")
print(f"name: {r.get('name')}")
/home/yongqiang/miniconda3/bin/python /home/yongqiang/stable_diffusion_work/stable_diffusion_diffusers/forever.py 
name: yongqiang
type: <class 'str'>
name: yongqiangProcess finished with exit code 0

3. Connection Pools

By default, redis-py uses a connection pool to manage connections. Each instance of a Redis class receives its own connection pool.

redis-py 使用 connection pool 來管理對一個 redis-server 的所有連接,避免每次建立、釋放連接的開銷。默認情況下,每個 Redis 實例都會維護一個自己的連接池。可以直接建立一個連接池,然后作為 Redis 參數,這樣就可以實現多個 Redis 實例共享一個連接池。

#!/usr/bin/env python
# coding=utf-8import redispool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)
r = redis.Redis(connection_pool=pool)r.set('name', 'yongqiang')print(f"name: {r['name']}")print(f"type: {type(r.get('name'))}")
print(f"name: {r.get('name')}")
/home/yongqiang/miniconda3/bin/python /home/yongqiang/stable_diffusion_work/stable_diffusion_diffusers/forever.py 
name: yongqiang
type: <class 'str'>
name: yongqiangProcess finished with exit code 0

4. Redis Commands

https://redis.readthedocs.io/en/stable/commands.html

4.1. set(name, value, ex=None, px=None, nx=False, xx=False, keepttl=False, get=False, exat=None, pxat=None)

Set the value at key name to value.
在 Redis 中設置值,默認:不存在則創建,存在則修改。

https://redis.io/docs/latest/commands/set/

Parameters
name (Union[bytes, str, memoryview])
value (Union[bytes, bytearray, memoryview, str, int, float])
ex (Optional[Union[int, timedelta]]) - sets an expire flag on key name for ex seconds.
px (Optional[Union[int, timedelta]]) - sets an expire flag on key name for px milliseconds.
nx (bool) - if set to True, set the value at key name to value only if it does not exist. 如果設置為 True,則只有 name 不存在時,當前 set 操作才執行 (新建 / 添加)。
xx (bool) - if set to True, set the value at key name to value only if it already exists. 如果設置為 True,則只有 name 存在時,當前 set 操作才執行 (修改)。
keepttl (bool) - if True, retain the time to live associated with the key. (Available since Redis 6.0)
get (bool) - if True, set the value at key name to value and return the old value stored at key, or None if the key did not exist. (Available since Redis 6.2)
exat (Optional[Union[int, datetime]]) - sets an expire flag on key name for ex seconds, specified in unix time.
pxat (Optional[Union[int, datetime]]) - sets an expire flag on key name for ex milliseconds, specified in unix time.

Return type
Union[Awaitable[Any], Any]

  • ex (Optional[Union[int, timedelta]]) - sets an expire flag on key name for ex seconds.

設置過期時間是 2 秒。2 秒后,鍵 name 的值就變成 None

#!/usr/bin/env python
# coding=utf-8import redis
import timepool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)
r = redis.Redis(connection_pool=pool)r.set('name', 'yongqiang', ex=2)print(f"type: {type(r.get('name'))}")
print(f"name: {r.get('name')}")print("Start: %s" % time.ctime())
time.sleep(5)  # secs
print("End: %s" % time.ctime())print(f"name: {r.get('name')}")
/home/yongqiang/miniconda3/bin/python /home/yongqiang/stable_diffusion_work/stable_diffusion_diffusers/forever.py 
type: <class 'str'>
name: yongqiang
Start: Fri Aug 15 00:20:10 2025
End: Fri Aug 15 00:20:15 2025
name: NoneProcess finished with exit code 0
  • px (Optional[Union[int, timedelta]]) - sets an expire flag on key name for px milliseconds.

設置過期時間是 200 milliseconds。200 milliseconds 后,鍵 name 的值就變成 None

#!/usr/bin/env python
# coding=utf-8import redis
import timepool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)
r = redis.Redis(connection_pool=pool)r.set('name', 'yongqiang', px=200)print(f"type: {type(r.get('name'))}")
print(f"name: {r.get('name')}")print("Start: %s" % time.ctime())
time.sleep(2)  # secs
print("End: %s" % time.ctime())print(f"name: {r.get('name')}")
/home/yongqiang/miniconda3/bin/python /home/yongqiang/stable_diffusion_work/stable_diffusion_diffusers/forever.py 
type: <class 'str'>
name: yongqiang
Start: Fri Aug 15 00:24:02 2025
End: Fri Aug 15 00:24:04 2025
name: NoneProcess finished with exit code 0
  • nx (bool) - if set to True, set the value at key name to value only if it does not exist.

如果設置為 True,則只有 name 不存在時,當前 set 操作才執行 (新建 / 添加)。

#!/usr/bin/env python
# coding=utf-8import redis
import timepool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)
r = redis.Redis(connection_pool=pool)
r.flushdb(asynchronous=False)ret1 = r.set('name', 'yongqiang', nx=True)
print(f"ret1: {ret1}")ret2 = r.set('name', 'cheng', nx=True)
print(f"ret2: {ret2}")time.sleep(2)  # secs
/home/yongqiang/miniconda3/bin/python /home/yongqiang/stable_diffusion_work/stable_diffusion_diffusers/forever.py 
ret1: True
ret2: NoneProcess finished with exit code 0
  • xx (bool) - if set to True, set the value at key name to value only if it already exists.

如果設置為 True,則只有 name 存在時,當前 set 操作才執行 (修改)。

#!/usr/bin/env python
# coding=utf-8import redis
import timepool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)
r = redis.Redis(connection_pool=pool)
r.flushdb(asynchronous=False)ret1 = r.set('name', 'yongqiang', xx=True)
print(f"ret1: {ret1}")ret2 = r.set('name', 'yongqiang')
print(f"ret2: {ret2}")ret3 = r.set('name', 'cheng', xx=True)
print(f"ret3: {ret3}")time.sleep(2)  # secs
/home/yongqiang/miniconda3/bin/python /home/yongqiang/stable_diffusion_work/stable_diffusion_diffusers/forever.py 
ret1: None
ret2: True
ret3: TrueProcess finished with exit code 0

4.1.1. setnx(name, value)

Set the value of key name to value if key doesn’t exist.

https://redis.io/docs/latest/commands/setnx/

Parameters
name (Union[bytes, str, memoryview])
value (Union[bytes, bytearray, memoryview, str, int, float])

Return type
Union[Awaitable[Any], Any]

#!/usr/bin/env python
# coding=utf-8import redis
import timepool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)
r = redis.Redis(connection_pool=pool)
r.flushdb(asynchronous=False)ret1 = r.setnx('name', 'yongqiang')
print(f"ret1: {ret1}")ret2 = r.setnx('name', 'cheng')
print(f"ret2: {ret2}")time.sleep(2)  # secs
/home/yongqiang/miniconda3/bin/python /home/yongqiang/stable_diffusion_work/stable_diffusion_diffusers/forever.py 
ret1: True
ret2: FalseProcess finished with exit code 0

4.1.2. setex(name, time, value)

Set the value of key name to value that expires in time seconds. time can be represented by an integer or a Python timedelta object.

https://redis.io/docs/latest/commands/setex/

Parameters
name (Union[bytes, str, memoryview])
time (Union[int, timedelta])
value (Union[bytes, bytearray, memoryview, str, int, float])

Return type
Union[Awaitable[Any], Any]

#!/usr/bin/env python
# coding=utf-8import redis
import timepool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)
r = redis.Redis(connection_pool=pool)
r.flushdb(asynchronous=False)r.setex('name', 2, 'yongqiang')print(f"type: {type(r.get('name'))}")
print(f"name: {r.get('name')}")print("Start: %s" % time.ctime())
time.sleep(5)  # secs
print("End: %s" % time.ctime())print(f"name: {r.get('name')}")
/home/yongqiang/miniconda3/bin/python /home/yongqiang/stable_diffusion_work/stable_diffusion_diffusers/forever.py 
type: <class 'str'>
name: yongqiang
Start: Fri Aug 15 20:27:53 2025
End: Fri Aug 15 20:27:58 2025
name: NoneProcess finished with exit code 0

4.1.3. psetex(name, time_ms, value)

Set the value of key name to value that expires in time_ms milliseconds. time_ms can be represented by an integer or a Python timedelta object.

https://redis.io/commands/psetex

Parameters
name (Union[bytes, str, memoryview])
time_ms (Union[int, timedelta])
value (Union[bytes, bytearray, memoryview, str, int, float])

#!/usr/bin/env python
# coding=utf-8import redis
import timepool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)
r = redis.Redis(connection_pool=pool)
r.flushdb(asynchronous=False)r.psetex('name', 2000, 'yongqiang')print(f"type: {type(r.get('name'))}")
print(f"name: {r.get('name')}")print("Start: %s" % time.ctime())
time.sleep(5)  # secs
print("End: %s" % time.ctime())print(f"name: {r.get('name')}")
/home/yongqiang/miniconda3/bin/python /home/yongqiang/stable_diffusion_work/stable_diffusion_diffusers/forever.py 
type: <class 'str'>
name: yongqiang
Start: Fri Aug 15 20:32:44 2025
End: Fri Aug 15 20:32:49 2025
name: NoneProcess finished with exit code 0

4.2. flushdb(asynchronous=False, **kwargs)

Delete all keys in the current database.

https://redis.io/docs/latest/commands/flushdb/

asynchronous indicates whether the operation is executed asynchronously by the server.
清空當前 db 中的數據,默認是同步,異步 asynchronous=True,會新起一個線程進行清空操作,不阻塞主線程。

Parameters
asynchronous (bool)

Return type
Union[Awaitable[Any], Any]

#!/usr/bin/env python
# coding=utf-8import redis
import timepool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)
r = redis.Redis(connection_pool=pool)
r.flushdb(asynchronous=False)

4.3. mset(mapping)

Sets key/values based on a mapping. Mapping is a dictionary of key/value pairs. Both keys and values should be strings or types that can be cast to a string via str().

https://redis.io/commands/mset

Parameters
mapping (Mapping[AnyKeyT, Union[bytes, bytearray, memoryview, str, int, float]])

Return type
Union[Awaitable[Any], Any]

4.4. mget(keys, *args)

Returns a list of values ordered identically to keys.

https://redis.io/commands/mget

Parameters
keys (Union[bytes, str, memoryview, Iterable[Union[bytes, str, memoryview]]])
args (Union[bytes, bytearray, memoryview, str, int, float])

Return type
Union[Awaitable[Any], Any]

#!/usr/bin/env python
# coding=utf-8import redis
import timepool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)
r = redis.Redis(connection_pool=pool)
r.flushdb(asynchronous=False)r.mset({'k1': 'value1', 'k2': 'value2', 'k3': 'value3'})
print(r.mget("k1"))
print(r.mget("k1", "k2"))
print(r.mget("k1", "k2", "k3"))print(f"\nname: {r.get('name')}")
/home/yongqiang/miniconda3/bin/python /home/yongqiang/stable_diffusion_work/stable_diffusion_diffusers/forever.py 
['value1']
['value1', 'value2']
['value1', 'value2', 'value3']name: NoneProcess finished with exit code 0

References

[1] Yongqiang Cheng, https://yongqiang.blog.csdn.net/
[2] What is Redis? https://www.ibm.com/think/topics/redis

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/web/93219.shtml
繁體地址,請注明出處:http://hk.pswp.cn/web/93219.shtml
英文地址,請注明出處:http://en.pswp.cn/web/93219.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

社區物業HCommunity本地部署手冊

HC小區管理系統安裝手動版 更多文章參考&#xff1a; http://www.homecommunity.cn/pages/hc/hcH5_cn.html 1.0 說明 很多開發不太喜歡用梓豪安裝&#xff0c;希望通過手工自己安裝&#xff0c;這個就需要開發人員 有一定的安裝軟件能力&#xff0c;比如能夠自行安裝mysql能…

單例模式-使用局部變量懶漢不用加鎖

在 C11 及之后&#xff0c;“局部靜態變量懶漢”&#xff08;Meyers’ Singleton&#xff09;不需要自己加鎖&#xff0c;標準已經幫你做好了線程安全。 Singleton& getInstance() {static Singleton inst; // ← 這一句并發時只會初始化一次return inst; }首次調用時&am…

51單片機-GPIO介紹

本章概述思維導圖&#xff1a;51單片機引腳介紹STC89系列51單片機引腳介紹STC89系列51單片機的引腳是單片機與外部電路連接的接口&#xff0c;用于實現電源供電、時鐘信號輸入、控制信號輸出以及數據輸入輸出等功能。PDIP封裝引腳圖&#xff1a;1. 電源引腳&#xff1a;VCC&…

CERT/CC警告:新型HTTP/2漏洞“MadeYouReset“恐致全球服務器遭DDoS攻擊癱瘓

2025年8月15日CERT/CC&#xff08;計算機應急響應協調中心&#xff09;近日發布漏洞公告&#xff0c;警告多個HTTP/2實現中新發現的缺陷可能被威脅行為者用于發起高效拒絕服務&#xff08;DoS&#xff09;或分布式拒絕服務&#xff08;DDoS&#xff09;攻擊。該漏洞被非正式命名…

[Chat-LangChain] 會話圖(LangGraph) | 大語言模型(LLM)

第二章&#xff1a;會話圖&#xff08;LangGraph&#xff09; 在第一章中&#xff0c;我們學習了前端用戶界面——這是聊天機器人的"面孔"&#xff0c;我們在這里輸入問題并查看答案。 我們看到了消息如何從聊天窗口傳遞到聊天機器人的"大腦"。現在&…

Flask錯誤處理與會話技術詳解

flask入門day03 錯誤處理 1.abort函數&#xff1a;放棄請求并返回錯誤代碼 詳細狀態碼 from flask import Flask,abort,render_template ? app Flask(__name__) ? app.route(/) def index():return 我是首頁 ? app.route(/error) def error():abort(404)return 沒有找到…

java程序打包成exe,再打成安裝包,沒有jdk環境下可運行

一、前提條件準備&#xff1a;1、要被打包的程序文件&#xff1a;rest_assistant-1.0-SNAPSHOT.jarapplication.yml2、圖標文件tubiao123.ico3、jre4、打包成exe的軟件 config.exe4j5、打成安裝包的軟件 Inno Setup Compiler二、config.exe4j 的 exe打包配置步驟 按照以下圖進行…

區塊鏈技術原理(11)-以太坊交易

文章目錄什么是交易&#xff1f;交易類型交易生命周期關鍵概念&#xff1a;Gas 與交易費用交易狀態與失敗原因總結什么是交易&#xff1f; “交易&#xff08;Transaction&#xff09;” 是從一個賬戶向另一個賬戶發送的經過數字簽名的指令 。例如&#xff0c;如果 Bob 發送 A…

小兔鮮兒-小程序uni-app(二)

小兔鮮兒-小程序uni-app7.小兔鮮兒 - 用戶模塊會員中心頁(我的)靜態結構參考代碼會員設置頁分包預下載靜態結構退出登錄會員信息頁靜態結構獲取會員信息渲染會員信息更新會員頭像更新表單信息8.小兔鮮兒 - 地址模塊準備工作靜態結構地址管理頁地址表單頁動態設置標題新建地址頁…

BLE 廣播信道與數據信道:沖突避免、信道映射與自適應跳頻實現

低功耗藍牙(BLE)技術憑借低功耗、短距離、低成本的特性,已廣泛應用于智能家居、可穿戴設備、工業物聯網等領域。在 BLE 協議中,信道管理是保障通信可靠性的核心機制,其中廣播信道與數據信道的設計、沖突避免策略、跳頻技術更是面試中的高頻考點。本文將從基礎原理到實戰真…

nodejs03-常用模塊

nodejs 常用的核心模塊 Node.js 是一個基于 Chrome V8 引擎的 JavaScript 運行環境&#xff0c; 它允許 JavaScript 運行在服務器端。Node.js 擁有豐富的標準庫&#xff0c;也就是核心模塊&#xff0c; 這些模塊提供了各種功能&#xff0c; 使得開發服務器端應用程序變得簡單高…

多路混音聲音播放芯片型號推薦

以下是唯創知音旗下主流的多路聲音播放芯片深度解析&#xff0c;結合精準參數、豐富場景及技術特性&#xff0c;滿足智能設備多樣化音頻需求&#xff1a;一、WTV380/890 系列&#xff1a;高集成多模態交互芯片核心參數通道能力&#xff1a;支持8 路獨立語音輸出&#xff0c;可同…

【C++】自研基 2 Cooley–Tukey

“自研基 2 Cooley–Tukey&#xff1a;倒位序 逐級蝶形&#xff0c;入口 fft(int N, complex f[])”拆成三件事它在講什么 “基 2 Cooley–Tukey” 指的是最常見的 FFT 算法&#xff1a;長度 N 必須是 2 的整數次冪&#xff0c;把離散傅里葉變換分解成一層一層的“2 點蝶形”運…

小白挑戰一周上架元服務——ArkUI04

文章目錄前言一、ArkUI是何方神圣&#xff1f;二、聲明式UI三、組件1.基礎組件2.布局容器組件3.導航組件4.自定義組件5.組件生命周期四、狀態管理1.State裝飾器: 狀態變量2.Prop裝飾器&#xff1a;父子單向同步3.Link裝飾器&#xff1a;父子雙向同步4.Provide/Consume裝飾器&am…

劇本殺小程序系統開發:構建劇本殺社交新生態

在社交需求日益多樣化的今天&#xff0c;劇本殺憑借其獨特的社交屬性&#xff0c;成為了人們熱衷的社交娛樂方式之一。而劇本殺小程序系統開發&#xff0c;則進一步拓展了劇本殺的社交邊界&#xff0c;構建起一個全新的劇本殺社交新生態&#xff0c;讓玩家在推理與角色扮演中&a…

AI提高投放效率的核心策略

內容概要人工智能技術正深刻改變著廣告投放領域&#xff0c;其核心價值在于顯著提升投放效率。通過融合智能算法優化、實時數據分析與自動化投放流程&#xff0c;AI系統能夠以前所未有的速度和精度處理海量信息&#xff0c;驅動更精準的營銷決策。這不僅大幅縮短了傳統人工操作…

OpenBMC 中命令模式的深度解析:從原理到實現

引言 在 OpenBMC 的設計中&#xff0c;命令模式&#xff08;Command Pattern&#xff09;被廣泛應用于各種場景&#xff0c;特別是 IPMI 命令處理、異步操作封裝和用戶請求管理等。本文將深入分析 OpenBMC 中命令模式的實現原理、架構設計以及完整的執行流程&#xff0c;并通過…

從0開始跟小甲魚C語言視頻使用linux一步步學習C語言(持續更新)8.15

第十七天 第五十七&#xff0c;五十八&#xff0c;五十九和六十集 第五十六集 刪除鏈表結點 沒什么好說的關鍵部分代碼如圖 鏈表的插入操作 依舊沒有啥可以說的代碼部分大家看視頻就能看懂&#xff0c;大家應該是沒有什么問題的吧&#xff1f; 第五十七集 共用體形式結構與結構…

云服務器網站無法訪問的系統化故障排查指南及多維度解決方案

當云服務器上的網站突然無法訪問時&#xff0c;這種突發狀況往往讓人措手不及。別擔心&#xff0c;我們可以通過系統化的排查流程快速定位問題根源。以下是經過實戰驗證的故障排除指南&#xff0c;幫您分步解決網站訪問異常問題。一、基礎狀態確認 服務器的生命體征就像人體的脈…

strings命令和findstr命令驗證iso文件中ntkrnlmp.exe系統版本

strings命令和findstr命令驗證iso文件中ntkrnlmp.exe系統版本D:\chsads3647\i386>expand.exe Microsoft (R) File Expansion Utility Version 5.2.3647.0 版本所有 (c) Microsoft Corporation. 保留所有權利。未指定文件。D:\chsads3647\i386>strings.exe ntkrnlmp.exe …