Redis and Pytnon interact

  • Install mysql module
sudo pip install redis
  • Install using source code
unzip redis-py-master.zip
cd redis-py-master
sudo python setup.py install
  • Import module
import redis
  • Connect
try:
    r=redis.StrictRedis(host='localhost',port=6379)
except Exception,e:
    print e.message
  • Method 1: according to different data types, call corresponding methods to complete reading and writing
r.set('name','hello')
r.get('name')
  • Mode 2: Pipeline
  • Buffer multiple commands and execute them at one time, reduce TCP database packets between server and client, and improve efficiency
pipe = r.pipeline()
pipe.set('name', 'world')
pipe.get('name')
pipe.execute()

encapsulation

  • The connection to the redis server is consistent
  • Here, we encapsulate the reading and writing of string type
import redis
class RedisHelper():
    def __init__(self,host='localhost',port=6379):
        self.__redis = redis.StrictRedis(host, port)
    def get(self,key):
        if self.__redis.exists(key):
            return self.__redis.get(key)
        else:
            return ""
    def set(self,key,value):
        self.__redis.set(key,value)

Instance: user login

#coding=utf-8
# from redis import *
from MysqlHelper import *
from hashlib import sha1
try:
    # redis1=StrictRedis()
    #redis1.set('t2',123)
    #print redis1.get('t2')

    # pip1=redis1.pipeline()
    # pip1.set('t2','abc')
    # pip1.get('t2')
    # pip1.execute()
    # print redis1.get('t3')
    # redis=RedisHelper()
    # print redis.get('t2')

    uname=raw_input("Please enter the user name:")
    upwd=raw_input("Please input a password:")

    s1=sha1()
    s1.update(upwd.encode())
    upwd2=s1.hexdigest()

    redis=RedisHelper()
    upwd3=redis.get(uname)
    if upwd3!=None:
        if upwd2==upwd3:
            print('ok')
        else:
            print('Password error')
    else:
        mysql=MysqlHelper()
        sql='select upwd from users where uname=%s'
        params=[uname]
        result=mysql.fetchone(sql,params)
        if result==None:
            print('user name does not exist')
        elif result[0]==upwd2:
            print('ok')
            redis.set(uname,upwd2)
        else:
            print('Password error')

except Exception as e:
    print(e)

General class: MysqlHelper

#coding=utf-8
import MySQLdb
from redis import *

class MysqlHelper:
    def __init__(self,host='localhost',port=3306,db='test2',user='root',passwd='mysql',charset='utf8'):
        self.conn=MySQLdb.connect(host=host,port=port,db=db,user=user,passwd=passwd,charset=charset)

		#insert
    def insert(self,sql,params):
        return self.__cud(sql,params)

		#modify
    def update(self,sql,params):
        return self.__cud(sql,params)

		#delete
    def delete(self,sql,params):
        return self.__cud(sql,params)

		#query
    def __cud(self,sql,params=[]):
        # try:
        cs1 = self.conn.cursor()
        rows=cs1.execute(sql, params)
        self.conn.commit()
        cs1.close()
        self.conn.close()
        return rows
        # except Exception,e:
        #     print e
        #     self.conn.rollback()

		#single
    def fetchone(self,sql,params=[]):
        # try:
        cs1=self.conn.cursor()
        cs1.execute(sql,params)
        row=cs1.fetchone()
        cs1.close()
        self.conn.close()
        return row
        # except Exception as e:
        #     print(e)

		#Multiple
    def fetchall(self,sql,params):
        # try:
        cs1=self.conn.cursor()
        cs1.execute(sql,params)
        rows=cs1.fetchall()
        cs1.close()
        self.conn.close()

        return rows
        # except Exception as e:
        #     print(e)
class RedisHelper:
    def __init__(self,host='localhost',port=6379):
        self.redis=StrictRedis(host,port)
    def get(self,key):
        return self.redis.get(key)
    def set(self,key,value):
        self.redis.set(key,value)

demo download address: https://download.csdn.net/download/hiphopxiao/10650631

Tags: Redis SQL MySQL sudo

Posted on Mon, 06 Jan 2020 05:17:18 -0800 by dtasman7