解决redis与Python交互取出来的是bytes类型的问题

所属分类: 脚本专栏 / python 阅读数: 1364
收藏 0 赞 0 分享

基本代码

from redis import *

if __name__ == '__main__':
 sr = StrictRedis(host='localhost', port=6379, db=0)
 result=sr.set('name','python')
 print(result)

 result1 = sr.get('name')
 print(result1)

运行结果:

True

b'python'

这里我们存进去的是字符串类型的数据,取出来却是字节类型的,这是由于python3的与redis交互的驱动的问题,Python2取出来的就是字符串类型的。

为了得到字符串类型的数据,你可以每次取出来decode一下,但是太繁琐了,可以这样设置:

sr = StrictRedis(host='localhost', port=6379, db=0,decode_responses=True)

即在连接数据库的时候加上decode_responses=True即可

补充知识:python读并写入redis 使用pipline管道

日常开发中,我们总是需要将一些文件写入到缓存中。而读文件较快的方式就是python了,另外python提供了非常好用的api帮助我们连接redis。本例中将会用rediscluster包来连接redis集群,并使用pipeline管道插入文件

# encoding: utf-8
from rediscluster import StrictRedisCluster
import sys
import os
import datetime

# redis_nodes = [{"host": "10.80.23.175", "port": 7000},
#    {"host": "10.80.23.175", "port": 7001},
#    {"host": "10.80.24.175", "port": 7000},
#    {"host": "10.80.24.175", "port": 7001},
#    {"host": "10.80.25.175", "port": 7000},
#    {"host": "10.80.25.175", "port": 7001}
#    ]

def redis_cluster():
 
 redis_nodes = [{"host": "10.80.23.175", "port": 7000},
     {"host": "10.80.23.175", "port": 7001},
     {"host": "10.80.24.175", "port": 7000},
     {"host": "10.80.24.175", "port": 7001},
     {"host": "10.80.25.175", "port": 7000},
     {"host": "10.80.25.175", "port": 7001}
     ]
 try:
  redisconn = StrictRedisCluster(startup_nodes=redis_nodes,
          skip_full_coverage_check=True)
  return redisconn
 except Exception as e:
  print("Connect Error!")
  sys.exit(1)

def to_redis(redis_conn1, file_name):
 # file_name = "D:\data\logs\hippo.log"
 pipe = redis_conn1.pipeline()
 # pos = []
 index = 0
 count = 0
 with open(file_name, 'r') as file_to_read:
  while True:
   lines = file_to_read.readline()
   lines = lines.replace("\n", "")
   if not lines:
    break
    pass
   s = lines.split("\t")
   value = s[1]
   key = s[0]
   result = pipe.lpush(key, value)
   # print(file_name + s)
   index = index + 1
   if index > 5000:
    pipe.execute()
    index = 0
    count = count + 1
    print("execute insert! count is %d" % count)
   pass
  pass
 pipe.execute()

def read_file(path):
 if os.path.isfile(path):
  print("start execute file %s" % path)
  to_redis(path)
 else:
  for root, dirs, files in os.walk(path):
   # print('root_dir:', root) # 当前目录路径
   # print('sub_dirs:', dirs) # 当前路径下所有子目录
   print('files:', files) # 当前路径下所有非目录子文件
   for fileName in files:
    all_name = root + "/" + fileName
    print("start execute file %s" % all_name)
    to_redis(redis_conn, all_name)

start_time = datetime.datetime.now()
redis_conn = redis_cluster()

file_paths = sys.argv[1]
# 第一个参数是本文件 故去掉
#file_paths.pop[0]
#for file_name in file_paths:
#print(file_paths)
read_file(file_paths)
end_time = datetime.datetime.now()
print("use times is %d " % (end_time - start_time).seconds)

在使用的时候需要将要插入的文件以参数形式传入到命令中

例如,将 /data/a.log 插入到redis中

python RedisFIleToRedis.py /data/a.log

以上这篇解决redis与Python交互取出来的是bytes类型的问题就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。

更多精彩内容其他人还在看

python2.7无法使用pip的解决方法(安装easy_install)

下面小编就为大家分享一篇python2.7无法使用pip的解决方法(安装easy_install),具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
收藏 0 赞 0 分享

Python实现的计算马氏距离算法示例

这篇文章主要介绍了Python实现的计算马氏距离算法,简单说明了马氏距离算法原理,并结合实例形式分析了Python实现与使用马氏距离算法的相关操作技巧,需要的朋友可以参考下
收藏 0 赞 0 分享

python逐行读写txt文件的实例讲解

下面小编就为大家分享一篇python逐行读写txt文件的实例讲解,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
收藏 0 赞 0 分享

python批量读取txt文件为DataFrame的方法

下面小编就为大家分享一篇python批量读取txt文件为DataFrame的方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
收藏 0 赞 0 分享

Python通过调用mysql存储过程实现更新数据功能示例

这篇文章主要介绍了Python通过调用mysql存储过程实现更新数据功能,结合实例形式分析了Python调用mysql存储过程实现更新数据的具体步骤与相关操作技巧,需要的朋友可以参考下
收藏 0 赞 0 分享

Python实现的HMacMD5加密算法示例

这篇文章主要介绍了Python实现的HMacMD5加密算法,简单说明了HMAC-MD5加密算法的概念、原理并结合实例形式分析了Python实现HMAC-MD5加密算法的相关操作技巧,,末尾还附带了Java实现HMAC-MD5加密算法的示例,需要的朋友可以参考下
收藏 0 赞 0 分享

图解Python变量与赋值

Python是一门独特的语言,与C语言有很大区别,初学Python很多萌新表示对变量与赋值不理解,这里就大家介绍一下,需要的朋友可以参考下
收藏 0 赞 0 分享

Python中的并发处理之asyncio包使用的详解

本篇文章主要介绍了Python中的并发处理之asyncio包使用的详解,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
收藏 0 赞 0 分享

Python获取二维矩阵每列最大值的方法

下面小编就为大家分享一篇Python获取二维矩阵每列最大值的方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
收藏 0 赞 0 分享

numpy找出array中的最大值,最小值实例

下面小编就为大家分享一篇numpy找出array中的最大值,最小值实例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
收藏 0 赞 0 分享
查看更多