Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to operate Redis Library in Python

2025-03-30 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

Today, I will talk to you about how to operate the Redis library in Python, many people may not know much about it. In order to make you understand better, the editor has summarized the following content for you. I hope you can get something according to this article.

Redis library is very common in Internet applications, often exists as a "cache layer", because it is much faster than MySQL, Redis can be used as the only data repository of the application without MySQL, but if used with MySQL, because the performance is faster than MySQL, it is often used as the cache layer of Web application services, access to Redis first, access to MySQL before access, and update to Redis (you can access the cache next time).

Redis mainly supports five kinds of data structures: String: string, Hash: hash, List: list, Set: collection, Sorted Set: ordered collection. I like Redis very much because these data structures are really similar to the data containers of Python programming language.

Next, I'll use a real-life article website to demonstrate how to use Redis to summarize the use of various data structures:

Use Hash to store (ID, title) data for articles

Use String to store the number of visits to each article, which can be counted by 1 at a time

Use List to store the history of each user's access to articles and record them sequentially

Use Set to store a collection of ID for all users who visit a website

Use Sorted Set to store the hot list of websites, and the ranking score is the weight.

Introduction of redis package

If not, you can install it with pip install redis.

Import redis

# create a link redis_conn = redis.Redis (host='192.168.0.119', port=6379)

1. Add a few articles to the website

# using hash, similar to map form # Storage (Id, title) data for idx in range (101106): title = f "this is {idx} article title" redis_conn.hset ("articles", str (idx), title)

two。 Show users a list of articles

# Storage in hash, display all article lists in hgetall articles = redis_conn.hgetall ("articles") for id, title in articles.items (): # return bytes type print (id, title) by default

Take a look at the results:

101 this is 101 article title102 this is 102 article title103 this is 103 article title104 this is 104 article title105 this is 105 article title

You can also view a single article:

# display the title of a single article redis_conn.hget ("articles", "105")

The result is:

B'this is 105 article title'

3. When the user accesses the article, the behavior record is generated.

# this function uses many data structures def user_visit (uid, article_id): "produces behavior: uid accesses article_id" # 1. String structure, the number of visits to the article plus 1 redis_conn.incr (f "article_counter_ {article_id}") # 2. List structure Record uid's access list redis_conn.lpush (f "user_visit_ {uid}", str (article_id)) # 3. Set structure, record uid's site-wide collection redis_conn.sadd (f "all_visit_uids", str (uid)) # 4. SortedSet structure, the heat of the article plus 1 redis_conn.zincrby ("article_hots", 1, str (article_id))

Simulate the access of several users:

# simulate the access records of 3 users user_visit ("uid_01", "101") user_visit (" uid_01 "," 102") user_visit ("uid_01", "103")

User_visit ("uid_02",) user_visit ("uid_02",) user_visit ("uid_02", "104")

User_visit ("uid_03", "103") user_visit ("uid_03", "104") user_visit (" uid_03 "," 105")

4. Query the number of visits to the article

Because it is stored in the String structure, it can be directly get.

Redis_conn.get (f "article_counter_104") returns: 2

Redis_conn.get (f "article_counter_105") returns: 1

5. Show a user's access history

Because it is stored in List, you can use lrange paging query

Redis_conn.lrange ("user_visit_uid_01", 0,-1) returns: [baked 103, baked 102, baked 101']

Redis_conn.lrange ("user_visit_uid_03", 0,-1) returns the following: [baked 105, bounded 104, baked 103']

6. Show the collection of users who visit the whole site

Because it is stored in Set, you can use smembers to pull out all the content

Redis_conn.smembers ("all_visit_uids") returns: {bounded uiddly 01percent, bounded uiddly 02percent, bounded uiddly 03'}

7. Show the hot list and popularity of articles.

Redis_conn.zrange ("article_hots", 0,-1, withscores=True, desc=True) returns the following, which is actually the ID and heat value of each article: [(bread103, 3.0), (bread104, 2.0), (bread102, 2.0), (bread105, 1.0), (bread101, 1.0)]

The above is a summary of my operation of Redis using Python. String/list/set/hash is used more and sorted set is less, but it is convenient to use sorted set when you encounter scenarios such as hot lists and weighted lists.

The code is in github:

Https://github.com/peiss/ant-learn-python

After reading the above, do you have any further understanding of how to operate the Redis library in Python? If you want to know more knowledge or related content, please follow the industry information channel, thank you for your support.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report