ImportRedisclassDatabase:def __init__(self): Self.host='localhost'Self.port= 6379defWrite (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)exceptException, Exception:PrintExceptiondefRead (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)PrintvaluereturnvalueexceptException, Exception:PrintExceptionif __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 before reading, if you write or read too much data, then we better use batch processing, so that the efficiency is higher.
ImportRedisImportdatetimeclassDatabase:def __init__(self): Self.host='localhost'Self.port= 6379Self.write_pool= {} defAdd_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]=ValdefBatch_write (self):Try: R= Redis. Strictredis (host=self.host,port=self.port) R.mset (self.write_pool)exceptException, Exception:PrintExceptiondefadd_data (): Beg=Datetime.datetime.now () DB=Database () forIinchRange (1,10000): Db.add_write ('Meituan','Beijing', 2013,i,1, i) db.batch_write () End=Datetime.datetime.now ()Printend-Begif __name__=='__main__': Add_data ()
Reference article: http://www.jb51.net/article/48212.htm
Python read/write Redis database