search
HomeBackend DevelopmentPython TutorialDetailed explanation of how to install and use redis in Python

This article mainly introduces the method of installing and using redis in Python, analyzes the specific steps of installation and configuration, and analyzes the specific usage skills of the redis database in detail with examples. Friends in need can refer to it

The example in this article describes how to install and use redis in python. Share it with everyone for your reference, the details are as follows:

1. Installation

Okay, I admit that I only know the simplest installation:

sudo apt-get install redis-server

python support package: (Actually, it’s just a file, you can just get it and use it)

sudo apt-get install python-redis

2. Configuration

Configure it. The default configuration file is: "/etc/redis/redis.conf"
Binding ip:

"bind 127.0.0.1″ -> "bind 10.0.1.7″

Change the disk synchronization to non-synchronization or synchronization every second. If it is synchronized all the time, it will be too slow:

"appendfsync always" -> "appendfsync no"

Check the background execution Whether to open:

"daemonize yes"

Or anything else you want to set, for example:

Connection timeout: "timeout 300"

Run level : "loglevel notice" (I personally think the default one is pretty good. Unless there is a big exception, there is no need to change it to debug)

3. Use

#! /usr/bin/env python
#coding=utf-8
import redis
print redis.__file__
# 连接,可选不同数据库
r = redis.Redis(host='10.0.1.7', port=6379, db=1)
# -------------------------------------------
# 看信息
info = r.info()
for key in info:
 print "%s: %s" % (key, info[key])
# 查数据库大小
print '\ndbsize: %s' % r.dbsize()
# 看连接
print "ping %s" % r.ping()
# 选数据库
#r.select(2)
# 移动数据去2数据库
#r.move('a',2)
# 其他
#r.save('a') # 存数据
#r.lastsave('a') # 取最后一次save时间
#r.flush() #刷新
#r.shutdown() #关闭所有客户端,停掉所有服务,退出服务器
#
#--------------------------------------------
# 它有四种类型: string(key,value)、list(序列)、set(集合)、zset(有序集合,多了一个顺序属性)
# 不知道你用的哪种类型?
# print r.get_type('a') #可以告诉你
# -------------------------------------------
# string操作
print '-'*20
# 塞数据
r['c1'] = 'bar'
#或者
r.set('c2','bar')
#这里有个 getset属性,如果为True 可以在存新数据时将上次存储内容同时搞出来
print 'getset:',r.getset('c2','jj')
#如果你想设置一个递增的整数 每执行一次它自加1:
print 'incr:',r.incr('a')
#如果你想设置一个递减的整数 please:
print 'decr:',r.decr('a')
# 取数据
print 'r['']:',r['c1']
#或者
print 'get:',r.get('a')
#或者 同时取一批
print 'mget:',r.mget('c1','c2')
#或者 同时取一批 它们的名字(key)很像 而恰好你又不想输全部
print 'keys:',r.keys('c*')
#又或者 你只想随机取一个:
print 'randomkey:',r.randomkey()
# 查看一个数据有没有 有 1 无0
print 'existes:',r.exists('a')
# 删数据 1是删除成功 0和None是没这个东西
print 'delete:',r.delete('cc')
# 哦对了 它是支持批量操作的
print 'delete:',r.delete('c1','c2')
# 其他
r.rename('a','c3') #呃.改名
r.expire('c3',10) #让数据10秒后过期 说实话我不太明白么意思
r.ttl('c3') #看剩余过期时间 不存在返回-1
#--------------------------------
# 序列(list)操作
print '-'*20
# 它是两头通的
# 塞入
r.push('b','gg')
r.push('b','hh')
# head 属性控制是不是从另一头塞
r.push('b','ee',head=True)
# 看长度
print 'list len:',r.llen('b')
# 列出一批出来
print 'list lrange:',r.lrange('b',start=0,end=-1)
# 取出一位
print 'list index 0:',r.lindex('b',0)
# 修剪列表
#若start 大于end,则将这个list清空
print 'list ltrim :',r.ltrim('b',start=0,end=3) #只留 从0到3四位
# 排序
# 这可是个大工程
#--------------------------------
# 集合(set)操作
# 塞数据
r.sadd('s', 'a')
# 判断一个set长度为多少 不存在为0
r.scard('s')
# 判断set中一个对象是否存在
r.sismember('s','a')
# 求交集
r.sadd('s2','a')
r.sinter('s1','s2')
#求交集并将结果赋值
r.sinterstore('s3','s1','s2')
# 看一个set对象
r.smembers('s3')
# 求并集
r.sunion('s1','s2')
# 阿 我想聪明的你已经猜到了
#求并集 并将结果返回
r.sunionstore('ss','s1','s2','s3')
# 求不同
# 在s1中有,但在s2和s3中都没有的数
r.sdiff('s1','s2','s3')
r.sdiffstore('s4','s1','s2')# 这个你懂的
# 取个随机数
r.srandmember('s1')
#-------------------------------------
#zset 有序set
#'zadd', 'zcard', 'zincr', 'zrange', 'zrangebyscore', 'zrem', 'zscore'
# 分别对应
#添加, 数量, 自加1,取数据,按照积分(范围)取数据,删除,取积分
# 我靠 你玩死我了 redis!
# 今天在实验中,我尝试插入一条zset类型数据:
r1.zset(u'www.liyi99.com','liwu',3)
# 插入成功
# 我继续插入
r1.zset(u'www.liyi99,com',u'\u9001\u793c',5)
#报错:
#UnicodeDecodeError: 'ascii' codec can't decode byte 0xe4 in position 0: ordinal not in range(128)
#这次插入的是礼物的中文词 unicode编码
#为什么会失败那,这条数据是我从redis里面取出来然后没做任何修改再插入的阿
#redis返回和接受的数据类型都是unicode编码的阿
#好吧,我们再次插入试试
#再次插入
r1.zset('www.liyi99.com',u'\u9001\u793c',5)
#成功了
#插入
r1.zset('www.liyi99.com','礼物',5)
#依然成功,跟入redis.py 1024行
return self.send_command('ZADD %s %s %s\r\n%s\r\n' % (
  key, score, len(member), member))
# 哦 万恶的编码转换!
#不过取的时候,不论第一个是何种类型的数据都无关系

For more detailed articles on how to install python and use redis, please pay attention to the PHP Chinese website!

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
How do you create multi-dimensional arrays using NumPy?How do you create multi-dimensional arrays using NumPy?Apr 29, 2025 am 12:27 AM

Create multi-dimensional arrays with NumPy can be achieved through the following steps: 1) Use the numpy.array() function to create an array, such as np.array([[1,2,3],[4,5,6]]) to create a 2D array; 2) Use np.zeros(), np.ones(), np.random.random() and other functions to create an array filled with specific values; 3) Understand the shape and size properties of the array to ensure that the length of the sub-array is consistent and avoid errors; 4) Use the np.reshape() function to change the shape of the array; 5) Pay attention to memory usage to ensure that the code is clear and efficient.

Explain the concept of 'broadcasting' in NumPy arrays.Explain the concept of 'broadcasting' in NumPy arrays.Apr 29, 2025 am 12:23 AM

BroadcastinginNumPyisamethodtoperformoperationsonarraysofdifferentshapesbyautomaticallyaligningthem.Itsimplifiescode,enhancesreadability,andboostsperformance.Here'showitworks:1)Smallerarraysarepaddedwithonestomatchdimensions.2)Compatibledimensionsare

Explain how to choose between lists, array.array, and NumPy arrays for data storage.Explain how to choose between lists, array.array, and NumPy arrays for data storage.Apr 29, 2025 am 12:20 AM

ForPythondatastorage,chooselistsforflexibilitywithmixeddatatypes,array.arrayformemory-efficienthomogeneousnumericaldata,andNumPyarraysforadvancednumericalcomputing.Listsareversatilebutlessefficientforlargenumericaldatasets;array.arrayoffersamiddlegro

Give an example of a scenario where using a Python list would be more appropriate than using an array.Give an example of a scenario where using a Python list would be more appropriate than using an array.Apr 29, 2025 am 12:17 AM

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

How do you access elements in a Python array?How do you access elements in a Python array?Apr 29, 2025 am 12:11 AM

ToaccesselementsinaPythonarray,useindexing:my_array[2]accessesthethirdelement,returning3.Pythonuseszero-basedindexing.1)Usepositiveandnegativeindexing:my_list[0]forthefirstelement,my_list[-1]forthelast.2)Useslicingforarange:my_list[1:5]extractselemen

Is Tuple Comprehension possible in Python? If yes, how and if not why?Is Tuple Comprehension possible in Python? If yes, how and if not why?Apr 28, 2025 pm 04:34 PM

Article discusses impossibility of tuple comprehension in Python due to syntax ambiguity. Alternatives like using tuple() with generator expressions are suggested for creating tuples efficiently.(159 characters)

What are Modules and Packages in Python?What are Modules and Packages in Python?Apr 28, 2025 pm 04:33 PM

The article explains modules and packages in Python, their differences, and usage. Modules are single files, while packages are directories with an __init__.py file, organizing related modules hierarchically.

What is docstring in Python?What is docstring in Python?Apr 28, 2025 pm 04:30 PM

Article discusses docstrings in Python, their usage, and benefits. Main issue: importance of docstrings for code documentation and accessibility.

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor