Home Database Redis What are the methods for operating redis in python?

What are the methods for operating redis in python?

Jun 03, 2023 pm 01:45 PM
python redis

Python operates redis and uses connection pool:

redis-py uses connection pool to manage all connections to a redis server to avoid the overhead of establishing and releasing connections each time. By default, each Redis instance maintains its own connection pool. You can directly establish a connection pool and then use it as parameter Redis, so that multiple Redis instances can share a connection pool.

def getcoon():
      pool = redis.ConnectionPool(host='192.168.25.126', port=6379, password='123456', db=0)
      coon = redis.Redis(connection_pool=pool)
      coon.set('key', 'value')
      res = coon.get('key')
      return res
coon.set('sea', 'hahhahaha', ex=30)    # 过期时间单位s
set(name, value, ex=None, px=None, nx=False, xx=False)
在 Redis 中设置值,默认,不存在则创建,存在则修改。
参数:
ex - 过期时间(秒)
px - 过期时间(毫秒)
nx - 如果设置为True,则只有name不存在时,当前set操作才执行
xx - 如果设置为True,则只有name存在时,当前set操作才执行

redis uses connection pool operation

class OPRedis(object):

    def __init__(self):
        if not hasattr(OPRedis, 'pool'):
            OPRedis.getRedisCoon()  #创建redis连接
        self.coon = redis.Redis(connection_pool=OPRedis.pool)

    @staticmethod
    def getRedisCoon():
        OPRedis.pool = redis.ConnectionPool(host=redisInfo['host'], password=redisInfo['password'], port=redisInfo['port'], db=redisInfo['db'])

    """
    string类型 {'key':'value'} redis操作
    """

    def setredis(self, key, value, time=None):
        #非空即真非0即真
        if time:
            res = self.coon.setex(key, value, time)
        else:
            res = self.coon.set(key, value)
        return res

    def getRedis(self, key):
        res = self.coon.get(key).decode()
        return res

    def delRedis(self, key):
        res = self.coon.delete(key)
        return res

    """
    hash类型,{'name':{'key':'value'}} redis操作
    """
    def setHashRedis(self, name, key, value):
        res = self.coon.hset(name, key, value)
        return res


    def getHashRedis(self, name, key=None):
        # 判断key是否我为空,不为空,获取指定name内的某个key的value; 为空则获取name对应的所有value
        if key:
            res = self.coon.hget(name, key)
        else:
            res = self.coon.hgetall(name)
        return res


    def delHashRedis(self, name, key=None):
        if key:
            res = self.coon.hdel(name, key)
        else:
            res = self.coon.delete(name)
        return res

redisInfo configuration

redisInfo = {
    "host": '192.168.1.112',
    "password": '123456',
    "port": 6379,
    "db": 0
}

The above is the detailed content of What are the methods for operating redis in python?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What are class methods in Python What are class methods in Python Aug 21, 2025 am 04:12 AM

ClassmethodsinPythonareboundtotheclassandnottoinstances,allowingthemtobecalledwithoutcreatinganobject.1.Theyaredefinedusingthe@classmethoddecoratorandtakeclsasthefirstparameter,referringtotheclassitself.2.Theycanaccessclassvariablesandarecommonlyused

python asyncio queue example python asyncio queue example Aug 21, 2025 am 02:13 AM

asyncio.Queue is a queue tool for secure communication between asynchronous tasks. 1. The producer adds data through awaitqueue.put(item), and the consumer uses awaitqueue.get() to obtain data; 2. For each item you process, you need to call queue.task_done() to wait for queue.join() to complete all tasks; 3. Use None as the end signal to notify the consumer to stop; 4. When multiple consumers, multiple end signals need to be sent or all tasks have been processed before canceling the task; 5. The queue supports setting maxsize limit capacity, put and get operations automatically suspend and do not block the event loop, and the program finally passes Canc

How do you stay updated with the latest features and best practices for Redis? How do you stay updated with the latest features and best practices for Redis? Aug 20, 2025 pm 02:58 PM

Maintaining knowledge of Redis’s latest features and best practices is the key to continuous learning and focus on official and community resources. 1. Regularly check Redis official website, document updates and ReleaseNotes, subscribe to the GitHub repository or mailing list, get version update notifications and read the upgrade guide. 2. Participate in technical discussions on Redis's Google Groups mailing list, Reddit sub-section, StackOverflow and other platforms to understand other people's experience and problem solutions. 3. Build a local testing environment or use Docker to deploy different versions for functional testing, integrate the Redis upgrade test process in CI/CD, and master the value of feature through actual operations. 4. Close

How to use regular expressions with the re module in Python? How to use regular expressions with the re module in Python? Aug 22, 2025 am 07:07 AM

Regular expressions are implemented in Python through the re module for searching, matching and manipulating strings. 1. Use re.search() to find the first match in the entire string, re.match() only matches at the beginning of the string; 2. Use brackets() to capture the matching subgroups, which can be named to improve readability; 3. re.findall() returns all non-overlapping matches, and re.finditer() returns the iterator of the matching object; 4. re.sub() replaces the matching text and supports dynamic function replacement; 5. Common patterns include \d, \w, \s, etc., you can use re.IGNORECASE, re.MULTILINE, re.DOTALL, re

How to debug a remote Python application in VSCode How to debug a remote Python application in VSCode Aug 30, 2025 am 06:17 AM

To debug a remote Python application, you need to use debugpy and configure port forwarding and path mapping: First, install debugpy on the remote machine and modify the code to listen to port 5678, forward the remote port to the local area through the SSH tunnel, then configure "AttachtoRemotePython" in VSCode's launch.json and correctly set the localRoot and remoteRoot path mappings. Finally, start the application and connect to the debugger to realize remote breakpoint debugging, variable checking and code stepping. The entire process depends on debugpy, secure port forwarding and precise path matching.

How to build and run Python in Sublime Text? How to build and run Python in Sublime Text? Aug 22, 2025 pm 03:37 PM

EnsurePythonisinstalledbyrunningpython--versionorpython3--versionintheterminal;ifnotinstalled,downloadfrompython.organdaddtoPATH.2.InSublimeText,gotoTools>BuildSystem>NewBuildSystem,replacecontentwith{"cmd":["python","-

How to pass command-line arguments to a script in Python How to pass command-line arguments to a script in Python Aug 20, 2025 pm 01:50 PM

Usesys.argvforsimpleargumentaccess,whereargumentsaremanuallyhandledandnoautomaticvalidationorhelpisprovided.2.Useargparseforrobustinterfaces,asitsupportsautomatichelp,typechecking,optionalarguments,anddefaultvalues.3.argparseisrecommendedforcomplexsc

What are the key metrics to monitor for a healthy Redis instance? What are the key metrics to monitor for a healthy Redis instance? Aug 29, 2025 am 06:38 AM

TokeepaRedisinstancehealthy,monitorkeymetricsinthefollowingorder:1.Memoryusage,trackingused_memoryandused_memory_rsswhileapproachingsystemRAMlimits,andmanagingitviamaxmemory,evictionpolicies,efficientdatastructures,andcompression;2.CPUutilization,mon

See all articles