Learn python from scratch with me (5) database programming: Redis database

foreword

Looking back, I talked about python syntax programming, compulsory introductory basics and network programming, multi-threading/multi-process/coroutine, etc. yesterday, I talked about database programming MySQL, and today's second Redis chapter. Turning forward, the series of articles have been sorted out:

1. Learn python from scratch with me (1) Compulsory programming grammar
2. Learn python from scratch with me (2) Network programming
3. Learn python from scratch with me (3) Multi-thread/multi-process/ Coroutine
4. Learn python from scratch with me (4) Database programming: MySQL database

This article talks about: Python database programming: Redis database

Pay attention to the official account: python technology training camp , learn advanced step by step

Python resources suitable for zero-based learning and advanced people:

① Tencent certified python complete project practical tutorial notes PDF
② More than a dozen major manufacturers python interview topic PDF
③ Python full set of video tutorials (zero foundation-advanced advanced JS reverse)
④ Hundreds of project actual combat + source code + notes
⑤ Programming grammar - machine learning -Full-stack development-data analysis-crawler-APP reverse engineering and other full set of projects + documents
⑥ Exchange and study
⑦ Want to take part-time orders

This series of articles is based on the following learning routes. Due to the large content:

Learn python from scratch to advanced advanced roadmap

Python database programming: Redis database

1. Basic operation commands of server and client

Redis is a memory-based data structure storage system that is often used in scenarios such as caching, message queues, and leaderboards. The following introduces some basic operation commands of the Redis server and client.

1. Server command

Start the Redis service

redis-server

Close the Redis service

redis-cli shutdown

View Redis service status

redis-cli ping

View Redis service version

redis-cli info server

View Redis service configuration

redis-cli config get *

Modify the Redis service configuration

redis-cli config set <parameter> <value>

2. Client command

Connect to Redis service

redis-cli -h <host> -p <port> -a <password>

Set key-value pairs

redis-cli set <key> <value>

get key-value pair

redis-cli get <key>

delete key-value pair

redis-cli del <key>

Check if the key exists

redis-cli exists <key>

Set the key's expiration time

redis-cli expire <key> <seconds>

Check key expiration time

redis-cli ttl <key>

view all keys

redis-cli keys *

View key type

redis-cli type <key>

list manipulation

redis-cli lpush <key> <value>  # 从左侧插入元素
redis-cli rpush <key> <value>  # 从右侧插入元素
redis-cli lrange <key> <start> <stop>  # 获取列表元素
redis-cli lpop <key>  # 从左侧弹出元素
redis-cli rpop <key>  # 从右侧弹出元素

set operation

redis-cli sadd <key> <value>  # 添加元素
redis-cli smembers <key>  # 获取所有元素
redis-cli sismember <key> <value>  # 判断元素是否存在
redis-cli srem <key> <value>  # 删除元素

hash table operations

redis-cli hset <key> <field> <value>  # 设置字段值
redis-cli hget <key> <field>  # 获取字段值
redis-cli hgetall <key>  # 获取所有字段和值
redis-cli hdel <key> <field>  # 删除字段

sorted set operations

redis-cli zadd <key> <score> <value>  # 添加元素
redis-cli zrange <key> <start> <stop>  # 获取元素
redis-cli zrem <key> <value>  # 删除元素

The above are the basic operation commands of the Redis server and client. For more commands, please refer to the official Redis documentation.

2. Data manipulation

1.string

Redis is a memory-based data storage system that supports multiple data structures, one of which is string. In Python, we can use the redis-py library to manipulate the string data type in the Redis database.

The following are some commonly used Redis string manipulation commands:

①.set(key, value): Set the value corresponding to the key

import redis

r = redis.Redis(host='localhost', port=6379, db=0)

r.set('name', 'Tom')

②.get(key): Get the value corresponding to the key

import redis

r = redis.Redis(host='localhost', port=6379, db=0)

name = r.get('name')
print(name)

③.mset(mapping): Set multiple key-value pairs in batches

import redis

r = redis.Redis(host='localhost', port=6379, db=0)

r.mset({'name': 'Tom', 'age': 18})

④.mget(keys): Get the value corresponding to multiple keys in batches

import redis

r = redis.Redis(host='localhost', port=6379, db=0)

values = r.mget(['name', 'age'])
print(values)

⑤.incr(key, amount=1): Increase the value corresponding to the key by the amount

import redis

r = redis.Redis(host='localhost', port=6379, db=0)

r.set('count', 1)
r.incr('count')

⑥.decr(key, amount=1): Decrease the value corresponding to the key by the amount

import redis

r = redis.Redis(host='localhost', port=6379, db=0)

r.set('count', 10)
r.decr('count', 5)

⑦.append(key, value): Append the value to the end of the value corresponding to the key

import redis

r = redis.Redis(host='localhost', port=6379, db=0)

r.set('name', 'Tom')
r.append('name', ' Smith')

⑧.strlen(key): Get the length of the value corresponding to the key

import redis

r = redis.Redis(host='localhost', port=6379, db=0)

name_len = r.strlen('name')
print(name_len)

The above are some basic operation commands of the Redis string data type, which can be used according to actual needs.

2. Key commands

Key commands in Redis are used to manage and manipulate key-value pairs. Here are some commonly used key commands :

  • SET key value : Set a key-value pair. If the key already exists, the original value will be overwritten.
  • GET key : Get the value corresponding to the key.
  • DEL key : Delete the specified key-value pair.
  • EXISTS key : Checks if the specified key exists.
  • KEYS pattern : Find all keys matching the given pattern.
  • TTL key : Get the expiration time of the key, in seconds.
  • EXPIRE key seconds : Set the expiration time of the key, in seconds.
  • PERSIST key : Remove the expiration time of the key, making it permanently valid.
  • TYPE key : Get the data type of the value corresponding to the key.

These commands can be invoked through the corresponding methods in the Python Redis module, for example:

import redis

# 连接Redis数据库
r = redis.Redis(host='localhost', port=6379, db=0)

# 设置键值对
r.set('name', 'Alice')

# 获取键对应的值
name = r.get('name')
print(name)

# 删除指定的键值对
r.delete('name')

# 检查指定的键是否存在
exists = r.exists('name')
print(exists)

# 查找所有符合给定模式的键
keys = r.keys('*')
print(keys)

# 获取键的过期时间
ttl = r.ttl('name')
print(ttl)

# 设置键的过期时间
r.expire('name', 60)

# 移除键的过期时间
r.persist('name')

# 获取键对应的值的数据类型
type = r.type('name')
print(type)

3.hash

In Redis, Hash is a collection of key-value pairs, where the key and value are both string types. Hash can be used to store objects, such as user information, product information, etc.

The following are some common commands for operating Hash in Python Redis:

①.HSET(key, field, value): Set the value of the specified field in the Hash

redis_conn.hset('user:1', 'name', 'Alice')

②.HGET(key, field): Get the value of the specified field in the Hash

redis_conn.hget('user:1', 'name')

③.HMSET(key, mapping): Set the values ​​of multiple fields in the Hash

redis_conn.hmset('user:1', {'age': 20, 'gender': 'female'})

④.HMGET(key, fields): Get the values ​​of multiple fields in the Hash

redis_conn.hmget('user:1', 'name', 'age', 'gender')

⑤.HGETALL(key): Get all fields and values ​​in the Hash

redis_conn.hgetall('user:1')

⑥.HDEL(key, field): delete the specified field in the Hash

redis_conn.hdel('user:1', 'gender')

⑦.HEXISTS(key, field): Determine whether the specified field exists in the Hash

redis_conn.hexists('user:1', 'gender')

⑧.HKEYS(key): Get all the fields in the Hash

redis_conn.hkeys('user:1')

⑨.HVALS(key): Get all the values ​​in the Hash

redis_conn.hvals('user:1')

⑩.HLEN(key): Get the number of fields in the Hash

redis_conn.hlen('user:1')

The above are some common commands for operating Hash in Python Redis, which can be selected according to actual needs.

4.list

List in Redis is a doubly linked list that supports insertion and deletion at the head and tail. Each element in the List is a string.

The redis-py library can be used in Python to operate the List data type in the Redis database.

First you need to import the redis library:

import redis

Connect to the Redis database:

r = redis.Redis(host='localhost', port=6379, db=0)

List operation

①. Insert element

Insert one or more elements at the head of the List:

r.lpush('list_key', 'value1', 'value2', 'value3')

Insert one or more elements at the end of the List:

r.rpush('list_key', 'value4', 'value5', 'value6')

Insert an element before or after the specified element:

r.linsert('list_key', 'BEFORE', 'value2', 'new_value')
r.linsert('list_key', 'AFTER', 'value2', 'new_value')

②. Get elements

Get the elements within the specified range in the List:

r.lrange('list_key', 0, -1)  # 获取所有元素
r.lrange('list_key', 0, 2)  # 获取前三个元素
r.lrange('list_key', -3, -1)  # 获取后三个元素

Get the element at the specified index in the List:

r.lindex('list_key', 0)  # 获取第一个元素
r.lindex('list_key', -1)  # 获取最后一个元素

③. Delete element

Remove an element from the head of the List:

r.lpop('list_key')

Remove an element from the end of the List:

r.rpop('list_key')

Delete the specified elements in the List:

r.lrem('list_key', 0, 'value2')  # 删除所有值为value2的元素
r.lrem('list_key', 1, 'value2')  # 删除第一个值为value2的元素
r.lrem('list_key', -1, 'value2')  # 删除最后一个值为value2的元素

④. Other operations

Get the length of List:

r.llen('list_key')

Move the last element in a List to the head of another List:

r.rpoplpush('list_key', 'new_list_key')

Blockingly pop an element from the end of one List and insert it into the head of another:

r.brpoplpush('list_key', 'new_list_key', timeout=0)

The above is the common method of operating the List data type in the Redis database in Python.

5.set

Set in Redis is an unordered collection. Its function is similar to that of List. It is a collection of multiple string elements. But Set is different from List in that duplicate elements are not allowed in Set, and the elements in Set are unordered.

To operate the Set of Redis in Python, you can use the set method in the redis module. The following are some commonly used Set operations:

①. Add elements

import redis

r = redis.Redis(host='localhost', port=6379, db=0)

# 添加单个元素
r.sadd('set_key', 'value1')

# 添加多个元素
r.sadd('set_key', 'value2', 'value3', 'value4')

②. Get elements

import redis

r = redis.Redis(host='localhost', port=6379, db=0)

# 获取所有元素
members = r.smembers('set_key')
print(members)

# 判断元素是否存在
is_member = r.sismember('set_key', 'value1')
print(is_member)

③. Delete elements

import redis

r = redis.Redis(host='localhost', port=6379, db=0)

# 删除单个元素
r.srem('set_key', 'value1')

# 删除多个元素
r.srem('set_key', 'value2', 'value3', 'value4')

# 删除集合
r.delete('set_key')

④. Set operations

import redis

r = redis.Redis(host='localhost', port=6379, db=0)

# 求交集
r.sadd('set_key1', 'value1', 'value2', 'value3')
r.sadd('set_key2', 'value2', 'value3', 'value4')
intersection = r.sinter('set_key1', 'set_key2')
print(intersection)

# 求并集
union = r.sunion('set_key1', 'set_key2')
print(union)

# 求差集
difference = r.sdiff('set_key1', 'set_key2')
print(difference)

Set 6

In Redis, ZSET (ordered set) is a special data structure, which is a collection of key-value pairs, each of which is associated with a floating-point score. This score is used to sort the elements in order from smallest value to largest value. Members of ZSET are unique, but scores can be repeated.

Python Redis method of operating ordered collections :

①. Add elements
Use zaddthe command to add elements to the ordered collection, the syntax is as follows:

zadd(name, mapping)

where nameis the name of the sorted set and mappingis a dictionary denoting the elements to be added and their scores. For example:

redis.zadd('myzset', {'one': 1, 'two': 2, 'three': 3})

②. Get elements
Use zrangethe command to get the elements within the specified range in the ordered set, the syntax is as follows:

zrange(name, start, end, withscores=False)

Among them, nameis the name of the ordered collection, startand endrepresent the start position and end position of the element to be obtained respectively (counting from 0), and withscoresindicate whether to return the score of the element at the same time. For example:

redis.zrange('myzset', 0, -1, withscores=True)

③. Get the number of elements
Use zcardthe command to get the number of elements in the ordered set, the syntax is as follows:

zcard(name)

where nameis the name of the ordered set. For example:

redis.zcard('myzset')

④. Get the rank of elements
Use zrankthe command to get the rank of the specified element in the ordered set, the syntax is as follows:

zrank(name, value)

where nameis the name of the sorted set and valueis the element whose rank is to be obtained. For example:

redis.zrank('myzset', 'two')

⑤. Get element score
Use zscorethe command to get the score of the specified element in the ordered set, the syntax is as follows:

zscore(name, value)

where nameis the name of the sorted set and valueis the element whose score is to be obtained. For example:

redis.zscore('myzset', 'two')

⑥.Delete element
Use zremthe command to delete the specified element from the ordered set, the syntax is as follows:

zrem(name, values)

where nameis the name of the sorted set and valuesis the element to be removed. For example:

redis.zrem('myzset', 'two')

⑦. Get the elements within the specified score range
Use zrangebyscorethe command to get the elements within the specified score range in the ordered set, the syntax is as follows:

zrangebyscore(name, min, max, start=None, num=None, withscores=False, score_cast_func=float)

Among them, nameis the name of the ordered collection, minand maxrepresent the minimum and maximum value of the score range to be obtained, startand numrepresent the starting position and quantity of the elements to be obtained (counting from 0), and withscoresindicate whether to return the elements at the same time Score, score_cast_funcrepresenting a type conversion function for fractions. For example:

redis.zrangebyscore('myzset', 1, 2, withscores=True)

Three, python operation Redis

1. Redis library

Redis is an open source memory data structure storage system that supports a variety of data structures, including strings, hashes, lists, sets, and ordered sets. Redis is characterized by fast speed, high reliability, and supports rich data structures and operations, so it is widely used in scenarios such as caching, message queues, counters, and leaderboards.

Python is a high-level programming language, which is easy to learn, concise code, and strong readability, so it is widely used in Web development, data analysis, artificial intelligence and other fields. Python provides a variety of Redis client libraries, which can easily operate the Redis database.

To operate Redis with Python, you need to install the Redis client library first. The commonly used ones are redis-py, redis, and hiredisso on. Among them redis-pyis the Python client library officially recommended by Redis, which supports Python 2 and Python 3, provides a rich API, and is easy to use.

You can use the pip command to install the redis-py library :

pip install redis

After the installation is complete, you can use the library to operate the Redis database in Python redis-py. Here is a simple example:

import redis

# 连接Redis数据库
r = redis.Redis(host='localhost', port=6379, db=0)

# 设置键值对
r.set('name', 'Tom')

# 获取键值对
name = r.get('name')
print(name)

In the above example, first use redis.Redis()the method to connect to the Redis database, then use r.set()the method to set the key-value pair, and use r.get()the method to get the key-value pair. Among them, hostthe parameter specifies the address Redisof the server IP, portthe parameter specifies Redisthe port number of the server, and dbthe parameter specifies Redisthe number of the database. If no dbparameter is specified, database number 0 is used by default.

In addition to set()and get()methods, redis-pythe library also provides a variety of methods to operate the Redis database, including , incr(), decr(), hset(), hget(), lpush(), rpush(), lrange(), sadd(), smembers(), zadd()etc.zrange()

Connect to the Redis database :

import redis

# 连接Redis数据库
r = redis.Redis(host='localhost', port=6379, db=0)

Set key-value pairs :

# 设置键值对
r.set('name', 'Tom')

Get key-value pairs :

# 获取键值对
name = r.get('name')
print(name)

Delete key-value pairs :

# 删除键值对
r.delete('name')

Set expiration time :

# 设置过期时间
r.setex('name', 10, 'Tom')  # 10秒后过期

Check if the key exists :

# 判断键是否存在
if r.exists('name'):
    print('name exists')
else:
    print('name does not exist')

Increment and decrement :

# 自增
r.incr('count')
# 自减
r.decr('count')

The above are the basic operations of the Redis library

2. python-redis operations on string types

Redis is an in-memory key-value pair storage database that supports different categories of data types, one of which is the string type. String type is the most basic data type in Redis. The following are some basic operations for manipulating the String type in Redis:

①. Set String

We can set()set String using method. If the key does not exist, a new key is created and the string value is stored. Overwrites the old value for the key if it already exists. For example:

import redis

r = redis.Redis(host='localhost', port=6379, db=0)

r.set('key', 'value')

This will create a key in Redis called "key" and set its value to "value".

②. Get String

We can use get() method to get the value of String. For example:

value = r.get('key')

This will return the current value of the key named "key".

③.Delete String

We can use delete()method to delete String. For example:

r.delete('key')

This will delete the key named "key".

④. Operation String

Redis also provides many other methods for manipulating Strings, such as:

  • append(key, value): Append value to the end of key.
  • incr(key[, amount]): Increment the value of the key named "key", you can add +1 or add a custom value amount.
  • decr(key[, amount]): Decrement the value of the key named "key", which can be reduced by -1 or by a custom value amount.
  • setnx(key, value): Set the key's value to "value" only if the key "key" does not exist.
  • getset(key, value): Set the value of the key "key" to "value", and return the previous value of the key "key".

For example, to increase the value of the "in_stock" key by 2:

r.set("in_stock",10)
r.incr("in_stock",2) 
print(r.get("in_stock"))

This will return 12 because "in_stock"the key's value is increased by 2 from 10.

These are some basic operations on the String type in Redis. We can also use other methods to choose and use according to specific application requirements.

Pay attention to the official account: python technology training camp , learn advanced step by step

Python resources suitable for zero-based learning and advanced people:

① Tencent certified python complete project practical tutorial notes PDF
② More than a dozen major manufacturers python interview topic PDF
③ Python full set of video tutorials (zero foundation-advanced advanced JS reverse)
④ Hundreds of project actual combat + source code + notes
⑤ Programming grammar - machine learning -Full-stack development-data analysis-crawler-APP reverse engineering and other full set of projects + documents
⑥ Exchange and study
⑦ Want to take part-time orders

The next chapter will talk about: python database programming: MongoDB database

Guess you like

Origin blog.csdn.net/ch950401/article/details/131639970