How do you manipulate Redis with Python? Here's an example to illustrate using Python to read and write Redis databases.
For example, we insert a piece of data, as follows:
Copy Code code 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)
Except 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
Except Exception, Exception:
Print exception
if __name__ = = ' __main__ ':
db = Database ()
Db.write (' Meituan ', ' Beijing ', 2013,9,1,8000)
Db.read (' Meituan ', ' Beijing ', 2013,9,1)
The above operation is to write a piece of data, and then read, if you write or read too much data, then we'd better use batch processing, which is more efficient.
Copy Code code 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)
Except Exception, Exception:
Print exception
Def add_data ():
Beg = Datetime.datetime.now ()
db = Database ()
For I in Range (1,10000):
Db.add_write (' Meituan ', ' Beijing ', 2013,i,1,i)
Db.batch_write ()
End = Datetime.datetime.now ()
Print End-beg
if __name__ = = ' __main__ ':
Add_data ()