搜尋
首頁後端開發Python教學Python連接Redis連線配置

Python連接Redis連線配置

Oct 18, 2016 am 11:47 AM
pythonredis配置

系統環境:

OS:Oracle Linux Enterprise 5.6

redis:redis-2.6.8

python:Python-2.7.3

redis的python包版本:redis-2.7.前提條件:

1.確保Redis已成功安裝並且正確配置,參考文檔

2.確保Python環境已成功配置,參考文檔

配置python連接redis:

1.安裝Redis的Python包:

包:

使用easy-install安裝,關於easy-install的配置,參考以上Python環境的搭建。

[root@njdyw bin]# easy_install2.7.3 redis

Searching for redis

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

Re.com py

Best match: redis 2.7.2

Downloading http://pypi.python.org/packages/source/r/redis/redis-2.7.2.tar.gz#md5=17ac60dcf1333f82cc .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-JzQJJfe flagi not set; analyzing archive contents...

Adding redis 2.7.2 to easy-install.pth file

Installed /usr/local/python2.7.2/python2.7. 2.7.2-py2.7.egg

Processing dependencies for redis

Finished processing dependencies for redis


--安裝Parser包(可選)

說明:Parser可以控制如何解析redis響應的內容。 redis-py包含兩個Parser類,PythonParser和HiredisParser。默認,如果已經安裝了hiredis模組,redis-py會使用HiredisParser,否則會使用PythonParser。

HiredisParser是C編寫的,由redis核心團隊維護,效能要比PythonParser提高10倍以上,所以建議使用。安裝方法,使用easy_install:

[root@njdyw ~]# easy_install2.7.3 hiredis

Searching for hiredis

Reading http://pypi.python.org/simple/hiredis/Re com/pietern/hiredis-py

Best match: hiredis 0.1.1

Downloading http://pypi.python.org/packages/source/h/hiredis/hiredis-0.1.1.tar.gzmdmd5=9212847

Processing hiredis-0.1.1.tar.gz

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

zip_safe flag not set; analyzing archive contents...

Adding hiredis 0.1.1 到 easy-install.pth file

site-packages/hiredis-0.1.1-py2.7-linux-x86_64.egg

Processing dependencies for hiredis

Finished processing dependencies for hiredisc安裝的擴充包預設在python的site-packages目錄下

[root@njdyw ~]#whereis python2.7.3

python2.7: /bin/python2.7.3 /usr/localpython2.7: /bin/python2.7.3 /usr/local/python2.7.333 @njdyw ~]#cd /usr/local/python2.7.3/lib/python2.7/site-packages/

[root@njdyw site-packages]# ll


總計408

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

-rw-r--r-- 1 root root    119 03-21 10:07 README-- 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.py6c1. egg

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

可以看到redis-2.7.2-py2.7.7.2-py2.7.7.2-py2.7.2-py2.7.7.2-py2.7.7.2-py2

3.測試連接

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

Python 2.7.3 (default, Mar 21 2013, 10:06:48)GC Hat 4.1.2-50)] on linux2

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

>>>import redis

ient>>卷host='127.0.0.1',port=6379,db=0)

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

True

>>> value=test

True


>>> value=redis ')

>>> print value

Hello Python

>>> print value

Hello Python

>>> redisClient.delete('test_redis')

True

>>> value=redtestis.get(ctestis.S. value

None

None

>>> dir(redis)

['AuthenticationError', 'Connection', 'Error',, 'Prror', 'Error', ' 'Redis', 'RedisError', 'ResponseError', 'StrictRedis', 'UnixDomainSocketConnection', 'VERSION', 'WatchError', '__all__', '__builtins__', '__doc__', '__file__', '__ ', '__package__', '__path__', '__version__', '_compat', 'client', 'connection', 'exceptions', 'from_url', 'utils']

>>> redisClient=redis.StrictRedis(host

>>> 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__', '__format__', '__hash__' '__reduce_ex__'、'__new__'、'__reduce__'、'__reduce_ex__'、'__repr__'、'__setattr__'、'__setitem__'、'__sizeof__'、'__str__'、'__subclasshook__'、'__weakref__'、'_zaggregate、app__' ', 'bgrewriteaof', 'bgsave', 'bitcount', 'bitop', 'blpop', 'brpop', 'brpoplpush', 'client_kill', 'client_list', 'config_get', 'config_set', 'connection_pool', 'dbsize'、'debug_object'、'decr'、'刪除'、'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', '鎖定', 'lpop', 'lpush', 'lpushx', 'lrange', 'lrem', 'lset', 'ltrim', 'mget', '移動', 'mset', 'msetnx'、'物件'、'parse_response'、'持久'、'pexpire'、'pexpireat'、'ping'、'管道'、'pttl'、'發布'、'pubsub'、'randomkey'、'register_script ', '重新命名', 'renamenx', 'response_callbacks', 'rpop', 'rpoplpush', 'rpush', 'rpushx', 'sadd', '保存', 'scard', 'script_exists', 'script_flush' , 'script_kill'、'script_load'、'sdiff'、'sdiffstore'、'set'、'set_response_callback'、'setbit'、'setex'、'setnx'、'setrange'、'關閉'、'sinter'、' sinterstore '、'sismember'、'slaveof'、'smembers'、'smove'、'排序'、'spop'、'srandmember'、'srem'、'strlen'、'substr'、'sunion'、'sunionstore' , '時間', '交易', 'ttl', '類型', '取消觀看', '觀看', 'zadd', 'zcard', 'zcount', 'zincrby', 'zinterstore', 'zrange', 'zrangebyscore', 'zrank', 'zrem', 'zremrangebyrank', 'zremrangebyscore', 'zrevrange', 'zrevrangebyscore', 'zrevrank', 'zscore', 'zunionstore']

>revrank', 'zscore', 'zunionstore']

> 4.實例測試:

(1).把文字資料匯入redis

--導入的資料格式

[root@njdyw ~]#more data.txt

wocns # wolysopen111 # wowolys@21.com

wocns # wolysopen111 # wowolys@21.com

珊瑚珊珊#601601601#zss1984@126.com

pengfeihuchao#woaidami#294522652@qq.com

simulategirl#@#$9608125#.com ushigang_ 123@16 3.com

sirenxing424 # tfiloveyou #sirenxing424 @126.com

raininglxy #1901061139#lixinyu23@qq.com

leochenlei#leichenleiii3@qq.com

leochenlei#leichenleiii3@qq.com

leochenlei#leichenleiiii3@qq.com

leochenlei#leichenleiiii3@qq.com

leochenlei#leichenleiiialelei120138.com 433835@qq .com


--創建腳本腳本

[ root@njdyw ~]#cat imp_red.py

導入redis

導入re

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

. (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())

對於配對中的使用者:

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

  pipeline.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 ~]# python2.7.3 imp_red.py

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


[root@njdyw ~]#redis-cli

redis 127.0.0.1:6379> 鍵*

1) "users_xiaochuan2018"

1) "users_xiaochuan2018"

2) "201%

4) “用戶_daisypp」

5)「users_boiny」

6)「users_raininglxy」

7)「users_fennal」

8)「users_abc654468252」068252」468252」468252」468252」468252」468252」468252」468252」468252」468252」468252」468252」468252! xl2008 11"

11) 「users_baby19881018」

12)「users_darksoul0929」

13)「users_pengcfwxh」

14)「users_alex126126」

15)「users_jiongjiongmao」

16)「users_sirenxing424」

17)「users_mengjie007」

18)「us」_cers_mengjie007」

18)「us使用者_licaijun007"

21) "users_ai3Min2"

22)“users_bokil”

23)“users_z370433835”

24)“users_yiling1007”

25)“users_simulate” s_baoautumn”

28)「user_黃大橋」

29)「users_q1718334567」

30)「users_xldq_l」

31)「users_beibeilong012」

31)「users_beibeilong012」

32)「3個」

34)“user_jacksbalu”

35)“ user_wolys ”

36)“users_kangte1”

37)“users_demonhaodh”

38)“users_ysdz8”

39)“users_leochenlei” 1)「users_peng飛虎潮」

redis 127.0.0.1: 6379>

redis 127.0.0.1:6379>hget users_pengfeihuchao 郵箱

"294522652@qq.com"

"294522652@qq.com"

"linlixian200606 @126.com”

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
如何使用numpy創建多維數組?如何使用numpy創建多維數組?Apr 29, 2025 am 12:27 AM

使用NumPy創建多維數組可以通過以下步驟實現:1)使用numpy.array()函數創建數組,例如np.array([[1,2,3],[4,5,6]])創建2D數組;2)使用np.zeros(),np.ones(),np.random.random()等函數創建特定值填充的數組;3)理解數組的shape和size屬性,確保子數組長度一致,避免錯誤;4)使用np.reshape()函數改變數組形狀;5)注意內存使用,確保代碼清晰高效。

說明Numpy陣列中'廣播”的概念。說明Numpy陣列中'廣播”的概念。Apr 29, 2025 am 12:23 AM

播放innumpyisamethodtoperformoperationsonArraySofDifferentsHapesbyAutapityallate AligningThem.itSimplifififiesCode,增強可讀性,和Boostsperformance.Shere'shore'showitworks:1)較小的ArraySaraySaraysAraySaraySaraySaraySarePaddedDedWiteWithOnestOmatchDimentions.2)

說明如何在列表,Array.Array和用於數據存儲的Numpy數組之間進行選擇。說明如何在列表,Array.Array和用於數據存儲的Numpy數組之間進行選擇。Apr 29, 2025 am 12:20 AM

forpythondataTastorage,choselistsforflexibilityWithMixedDatatypes,array.ArrayFormeMory-effficityHomogeneousnumericalData,andnumpyArraysForAdvancedNumericalComputing.listsareversareversareversareversArversatilebutlessEbutlesseftlesseftlesseftlessforefforefforefforefforefforefforefforefforefforlargenumerdataSets; arrayoffray.array.array.array.array.array.ersersamiddreddregro

舉一個場景的示例,其中使用Python列表比使用數組更合適。舉一個場景的示例,其中使用Python列表比使用數組更合適。Apr 29, 2025 am 12:17 AM

Pythonlistsarebetterthanarraysformanagingdiversedatatypes.1)Listscanholdelementsofdifferenttypes,2)theyaredynamic,allowingeasyadditionsandremovals,3)theyofferintuitiveoperationslikeslicing,but4)theyarelessmemory-efficientandslowerforlargedatasets.

您如何在Python數組中訪問元素?您如何在Python數組中訪問元素?Apr 29, 2025 am 12:11 AM

toAccesselementsInapyThonArray,useIndIndexing:my_array [2] accessEsthethEthErlement,returning.3.pythonosezero opitedEndexing.1)usepositiveandnegativeIndexing:my_list [0] fortefirstElment,fortefirstelement,my_list,my_list [-1] fornelast.2] forselast.2)

Python中有可能理解嗎?如果是,為什麼以及如果不是為什麼?Python中有可能理解嗎?如果是,為什麼以及如果不是為什麼?Apr 28, 2025 pm 04:34 PM

文章討論了由於語法歧義而導致的Python中元組理解的不可能。建議使用tuple()與發電機表達式使用tuple()有效地創建元組。 (159個字符)

Python中的模塊和包裝是什麼?Python中的模塊和包裝是什麼?Apr 28, 2025 pm 04:33 PM

本文解釋了Python中的模塊和包裝,它們的差異和用法。模塊是單個文件,而軟件包是帶有__init__.py文件的目錄,在層次上組織相關模塊。

Python中的Docstring是什麼?Python中的Docstring是什麼?Apr 28, 2025 pm 04:30 PM

文章討論了Python中的Docstrings,其用法和收益。主要問題:Docstrings對於代碼文檔和可訪問性的重要性。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

VSCode Windows 64位元 下載

VSCode Windows 64位元 下載

微軟推出的免費、功能強大的一款IDE編輯器

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )專業的PHP整合開發工具