How does one 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:
Copy codeThe 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.
Copy codeThe 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 ()