Python read-write Redis database Operations Example _python

Source: Internet
Author: User
Tags datetime redis
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 ()
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.