1. Introduction

The previous two articles talked about the common ways Python handles Mysql and Sqlite databases. This article continues with another common way to store data: Redis

Redis: Remote Dictionary Server, Redis is an open source, memory-based NoSql database written in C language

Redis is often used for caching data and high-speed read/write scenarios because of its superior performance and support of clustering, distribution and master-slave synchronization

This article will talk about the correct posture of Redis in Python

2. Prepare

In this example, redis-server is installed on cloud Server Centos 7.8

First, install the Redis database on the cloud server

Then, modify the Redis configuration file through the vim command, open the remote connection, and set the connection password

Configuration file directory: /etc/redis.conf

  • Bind was changed to 0.0.0.0 to allow extranet access

  • Requirepass Sets an access password

It should be pointed out that in order to ensure cloud server data security, Redis must strengthen the password when opening remote access

Then, start the Redis service, enable the firewall and port, and configure the cloud server security group

By default, the Redis service uses port number 6379

In addition, you need to configure the cloud server security group to ensure that the Redis database can be connected normally

After completing the above operations, we can connect through Redis-CLI or Redis client tools

Finally, to use Python to manipulate Redis, we need to install a dependency using PIP

3. The actual combat

Before we can manipulate data in Redis, we need to instantiate a Redis connection object with Host, port number, and password

Next, we’ll talk about Python’s methods for manipulating strings, lists, sets, Zsets, hash tables, and transactions

1. String manipulation

There are two ways to manipulate strings: set() and mset()

Set () can save only one value at a time

  • Name: key: indicates the key

  • Value: value, value to be saved

  • Ex: Indicates the expiration time, in seconds. If this parameter is not set, the expiration time is permanent. Otherwise, it will be deleted after expiration

  • Px: expiration time, in milliseconds

  • Nx /xx: Whether the set operation is performed depends on whether the name key exists

The operation methods for obtaining and deleting values are get(Key) and delete(Key or Keys) respectively.

For multi-valued data, simply call the mset() method, taking as arguments a dictionary of key-value pairs of the data to be inserted

Similarly, Redis provides the mget() method, which can fetch multiple key values at once

2. List operations

Redis provides a number of methods for manipulating lists, of which the following are common:

  • Lpush /rpush: Inserts one or more values to the head or tail of the list, where Lpush stands for head insert; Rpush stands for tail-insert data

  • Lset: Inserts a value into the corresponding position in the list through an index

  • Linsert: Inserts data before or after a list element

  • Lindex: Gets an element in a list by index, where 0 is the first element; Minus 1 is the last element

  • Lrange: Gets the value of the specified region from the list by specifying the start and end positions

  • Llen: Gets the length of the list. If the list corresponding to the Key does not exist, 0 is returned

  • Lpop: Removes and returns the first element in the list

  • Rpop: Removes and returns the last element in the list

Example code is as follows:

3. Operate the Set Set

A Set is an unordered Set of elements that cannot be repeated. Redis also provides many methods for manipulating sets

Among them, the common methods are as follows:

  • Sadd: Adds elements to a collection. Elements that already exist in the collection are ignored. If the collection does not exist, a new collection is created

  • Scard: Returns the number of collection elements

  • Smembers: Returns all elements in the collection

  • Srem: Removes one or more elements from the collection and ignores them if they do not exist

  • Sinter: Returns the intersection of two sets. The result is still a set

  • Sunion: Returns the union of two collections

  • Sdiff: Returns the difference between two sets, using the first set parameter as the criterion

  • Sunionstore: Calculates the union of two sets and saves it into a new set

  • Sismember: Determines whether an element exists in the set

  • Spop: Randomly removes an element from the collection and returns it

The specific example code is as follows:

4. Operate the zset set

Compared with ordinary set sets, zset sets are ordered. The elements in zset sets include: values and fractions, where fractions are used for sorting

Among them, the common methods are as follows:

  • Zadd: Adds elements to the collection, if the collection does not exist, creates a new collection, and then inserts data

  • Zrange: Returns the values of the elements in the collection (excluding fractions) by starting and ending points; If withscores=True, the result is returned withscores

  • Zscore: Gets the score of an element

  • Zcard: Gets the number of elements in the set

  • Zrank: Gets the index of the element in the collection

  • Zrem: Deletes elements in the collection

  • Zcount: Determines the number of elements in this range by the minimum and maximum values

The practice code is as follows:

4, operation hash

A hash table contains many key-value pairs, and each key is unique

Redis operates on a hash table. The following methods are commonly used:

  • Hset: Adds a key-value pair to a hash table

  • Hmset: Adds multiple key-value pairs to a hash table

  • Hget: Gets the value of a single key in a hash table

  • Hmget: Gets a list of values for multiple keys in a hash table

  • Hgetall: Gets all the key-value pairs in the hash table

  • Hkeys: Gets the list of all keys in the hash table

  • Hvals: Gets a list of all values in the hash table

  • Hexists: determines whether a key exists in a hash table

  • Hdel: deletes a key pair in the hash table

  • Hlen: Returns the number of key-value pairs in the hash table

The corresponding operation code is as follows:

5. Manipulate the transaction pipeline

Redis supports transaction piping, which enables several operations to be committed for execution

The operation steps are as follows:

  • First, define a transaction pipeline

  • It then performs a series of operations through the transaction object

  • Commit transaction operation to end transaction operation

Here is a simple example:

4. The last

This article realizes the operation of Redis common data through Python. Limited by space, it is impossible to expand and explain some uncommon methods in Redis

This article reprinted text, copyright belongs to the author, such as infringement contact xiaobian delete!

The original address: www.tuicool.com/articles/If…

For source code or more information (click here)