search
HomeBackend DevelopmentPython TutorialPython connection Redis connection configuration
Python connection Redis connection configurationOct 18, 2016 am 11:47 AM
pythonredisConfiguration

System environment:

OS: Oracle Linux Enterprise 5.6

redis: redis-2.6.8

python: Python-2.7.3

redis’ python package version: redis-2.7.2.tar


Prerequisites:

1. Make sure that Redis has been successfully installed and configured correctly, refer to the document

2. Make sure that the Python environment has been successfully configured, refer to the document

Configure python connection redis:

1. Install the Python package of Redis:

Use easy-install to install. For the configuration of easy-install, refer to the above Python environment setup.

[root@njdyw bin]# easy_install2.7.3 redis

Searching for redis

Reading http://pypi.python.org/simple/redis/

Reading http://github.com/andymccurdy/redis- py

Best match: redis 2.7.2

Downloading http://pypi.python.org/packages/source/r/redis/redis-2.7.2.tar.gz#md5=17ac60dcf13eb33f82cc25974ab17157

Processing redis-2.7 .2.tar.gz

Running redis-2.7.2/setup.py -q bdist_egg --dist-dir /tmp/easy_install-8FAlft/redis-2.7.2/egg-dist-tmp-JzQViJ

zip_safe flag not set; analyzing archive contents...

Adding redis 2.7.2 to easy-install.pth file


Installed /usr/local/python2.7.3/lib/python2.7/site-packages/redis- 2.7.2-py2.7.egg

Processing dependencies for redis

Finished processing dependencies for redis


--Install Parser package (optional)

Description: Parser can control how to parse the content of redis response. redis-py contains two Parser classes, PythonParser and HiredisParser. By default, redis-py will use HiredisParser if the hiredis module is installed, otherwise it will use PythonParser.

HiredisParser is written in C and maintained by the redis core team. Its performance is more than 10 times higher than PythonParser, so it is recommended to use it. Installation method, use easy_install:

[root@njdyw ~]# easy_install2.7.3 hiredis

Searching for hiredis

Reading http://pypi.python.org/simple/hiredis/

Reading https://github. com/pietern/hiredis-py

Best match: hiredis 0.1.1

Downloading http://pypi.python.org/packages/source/h/hiredis/hiredis-0.1.1.tar.gz#md5=92128474f6fb027cfb8587fce724ea8e

Processing hiredis-0.1.1.tar.gz

Running hiredis-0.1.1/setup.py -q bdist_egg --dist-dir /tmp/easy_install-ZanSCB/hiredis-0.1.1/egg-dist-tmp -XCZBQ0

zip_safe flag not set; analyzing archive contents...

Adding hiredis 0.1.1 to easy-install.pth file


Installed /usr/local/python2.7.3/lib/python2.7/ site-packages/hiredis-0.1.1-py2.7-linux-x86_64.egg

Processing dependencies for hiredis

Finished processing dependencies for hiredis


2. Check whether the installation is successful

--easy-install The installed extension package is in the site-packages directory of python by default

[root@njdyw ~]#whereis python2.7.3

python2.7: /bin/python2.7.3 /usr/local/python2.7.3

[root @njdyw ~]#cd /usr/local/python2.7.3/lib/python2.7/site-packages/

[root@njdyw site-packages]# ll

Total 408

-rw-r--r -- 1 root root 239 03-21 10:45 easy-install.pth

-rw-r--r-- 1 root root 119 03-21 10:07 README

-rw-r--r-- 1 root root 60401 03-21 10:45redis-2.7.2-py2.7.egg

-rw-r--r-- 1 root root 332125 03-21 10:12 setuptools-0.6c11-py2.7. egg

-rw-r--r-- 1 root root 30 03-21 10:12 setuptools.pth


You can see that the redis-2.7.2-py2.7.egg package has been successfully installed


3. Test the connection

[root@njdyw site-packages]#python2.7.3

Python 2.7.3 (default, Mar 21 2013, 10:06:48)

[GCC 4.1.2 20080704 (Red Hat 4.1.2-50)] on linux2

Type "help", "copyright", "credits" or "license" for more information.

>>>import redis

>>>redisClient=redis.StrictRedis( host='127.0.0.1',port=6379,db=0)

>>> redisClient.set('test_redis','Hello Python')

True

>>> value=redisClient.get('test_redis ')

>>> print value

Hello Python

>>> redisClient.delete('test_redis')

True

>>> value=redisClient.get('test_redis')

>>> print value

None



>>> dir(redis)

['AuthenticationError', 'Connection', 'ConnectionError', 'ConnectionPool', 'DataError', 'InvalidResponse', 'PubSubError', 'Redis', 'RedisError', 'ResponseError', 'StrictRedis', 'UnixDomainSocketConnection', 'VERSION', 'WatchError', '__all__', '__builtins__', '__doc__', '__file__', '__loader__', '__name__ ', '__package__', '__path__', '__version__', '_compat', 'client', 'connection', 'exceptions', 'from_url', 'utils']

>>> redisClient=redis.StrictRedis(host ='127.0.0.1',port=6379,db=0)

>>> dir(redisClient)

['RESPONSE_CALLBACKS', '__class__', '__contains__', '__delattr__', '__delitem__', '__dict__', '__doc__', '__format__', '__getattribute__', '__getitem__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_zaggregate', 'append', 'bgrewriteaof', 'bgsave', 'bitcount', 'bitop', 'blpop', 'brpop', 'brpoplpush', 'client_kill', 'client_list', 'config_get', 'config_set', 'connection_pool', 'dbsize', 'debug_object', 'decr', 'delete', 'echo', 'eval', 'evalsha', 'execute_command', 'exists', 'expire', 'expireat', 'flushall', 'flushdb', 'from_url', 'get', 'getbit', 'getrange', 'getset', 'hdel', 'hexists', 'hget', 'hgetall', 'hincrby', 'hincrbyfloat', 'hkeys', 'hlen', 'hmget', 'hmset', 'hset', 'hsetnx', 'hvals', 'incr', 'incrbyfloat', 'info', 'keys', 'lastsave', 'lindex', 'linsert', 'llen', 'lock', 'lpop', 'lpush', 'lpushx', 'lrange', 'lrem', 'lset', 'ltrim', 'mget', 'move', 'mset', 'msetnx', 'object', 'parse_response', 'persist', 'pexpire', 'pexpireat', 'ping', 'pipeline', 'pttl', 'publish', 'pubsub', 'randomkey', 'register_script', 'rename', 'renamenx', 'response_callbacks', 'rpop', 'rpoplpush', 'rpush', 'rpushx', 'sadd', 'save', 'scard', 'script_exists', 'script_flush', 'script_kill', 'script_load', 'sdiff', 'sdiffstore', 'set', 'set_response_callback', 'setbit', 'setex', 'setnx', 'setrange', 'shutdown', 'sinter', 'sinterstore', 'sismember', 'slaveof', 'smembers', 'smove', 'sort', 'spop', 'srandmember', 'srem', 'strlen', 'substr', 'sunion', 'sunionstore', 'time', 'transaction', 'ttl', 'type', 'unwatch', 'watch', 'zadd', 'zcard', 'zcount', 'zincrby', 'zinterstore', 'zrange', 'zrangebyscore', 'zrank', 'zrem', 'zremrangebyrank', 'zremrangebyscore', 'zrevrange', 'zrevrangebyscore', 'zrevrank', 'zscore', 'zunionstore']

>>>


4.测试实例:

(1).把文本数据导入到redis

--导入的数据格式

[root@njdyw ~]#more data.txt

wolys # wolysopen111 # wolys@21cn.com

coralshanshan # 601601601 # zss1984@126.com

pengfeihuchao # woaidami # 294522652@qq.com

simulategirl # @#$9608125 # simulateboy@163.com

daisypp # 12345678 # zhoushigang_123@163.com

sirenxing424 # tfiloveyou # sirenxing424@126.com

raininglxy # 1901061139 # lixinyu23@qq.com

leochenlei # leichenlei # chenlei1201@gmail.com

z370433835 # lkp145566 # 370433835@qq.com


--创建命令脚本

[root@njdyw ~]#cat imp_red.py

import redis

import re

pool = redis.ConnectionPool(host='127.0.0.1', port=6379)

r = redis.Redis(connection_pool=pool)

pipe = r.pipeline()

p=re.compile(r'(.*)s#s(.*)s#s(.*)');

pipe = r.pipeline()

f = open("data.txt")

matchs=p.findall(f.read())

for user in matchs:

  key='users_%s' %user[0].strip()

  pipe.hset(key,'pwd',user[1].strip()).hset(key,'email',user[2].strip())

pipe.execute()

f.close()


注意:要严格控制python脚本中的空格

--执行脚本

[root@njdyw ~]# python2.7.3 imp_red.py


--查看导入数据

[root@njdyw ~]#redis-cli

redis 127.0.0.1:6379> keys *

1) "users_xiaochuan2018"

2) "users_coralshanshan"

3) "users_xiazai200901"

4) "users_daisypp"

5) "users_boiny"

6) "users_raininglxy"

7) "users_fennal"

8) "users_abc654468252"

9) "users_babylovebooks"

10) "users_xl200811"

11) "users_baby19881018"

12) "users_darksoul0929"

13) "users_pengcfwxh"

14) "users_alex126126"

15) "users_jiongjiongmao"

16) "users_sirenxing424"

17) "users_mengjie007"

18) "users_cxx0409"

19) "users_candly8509"

20) "users_licaijun007"

21) "users_ai3Min2"

22) "users_bokil"

23) "users_z370433835"

24) "users_yiling1007"

25) "users_simulategirl"

26) "users_fxh852"

27) "users_baoautumn"

28) "users_huangdaqiao"

29) "users_q1718334567"

30) "users_xldq_l"

31) "users_beibeilong012"

32) "users_hudaoyin"

33) "users_yoyomika"

34) "users_jacksbalu"

35) "users_wolys"

36) "users_kangte1"

37) "users_demonhaodh"

38) "users_ysdz8"

39) "users_leochenlei"

40) "users_llx6888"

41) "users_pengfeihuchao"

redis 127.0.0.1:6379>

redis 127.0.0.1:6379>hget users_pengfeihuchao email

"294522652@qq.com"

redis 127.0.0.1:6379> hget users_llx6888 email

"linlixian200606@126.com"


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
详细讲解Python之Seaborn(数据可视化)详细讲解Python之Seaborn(数据可视化)Apr 21, 2022 pm 06:08 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于Seaborn的相关问题,包括了数据可视化处理的散点图、折线图、条形图等等内容,下面一起来看一下,希望对大家有帮助。

详细了解Python进程池与进程锁详细了解Python进程池与进程锁May 10, 2022 pm 06:11 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于进程池与进程锁的相关问题,包括进程池的创建模块,进程池函数等等内容,下面一起来看一下,希望对大家有帮助。

Python自动化实践之筛选简历Python自动化实践之筛选简历Jun 07, 2022 pm 06:59 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于简历筛选的相关问题,包括了定义 ReadDoc 类用以读取 word 文件以及定义 search_word 函数用以筛选的相关内容,下面一起来看一下,希望对大家有帮助。

归纳总结Python标准库归纳总结Python标准库May 03, 2022 am 09:00 AM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于标准库总结的相关问题,下面一起来看一下,希望对大家有帮助。

Python数据类型详解之字符串、数字Python数据类型详解之字符串、数字Apr 27, 2022 pm 07:27 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于数据类型之字符串、数字的相关问题,下面一起来看一下,希望对大家有帮助。

分享10款高效的VSCode插件,总有一款能够惊艳到你!!分享10款高效的VSCode插件,总有一款能够惊艳到你!!Mar 09, 2021 am 10:15 AM

VS Code的确是一款非常热门、有强大用户基础的一款开发工具。本文给大家介绍一下10款高效、好用的插件,能够让原本单薄的VS Code如虎添翼,开发效率顿时提升到一个新的阶段。

详细介绍python的numpy模块详细介绍python的numpy模块May 19, 2022 am 11:43 AM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于numpy模块的相关问题,Numpy是Numerical Python extensions的缩写,字面意思是Python数值计算扩展,下面一起来看一下,希望对大家有帮助。

python中文是什么意思python中文是什么意思Jun 24, 2019 pm 02:22 PM

pythn的中文意思是巨蟒、蟒蛇。1989年圣诞节期间,Guido van Rossum在家闲的没事干,为了跟朋友庆祝圣诞节,决定发明一种全新的脚本语言。他很喜欢一个肥皂剧叫Monty Python,所以便把这门语言叫做python。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),