SoFunction
Updated on 2025-05-12

Python connects Redis to add, delete, modify and check (CRUD) operations

introduce

Redis is an open source memory data structure storage system that supports multiple data structures (such as strings, hashs, lists, collections, ordered collections, etc.), and is widely used in cache, session management, message queues and other scenarios. This article will introduce how to use it in Pythonredis-pyThe library connects to the Redis database and performs common additions, deletions, modifications and checks.

Install redis-py

First, it needs to be installedredis-pyLibrary, this is the official client for Python to interact with Redis.

pip install redis

Connect Redis

Before performing the addition, deletion, modification and search operations, we first need to connect to the Redis server. Assume that the Redis service is running on the local default port 6379.

import redis

# Connect to Redis Servicer = (host='localhost', port=6379, db=0, decode_responses=True)

Parameter description:

  • host: The host of Redis service, default is'localhost'
  • port: The port of Redis service, default is6379
  • db: Select the database to use. Redis has 16 databases by default, with numbers from 0 to 15, and the default connection isdb=0
  • decode_responses=True: Make sure the result returned is a string, not a byte.

Add (Create)

Redis supports operations of multiple data structures, we can useset()Method to set a key-value pair.

# Set a string type key-value pair('name', 'John Doe')

# Set multiple key-value pairs({'age': 30, 'city': 'New York'})
  • set(): Set the value of a key. If the key already exists, the original value will be overwritten.
  • mset(): Set multiple key-value pairs in batches.

Query (Read)

Can be passedget()Method to get the stored value in Redis.

# Get the value of a single keyname = ('name')
print(f'Name: {name}')  # Output: Name: John Doe
# Get the values ​​of multiple keysvalues = ('name', 'age', 'city')
print(values)  # Output: ['John Doe', '30', 'New York']
  • get(): Get the value of the specified key.
  • mget(): Batch get the values ​​of multiple keys.

Update

Redis's update operation is actually throughset()To achieve it, becauseset()Will overwrite existing key-value pairs.

# Update the value of the key 'age'('age', 35)
print(('age'))  # Output: 35

Delete

If you need to delete a key-value pair, you can usedelete()method.

# Delete key 'city'('city')
print(('city'))  # Output: None, because the key 'city' has been deleted
  • delete(): Delete the specified key, if the key does not exist, do nothing.

Other common operations

In addition to basic CRUD operations, Redis supports some other useful operations:

Check if the key exists

# Check whether the key 'name' existsexists = ('name')
print(exists)  # Output: True

Set the expiration time of the key

# Set the key 'name' expires after 10 seconds('name', 10)

Get the expiration time of the key

# Get the remaining expiration time of the key 'name'ttl = ('name')
print(ttl)  # Output: The remaining seconds

Use hash type to store data

Redis also supports hash types, suitable for storing structured data. Can be usedhset()hget()etc. operate hashing.

# Set the hash key 'user' and store the fields 'name' and 'age'('user', 'name', 'John Doe')
('user', 'age', 30)

# Get fields in hashname = ('user', 'name')
age = ('user', 'age')
print(f'Name: {name}, Age: {age}')

Summarize

This article shows how to use it in Pythonredis-pyThe library connects Redis and performs addition, deletion, modification and search operations. Redis’s flexibility and efficiency make it ideal for building high-performance applications. In addition to the basic operations introduced in this article, Redis also provides many advanced functions, such as transactions, pipelines, publishing and subscriptions, etc., which can be further expanded according to the specific application scenario.

Complete example

Shows how to use Python to connect to Redis and perform operations such as adding, checking, modifying, and deleting. Will useredis-pylibrary and operate using Redis's multiple data structures. Examples will include basic string operations, hash operations, and how to set the expiration time of a key.

import redis

# Connect to Redis Servicer = (host='localhost', port=6379, db=0, decode_responses=True)

# 1. Add (Create) operation# Set key-value pairs of string type('name', 'John Doe')
('age', 30)
('city', 'New York')

# Set a hash type key-value pair('user:1000', 'name', 'Alice')
('user:1000', 'age', 25)

# Set multiple key-value pairs in batches({'country': 'USA', 'language': 'English'})

# Print the resultsprint(f"Set 'name': {('name')}")
print(f"Set 'age': {('age')}")
print(f"Set 'city': {('city')}")
print(f"Set 'country' and 'language': {('country', 'language')}")

# 2. Query (Read) operation# Get a single key valueprint("\n--Query Operation--")
name = ('name')
print(f"Name: {name}")

# Get multiple key valuesuser_data = ('name', 'age', 'city', 'country', 'language')
print(f"User data: {user_data}")

# Get fields in hashuser_name = ('user:1000', 'name')
user_age = ('user:1000', 'age')
print(f"User 1000 Name: {user_name}, Age: {user_age}")

# 3. Update operation# Update the value of string type('age', 35)
print(f"Updated 'age': {('age')}")

# Update fields in the hash('user:1000', 'age', 26)
print(f"Updated 'user:1000' age: {('user:1000', 'age')}")

# 4. Delete operation# Delete a single key('city')
print(f"Deleted 'city', current value: {('city')}")

# Delete fields in the hash('user:1000', 'name')
print(f"Deleted 'name' from 'user:1000', current fields: {('user:1000')}")

# 5. Set the expiration time of the key# Set the 'country' key to expire in 5 seconds('country', 5)
print(f"Is 'country' key expired? {('country')}")  # Initially True
# Wait for 6 seconds, the key should expireimport time
(6)
print(f"After waiting 6 seconds, is 'country' expired? {('country')}")  # should be False
# 6. Other operations: Check whether the key existskey_exists = ('name')
print(f"Does 'name' exist? {key_exists}")

# Get the remaining survival time of the keyttl = ('age')
print(f"The remaining time-to-live for 'age' is: {ttl} seconds")

# Get all fields and values ​​in the hashuser_data_all = ('user:1000')
print(f"All fields in 'user:1000': {user_data_all}")

# Finishprint("\n-- Complete all operations --")

Code description:

  • Connect Redisuse()To create a Redis connection object, specifying the host name, port, and database index. Used heredecode_responses=True, let the result returned is a string instead of a byte.

  • Create operation

    • useset()Sets a key-value pair of string type.
    • usehset()Sets a field of hash type.
    • usemset()Set multiple key-value pairs in batches.
  • Check (Read) operations

    • useget()Gets the value of a single string type.
    • usemget()Get the values ​​of multiple keys in batches.
    • usehget()Gets the value of the specified field of the hash type.
    • usehgetall()Gets all fields in the hash and their corresponding values.
  • Update operationUpdate operation is calledset()orhset()To achieve it. Redis will automatically overwrite existing values.

  • Delete operation

    • usedelete()Delete a single key.
    • usehdel()Delete a field in the hash.
  • Expiration timeuseexpire()Set the expiration time of the key, in seconds. usettl()Get the remaining survival time.

  • Check if the key existsuseexists()Determine whether a key exists.

Example of run result:

Set 'name': John Doe
Set 'age': 30
Set 'city': New York
Set 'country' and 'language': ['USA', 'English']

--Query operation--
Name: John Doe
User data: ['John Doe', '30', 'New York', 'USA', 'English']
User 1000 Name: Alice, Age: 25

Updated 'age': 35
Updated 'user:1000' age: 26
Deleted 'city', current value: None
Deleted 'name' from 'user:1000', current fields: {'age': '26'}

Is 'country' key expired? True
After waiting 6 seconds, is 'country' expired? False
Does 'name' exist? True
The remaining time-to-live for 'age' is: -1 seconds
All fields in 'user:1000': {'age': '26'}

-- Complete all operations --

Summarize

With this complete example, we show how to use Python throughredis-pyThe library and Redis perform basic addition, deletion, modification and check operations, and cover some commonly used functions in Redis, such as setting the expiration time and checking whether the key exists. These operations are suitable for application scenarios such as cache management, session storage, real-time data processing, etc.

This is the article about Python connecting to Redis for adding, deleting, modifying and checking (CRUD) operations. For more related content related to Python connecting to Redis, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!