Redis is an open-source non-relational database. it is written in C language and is a key-value storage system. it stores many value types, including string, list ), set, zset, and hash how to operate Redis using Python? The following example describes how to read and write Redis databases using Python.
For example, we insert a data record as follows:
The code is as follows:
Import redis
Class Database:
Def _ init _ (self ):
Self. host = 'localhost'
Self. port = 6379
Def write (self, website, city, year, month, day, deal_number ):
Try:
Key = '_'. join ([website, city, str (year), str (month), str (day)])
Val = deal_number
R = redis. StrictRedis (host = self. host, port = self. port)
R. set (key, val)
Failed T Exception, exception:
Print exception
Def read (self, website, city, year, month, day ):
Try:
Key = '_'. join ([website, city, str (year), str (month), str (day)])
R = redis. StrictRedis (host = self. host, port = self. port)
Value = r. get (key)
Print value
Return value
Failed T Exception, exception:
Print exception
If _ name _ = '_ main __':
Db = Database ()
Db. write ('meituany', 'Beijing)
Db. read ('meituany', 'Beijing', 1)
The above Operation writes a piece of data first and then reads it. if too much data is written or read, we 'd better use batch processing to improve efficiency.
The code is as follows:
Import redis
Import datetime
Class Database:
Def _ init _ (self ):
Self. host = 'localhost'
Self. port = 6379
Self. write_pool = {}
Def add_write (self, website, city, year, month, day, deal_number ):
Key = '_'. join ([website, city, str (year), str (month), str (day)])
Val = deal_number
Self. write_pool [key] = val
Def batch_write (self ):
Try:
R = redis. StrictRedis (host = self. host, port = self. port)
R. mset (self. write_pool)
Failed T Exception, exception:
Print exception
Def add_data ():
Beg = datetime. datetime. now ()
Db = Database ()
For I in range (1,10000 ):
Db. add_write ('meituany', 'Beijing', 2013, I, 1, I)
Db. batch_write ()
End = datetime. datetime. now ()
Print end-beg
If _ name _ = '_ main __':
Add_data ()