Using Python for Redis operations

Source: Internet
Author: User
Tags connection pooling install redis

Write in front

First of all, this is to learn Python on the redis operation of a small demo, including some of these days the site found some information, summed up a few things, and finally attached I wrote a python operation Redis Demo:

Module installation

Python provides a module redis-py to make it easy for us to operate the Redis database, and the installation of the module is simple, using PIP to install the line, the command is as follows:

Pip Install Redis

After the installation, use the import call to know if the installation is successful, in the Python interface to enter the import Redis, if not error, then the module even if the installation is successful.

Once the module is successfully installed, you can create a Redis connection and then learn how to create a Redis connection:

Redis-py provides two classes of Redis and Strictredis for implementing Redis commands, Strictredis is used to implement most of the official commands, and uses the official syntax and commands (for example, the SET command corresponds to the Strictredis.set method). Redis is a subclass of Strictredis for backwards compatibility with older versions of Redis-py. Simply put, the official recommendation is to use the Strictredis method.

The Redis class is not recommended here because he and we are in a different REDIS-CLI operation, the main difference is the following three aspects.

(1) Lrem: The order of the parameters ' num ' and ' value ' is exchanged for a bit, the CLI is lrem queuename 0 ' string '. The 0 here is all the meaning. But the Redis class, the control and the string swapped.

(2) Zadd: When the order of score and value was realized, it was accidentally reversed, and then someone used it.

(3) The order of Setex:time and value is reversed.

We can use Strictredis to connect directly to Redis with the following code:

#创建一个redis连接r =redis. Strictredis (host= ' 192.168.7.25 ', port=6379,db=0)

Use of connection pooling

However, for a large number of redis connections, if you use a direct connection to Redis, it will cause a large number of TCP duplicate connections, so it is recommended to use a connection pool to solve this problem, after using a connection pool connection to Redis, you can generate connections from the connection pool, after the call is completed, The link will be returned to the connection pool for other connection requests to be invoked, which will reduce the execution time of a large number of redis connections, and the following are the implementations of the two Redis and Strictredis connection pools:

Method for Redis connection pooling: Pool = redis. ConnectionPool (host= ' 127.0.0.1 ',  port=6379, db=0) R = redis. How the connection pool for Redis (Connection_pool=pool) Strictredis is implemented: Pool = redis. ConnectionPool (host= ' 127.0.0.1 ',  port=6379, db=0) R = redis. Strictredis (Connection_pool=pool) The official Redis connection pool can be added with parameters:  class redis. Strictredis (host= ' localhost ', port=6379, db=0, password=none, socket_timeout=none,  Connection_pool=none, charset= ' Utf-8 ',  errors= ' strict ',  decode_responses=false, unix_ Socket_path=none) Implementation of the redis protocol. This abstract class provides a python interface to all redis  commands and an implementation of the redis protocol. connection and pipeline derive from this, implementing how the  commands are sent and received to The redis server 

Some small demo

Next, we need to propose several data types for Redis, and when I use Redis clients to connect to Redis, I find that Redis supports five types of keys, and the list is as follows:

String: Stores data of a string, as well as data types such as int or float.

List: Storing data for a list type

Hash: Storing data for a dictionary type

Set: Stores data for a collection type

Zset: The data stored is also collection type, but the data is stored in order (this type is not included in the demo ...). )

Well, once you know the type of data that Redis supports, you can write a little demo, and here are some small demos:

#创建一个string类型的key并放入valuer. Set ("ABC", 34634) #创建一个hashr. Hset (' abc:def ', ' name ', ' ABCDE ') #获取一个hash的所有值print R.hgetall (' abc:def ') #获取一个hash的所有keyprint r.hkeys (' abc:def ') #创建listr. Sadd (' Abcd:ef ', ' Nihao ') r.sadd (' Abcd:ef ', ' Hello ') r.sadd (' xxxx ', ' Nihao ') r.sadd (' xxxx ', ' good ') #打印出该key中的值 listprint r.smembers (' Abcd:ef ') #查询两个list中相同的值print R.sinter (' Abcd:ef ', ' xxxx ') #给两个list取并集print r.sunion (' abcd:ef ', ' xxxx ') #列出所有keyprint R.keys () #列出以abc开头的所有keyprint R.keys ("abc*")

Demo Summary

Since the company has encountered demand, need to batch modify a batch of key value, before using the shell can do, but now by completing this requirement using Python to achieve this small demo bar.

The demo will be accompanied by some of my explanations, I hope the gods do not spit groove ... A long time did not move handwriting python, and then write is a variety of egg pain ...

#!/usr/bin/env python#coding=utf-8import redis     #导入redis-py Module class  redispool:     #定义了一个连接池类, which returns a connection from the connection pool to the caller     def redis_pool (self , clienthost= "192.168.0.25", clientport=6379,clientdb=0):         pool= Redis. ConnectionPool (HOST=CLIENTHOST,PORT=CLIENTPORT,DB=CLIENTDB)          Return redis. Strictredis (connection_pool=pool) class changekey:  #该类使用获取到的redis连接对想要进行修改的key进行修改          def change_string (Self,r,key,value):           try:            Bool  = r.set (key,value)         except exception as e:             Bool = False             print  ' Insert string error: ',e         return Bool        def  Change_list (Self,r,keyname,key):        filed_list=[]         for i in range (0,len (Key)):             try:                 r.rpush (Keyname,key[i])              except Exception as e:                 filed_list.append ((keyname,key[i))                  print  ' Insert set error : ', e    &Nbsp;   return filed_list        def change_ Hash (Self,r,keyname,key):        filed_list=[]         for i in key.keys ():             try:                 r.hset (Keyname,i,key[i])              except Exception as e:                 filed_list.append ([i,key[i]])                  print  ' Insert set error: ',e         return Filed_List        def  Change_set (self,r,keyname,kEY):        filed_list=[]         newkey=list (Key)         for i in range (0,len ( NewKey)):            try:                         r.sadd (Keyname,newkey[i])             except  Exception as e:                 filed_list.append (Keyname,newkey[i])                  print  ' Insert set error: ',e         return filed_list        def change_ Key (Self,r,keys):  &NBsp;   #通过传递进来的Keys判断其值是属于哪种类型 to invoke the Insert function of a different key to insert the key into Redis          for i in keys:            if  isinstance (Keys[i], (Str,int,float,long)):                 print  "the key %s type is string,will  Input new value: " % (i)                  bool = self. Change_string (R,i,keys[i])                  if Bool:                     print  "update is ok,the key:%s new value:%s"  % (I,keys[i])           &NBsp;     else:                     print  "Update is filed,the filed key  %s value %s " % (i,keys[i))                  elif isinstance (keys[i],list):                 print  "The key %s type is  list,will input new value: " % (str (i))                  filed_list = self. Change_list (R,i,keys[i])                  if len (filed_list)  == 0:                     print  "update is ok,the key:%s new value:%s"  % (I,Keys[i])                  else:                      print  "update is filed,the filed list is %s"  % (Filed_List)              elif isinstance (Keys[i],dict):                 print  "The key  %s type is hash,will input new value: " % (str (i))                  filed_list = self. Change_hash (R,i,keys[i])                  if len (Filed_lisT)  == 0:                     print  "update is ok,the key:%s new value:%s"   % (I,keys[i])                  else:                     print  "update is filed,the filed list is %s"  % (Filed _list)             elif isinstance (Keys[i],set ):                print  " The key %s type is set,will input new value: " % (str (i))                  filed_list =  self. Change_set (R,I,keys[i])                 if  len (filed_list)  == 0:                     print  "Update is ok,the key:%s new  value:%s " % (i,keys[i))                  else:                     print  "update is filed,the filed list  is %s " % (filed_list)             else:                 print  " The key %s not match that support type. The support type:string,list,hash,set. "  % (i) class&nbsp Batchchangekey:    def batch_change_key (Self,r,keys,value):         for i in r.keys (keys):             self. Changekey=changekey ()             self. Changekey.change_key (R,{i:value})      def main ():       pool=redispool ()      #调用连接池类       r=pool.redis_pool (" 192.168.0.25 ", 6379,0)      #获取该连接池中的一个连接      #keys ={' m ': ' Huxianglin ', ' e ': [All-in-all], ' C ': {' z ': ' A ', ' C ': ' B '}, ' Abc:def:ghi ': Set (["A", "B", "C"])}       #changekey = ChangeKey ()      #使用上面定义的Keys传递给该类, the keys passed are required to be a dictionary type of data       # ChangeKey. Change_key (R,keys)     batchchangekey=batchchangekey ()      #调用批量修改的类 and pass in a part of the key that needs to be modified by R.keys (key) to get a list of the keys that can be matched, then traverse the list and pass value in      Batchchangekey. Batch_change_key (R, "abc:defg:*"  ,  "HelloWorld") if __name__ ==  ' __main__ ':     main ()


This article is from the "Lemon" blog, be sure to keep this source http://xianglinhu.blog.51cto.com/5787032/1762354

Using Python for Redis operations

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.