SoFunction
Updated on 2024-11-19

Python call Redis sample code

Python call Redis sample code

Updated November 24, 2020 11:21:10 by LeoZhanggg
This article mainly introduces the Python call Redis sample code, to help you better understand and learn python, interested parties can understand the following
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# *************************************
# @Time  : 2019/8/12
# @Author : Zhang Fan
# @Desc  : Library
# @File  : 
# @Update : 2019/8/23
# *************************************
import redis


class MyRedis(object):
  """
  ===================================================================
  =====================    MyRedis    ========================
  ===================================================================
  """
  def __init__(self):
    self.redis_conn = None
    self.redis_db = None

  def connect_to_redis(self, redis_host, redis_port=6379, db=0, password=None):
    """
    Connecting to the Redis server
    """
    self.redis_db = db
    print('Executing : Connect To Redis | host={0}, port={1}, db={2}, password={3}'
           .format(redis_host, redis_port, self.redis_db, password))
    try:
      self.redis_conn = (
        host=redis_host, port=redis_port, db=self.redis_db, password=password)
    except Exception as ex:
      (str(ex))
      raise Exception(str(ex))

  def redis_key_should_be_exist(self, name):
    """
    Verify that the specified key exists in redis
    """
    if not self.redis_conn.exists(name):
      (("Redis of db%s doesn't exist in key [ %s ]." % (self.redis_db, name)))
      raise AssertionError

  def redis_key_should_not_be_exist(self, name):
    """
    Verify that the specified key does not exist in redis
    """
    if self.redis_conn.exists(name):
      (("Redis of db%s exist in key [ %s ]." % (self.redis_db, name)))
      raise AssertionError

  def getkeys_from_redis_bypattern(self, pattern, field=None):
    """
    Get all keys in redis
    """
    keys_list = list()
    print('Executing : Getall Key | %s' % pattern)
    if field is None:
      return self.redis_conn.keys(pattern)
    else:
      keys = self.redis_conn.keys(pattern)
      for key in keys:
        if not self.redis_conn.hget(key, field) is None:
          keys_list.append(key)
      return keys_list

  # ========================== String Type =============================
  def get_from_redis(self, name):
    """
    Getting redis data
    """
    print('Executing : Get Key | %s' % name)
    return self.redis_conn.get(name)

  def del_from_redis(self, name):
    """
    Deleting any data type in redis
    """
    return self.redis_conn.delete(name)

  def set_to_redis(self, name, data, expire_time=0):
    """
    Setting the value of the redis execution key
    """
    return self.redis_conn.set(name, data, expire_time)

  def append_to_redis(self, name, value):
    """
    Adding data to redis
    """
    return self.redis_conn.append(name, value)

    # ========================== Hash Type ==========================
  def hgetall_from_redis(self, name):
    """
    Get redis hash all data
    """
    print('Executing : Hgetall Key | %s' % name)
    return self.redis_conn.hgetall(name)

  def hget_from_redis(self, name, key):
    """
    Get redis hash specified key data
    """
    print('Executing : Hget Key | %s' % name)
    return self.redis_conn.hget(name, key)

  def hset_to_redis(self, name, key, data):
    """
    Set the value of the specified key in redis
    """
    print(('Executing : Hset Redis | name={0}, key={1}, data={2}'
           .format(name, key, data)))
    return self.redis_conn.hset(name, key, data)

  def hdel_to_redis(self, name, *keys):
    """
    Delete the value of the specified key from redis
    """
    print('Executing : Hdel Key | ', *keys)
    self.redis_conn.hdel(name, *keys)

  # ========================= ZSet Type ================================
  def get_from_redis_zscore(self, name, values):
    """
    Get the score corresponding to value in the ordered set corresponding to name
    """
    try:
      return int(self.redis_conn.zscore(name, values))
    except:
      return self.redis_conn.zscore(name, values)

  def get_from_redis_zrange(self, name, start=0, end=10):
    """
    Get the elements of the ordered set corresponding to name by index range
    """
    return self.redis_conn.zrange(name, start, end, desc=False, withscores=True, score_cast_func=int)

  def del_from_redis_zrem(self, name, values):
    """
    Removes the member of the ordered set corresponding to name whose value is values
    """
    return self.redis_conn.zrem(name, values)

  def add_from_redis_zadd(self, name, value, score):
    """
    Add an entry to the ordered set corresponding to name. If the value exists, modify the corresponding score.
    """
    return self.redis_conn.zadd(name, {value: score})

  def count_from_redis_zcard(self, name):
    """
    Get the number of ordered set elements corresponding to name
    """
    return self.redis_conn.zcard(name)


if __name__ == '__main__':
  print('This is test.')
  mr = MyRedis()

Above is Python call Redis sample code details, more information about Python call Redis please pay attention to my other related articles!

  • Python
  • call (programming)
  • Redis

Related articles

  • Python annotations in detail

    The following is a detailed explanation of Python annotations. I think it is quite good, now share it with you, but also give you a reference. Together follow the editor over to see it
    2016-06-06
  • Python online running code assistant

    The Python Code Runner Helper allows you to enter Python code online and have it executed by a Python script running locally.
    2016-07-07
  • Python crawler basic requests module

    This article introduces the basis of Python crawler requests module, there are very detailed code examples, is learning python crawler partners have a very good help, need friends can refer to the next!
    2021-04-04
  • How python modules are viewed

    In this article, I am going to give you a compilation of knowledge about python's module location, if you need it, you can refer to the following.
    2020-06-06
  • Python Machine Learning Chapter 1 Environment Configuration Diagram Flow

    Machine learning is an umbrella term for a class of algorithms that attempt to mine large amounts of historical data for implicit patterns that can be used for prediction or classification; more specifically, machine learning can be thought of as finding a function where the input is sample data and the output is a desired outcome, except that the function is so complex that it is less convenient to express it formally
    2021-11-11
  • Analyzing how to parse and modify XML in Python

    We often need to parse data written in different languages.Python provides many libraries to parse or split data written in other languages. In this Python XML Parser tutorial, you will learn how to parse XML using Python.
    2021-06-06
  • Python Business Card Management System

    This article introduces the Python version of the business card management system in detail, with certain reference value, interested partners can refer to it!
    2018-11-11
  • Python crawler to get the list of funds

    This article introduces the Python crawler to get the list of funds, python crawler is used to collect data is the most direct and commonly used methods, you can use the python crawler program to obtain a large amount of data, the following more related content, the need for partners can refer to it
    2022-05-05
  • An in-depth look at a small summary of ways to efficiently reverse-order tables in Python

    In Python programming, sometimes you need to list the elements in reverse order, this article introduces the Python in reverse order of the list of several common methods, I hope to help you to a certain extent!
    2024-01-01
  • python3.8 download and installation steps in detail

    This article introduces the python3.8 download and installation steps explained, this article illustrates and gives you a very detailed introduction, with certain reference value, the need for friends can refer to the following
    2020-01-01

Latest Comments