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
What are some common operations that can be performed on Python arrays?What are some common operations that can be performed on Python arrays?Apr 26, 2025 am 12:22 AM

Pythonarrayssupportvariousoperations:1)Slicingextractssubsets,2)Appending/Extendingaddselements,3)Insertingplaceselementsatspecificpositions,4)Removingdeleteselements,5)Sorting/Reversingchangesorder,and6)Listcomprehensionscreatenewlistsbasedonexistin

In what types of applications are NumPy arrays commonly used?In what types of applications are NumPy arrays commonly used?Apr 26, 2025 am 12:13 AM

NumPyarraysareessentialforapplicationsrequiringefficientnumericalcomputationsanddatamanipulation.Theyarecrucialindatascience,machinelearning,physics,engineering,andfinanceduetotheirabilitytohandlelarge-scaledataefficiently.Forexample,infinancialanaly

When would you choose to use an array over a list in Python?When would you choose to use an array over a list in Python?Apr 26, 2025 am 12:12 AM

Useanarray.arrayoveralistinPythonwhendealingwithhomogeneousdata,performance-criticalcode,orinterfacingwithCcode.1)HomogeneousData:Arrayssavememorywithtypedelements.2)Performance-CriticalCode:Arraysofferbetterperformancefornumericaloperations.3)Interf

Are all list operations supported by arrays, and vice versa? Why or why not?Are all list operations supported by arrays, and vice versa? Why or why not?Apr 26, 2025 am 12:05 AM

No,notalllistoperationsaresupportedbyarrays,andviceversa.1)Arraysdonotsupportdynamicoperationslikeappendorinsertwithoutresizing,whichimpactsperformance.2)Listsdonotguaranteeconstanttimecomplexityfordirectaccesslikearraysdo.

How do you access elements in a Python list?How do you access elements in a Python list?Apr 26, 2025 am 12:03 AM

ToaccesselementsinaPythonlist,useindexing,negativeindexing,slicing,oriteration.1)Indexingstartsat0.2)Negativeindexingaccessesfromtheend.3)Slicingextractsportions.4)Iterationusesforloopsorenumerate.AlwayschecklistlengthtoavoidIndexError.

How are arrays used in scientific computing with Python?How are arrays used in scientific computing with Python?Apr 25, 2025 am 12:28 AM

ArraysinPython,especiallyviaNumPy,arecrucialinscientificcomputingfortheirefficiencyandversatility.1)Theyareusedfornumericaloperations,dataanalysis,andmachinelearning.2)NumPy'simplementationinCensuresfasteroperationsthanPythonlists.3)Arraysenablequick

How do you handle different Python versions on the same system?How do you handle different Python versions on the same system?Apr 25, 2025 am 12:24 AM

You can manage different Python versions by using pyenv, venv and Anaconda. 1) Use pyenv to manage multiple Python versions: install pyenv, set global and local versions. 2) Use venv to create a virtual environment to isolate project dependencies. 3) Use Anaconda to manage Python versions in your data science project. 4) Keep the system Python for system-level tasks. Through these tools and strategies, you can effectively manage different versions of Python to ensure the smooth running of the project.

What are some advantages of using NumPy arrays over standard Python arrays?What are some advantages of using NumPy arrays over standard Python arrays?Apr 25, 2025 am 12:21 AM

NumPyarrayshaveseveraladvantagesoverstandardPythonarrays:1)TheyaremuchfasterduetoC-basedimplementation,2)Theyaremorememory-efficient,especiallywithlargedatasets,and3)Theyofferoptimized,vectorizedfunctionsformathematicalandstatisticaloperations,making

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

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

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),

EditPlus Chinese cracked version

EditPlus Chinese cracked version

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

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!