Python读写Redis数据库操作示例

yipeiwu_com5年前Python基础
使用Python如何操作Redis呢?下面用实例来说明用Python读写Redis数据库。
比如,我们插入一条数据,如下:
复制代码 代码如下:
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) 

上面操作是先写入一条数据,然后再读取,如果写入或者读取数据太多,那么我们最好用批处理,这样效率会更高。
复制代码 代码如下:
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() 

相关文章

python使用xslt提取网页数据的方法

python使用xslt提取网页数据的方法

1、引言 在Python网络爬虫内容提取器一文我们详细讲解了核心部件:可插拔的内容提取器类gsExtractor。本文记录了确定gsExtractor的技术路线过程中所做的编程实验。这是...

python调用shell的方法

1.1  os.system(command)在一个子shell中运行command命令,并返回command命令执行完毕后的退出状态。这实际上是使用C标准库函数system(...

python3读取图片并灰度化图片的四种方法(OpenCV、PIL.Image、TensorFlow方法)总结

python3读取图片并灰度化图片的四种方法(OpenCV、PIL.Image、TensorFlow方法)总结

在处理图像的时候经常是读取图片以后把图片转换为灰度图。作为一个刚入坑的小白,我在这篇博客记录了四种处理的方法。 首先导入包: import numpy as np import cv...

Python使用正则表达式实现文本替换的方法

本文实例讲述了Python使用正则表达式实现文本替换的方法。分享给大家供大家参考,具体如下: 2D客户端编程从某种意义上来讲就是素材组织,所以,图片素材组织经常需要批量处理,python...

分享给Python新手们的几道简单练习题

前言 本文主要给大家分享了一些简单的Python练习题,对学习python的新手们来说是个不错的练习问题,下面话不多说了,来一起看看详细的介绍吧。 第一题:使用while循环输入 1 2...