current position:Home>Python connects redis, singleton and thread pool, and resolves problems encountered
Python connects redis, singleton and thread pool, and resolves problems encountered
2022-01-31 17:42:16 【Coriander Chat Game】
「 This is my participation 11 The fourth of the yuegengwen challenge 7 God , Check out the activity details :2021 One last more challenge 」
I'm going to do a small project recently , The final solution of the project is flask + redis, So you need to connect redis
1、 demand
Want to use redis, In normal development , Generally we use thread pool , The multithreading library will also be used later , The stored object is a string , At this time, you need to serialize the object ,
Directly used redis The built-in json serialize
2、demo
The details of the project will not be mentioned , Because I haven't used it before python Operation on Database , So first write a demo test , attempt to connect redis
We all know that doing database operations , It is better to use connection pool , This reduces the cost of connection , Reduce operation time at high concurrency , At the same time, I want to make a single example in the process of using the program , After looking at various single cases, I choose the simplest way , For one demo Enough is enough .
To sum up : Single case , Thread pool
install redis I won't go into that , Baidu is everywhere .
I don't say much nonsense , Go straight to code
Directly on the console pip install redis That's all right.
Look at the connection pool code :
import redis
class RedisPool:
instance = None
def __init__(self):
self.pool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True, db=8)
def __getConnection(self):
conn = redis.Redis(connection_pool=self.pool)
return conn
@classmethod
def getConn(cls):
if RedisPool.instance is None:
RedisPool.instance = RedisPool()
return RedisPool.instance.__getConnection()
redisConn = RedisPool.getConn()
redisConn.set('aaa', 'vvv')
Copy code
Object turn json Function of
def toStr(obj):
return json.dumps(obj,default = lambda x: x.__dict__,ensure_ascii=False)
Copy code
Simply define an object
class RankData:
def __init__(self):
self.data = []
Call store in redis
from gameRank import RedisPool
from gameRank.JsonUtil import toStr
from gameRank.RankData import RankData
rank = RankData()
rank.data.append({' name ':' Coriander ','code':'12345'})
rank.data.append({' name ':' Coriander ','code':'12345'})
rank.data.append({' name ':' Coriander ','code':'12345'})
rank.data.append({' name ':' Coriander ','code':'12345'})
rank.data.append({' name ':' Coriander ','code':'12345'})
rank.data.append({' name ':' Coriander ','code':'12345'})
rank.data.append({' name ':' Coriander ','code':'12345'})
rank.data.append({' name ':' Coriander ','code':'12345'})
rank.data.append({' name ':' Coriander ','code':'12345'})
redisConn = RedisPool.getConn()
redisConn.hset('20211115','aaa', toStr(rank))
Copy code
3、 Problems encountered
3.1 solve Object of type “XXX“ is not JSON serializable terms of settlement
error : Unable to serialize
stay Java There are all kinds of json library , It's used here python Self contained json, But I didn't notice that the custom object can't be serialized , Just add the following line
default = lambda x: x.dict,
3.2 redis Shown in is binary
Show not chinese , It's generating json The statement of add
ensure_ascii=False
4、 summary
It's not hard to , Just copy mechanically , Comments are welcome on thumb up ,
copyright notice
author[Coriander Chat Game],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/01/202201311742154184.html
The sidebar is recommended
- Python - convert Matplotlib image to numpy Array or PIL Image
- Python and Java crawl personal blog information and export it to excel
- Using class decorators in Python
- Untested Python code is not far from crashing
- Python efficient derivation (8)
- Python requests Library
- leetcode 2047. Number of Valid Words in a Sentence(python)
- leetcode 2027. Minimum Moves to Convert String(python)
- How IOS developers learn Python Programming 5 - data types 2
- leetcode 1971. Find if Path Exists in Graph(python)
guess what you like
-
leetcode 1984. Minimum Difference Between Highest and Lowest of K Scores(python)
-
Python interface automation test framework (basic) -- basic syntax
-
Detailed explanation of Python derivation
-
Python reptile lesson 2-9 Chinese monster database. It is found that there is a classification of color (he) desire (Xie) monsters during operation
-
A brief note on the method of creating Python virtual environment in Intranet Environment
-
[worth collecting] for Python beginners, sort out the common errors of beginners + Python Mini applet! (code attached)
-
[Python souvenir book] two people in one room have three meals and four seasons: 'how many years is it only XX years away from a hundred years of good marriage' ~?? Just come in and have a look.
-
The unknown side of Python functions
-
Python based interface automation test project, complete actual project, with source code sharing
-
A python artifact handles automatic chart color matching
Random recommended
- Python crawls the map of Gaode and the weather conditions of each city
- leetcode 1275. Find Winner on a Tic Tac Toe Game(python)
- leetcode 2016. Maximum Difference Between Increasing Elements(python)
- Run through Python date and time processing (Part 2)
- Application of urllib package in Python
- Django API Version (II)
- Python utility module playsound
- Database addition, deletion, modification and query of Python Sqlalchemy basic operation
- Tiobe November programming language ranking: Python surpasses C language to become the first! PHP is about to fall out of the top ten?
- Learn how to use opencv and python to realize face recognition!
- Using OpenCV and python to identify credit card numbers
- Principle of Python Apriori algorithm (11)
- Python AI steals your voice in 5 seconds
- A glance at Python's file processing (Part 1)
- Python cloud cat
- Python crawler actual combat, pyecharts module, python data analysis tells you which goods are popular on free fish~
- Using pandas to implement SQL group_ concat
- How IOS developers learn Python Programming 8 - set type 3
- windows10+apache2. 4 + Django deployment
- Django parser
- leetcode 1560. Most Visited Sector in a Circular Track(python)
- leetcode 1995. Count Special Quadruplets(python)
- How to program based on interfaces using Python
- leetcode 1286. Iterator for Combination(python)
- leetcode 1418. Display Table of Food Orders in a Restaurant (python)
- Python Matplotlib drawing histogram
- Python development foundation summary (VII) database + FTP + character coding + source code security
- Python modular package management and import mechanism
- Django serialization (II)
- Python dataloader error "dataloader worker (PID XXX) is killed by signal" solution
- apache2. 4 + Django + windows 10 Automated Deployment
- leetcode 1222. Queens That Can Attack the King(python)
- leetcode 1387. Sort Integers by The Power Value (python)
- Tiger sniffing 24-hour praise device, a case with a crawler skill, python crawler lesson 7-9
- Python object oriented programming 01: introduction classes and objects
- Baidu Post: high definition Python
- Python Matplotlib drawing contour map
- Python crawler actual combat, requests module, python realizes IMDB movie top data visualization
- Python classic: explain programming and development from simple to deep and step by step
- Python implements URL availability monitoring and instant push