Table of Contents
Normally, when you need to connect to
For the many
ex
nx
xx
Home Database Redis A brief analysis of how to use Redis in Python

A brief analysis of how to use Redis in Python

Nov 22, 2021 pm 07:22 PM
python redis

How to use Redis in Python? The following article will introduce to you how to use Redis in Python. I hope it will be helpful to you!

A brief analysis of how to use Redis in Python

Previously we used Redis client to use Redis, but in actual work, in most cases The following are all using Redis through code. Since the editor is familiar with Python, we will learn how to use Python today. ##Redis. [Related recommendations: Redis video tutorial]

Environment preparation

  • Redis First you need to install it.
  • Python is installed (Python3 is recommended). The Python
  • library of
  • Redis is installed (pip install redis).
Start practicing

Try it out

Example: We plan to connect to

Redis through Python. Then write a kv, and finally print out the queried v.

Direct connection

#!/usr/bin/python3

import redis   # 导入redis模块

r = redis.Redis(host='localhost', port=6379, password="pwd@321", decode_responses=True)   # host是redis主机,password为认证密码,redis默认端口是6379
r.set('name', 'phyger-from-python-redis')  # key是"name" value是"phyger-from-python-redis" 将键值对存入redis缓存
print(r['name'])  # 第一种:取出键name对应的值
print(r.get('name'))  # 第二种:取出键name对应的值
print(type(r.get('name')))
Copy after login

A brief analysis of how to use Redis in Python

A brief analysis of how to use Redis in Python

##get

is the last one in the connection pool command to execute.

Connection pool

Normally, when you need to connect to

redis

, a connection will be created, and redis operations will be performed based on this connection. Release after the operation is completed. Under normal circumstances, this is no problem, but when the amount of concurrency is high, frequent connection creation and release will have a high impact on performance, so the connection pool comes into play. The principle of connection pool: Create multiple connections in advance. When performing

redis

operations, directly obtain the already created connections for operation. After completion, the connection will not be released, but returned to the connection pool for subsequent redis operations! This avoids continuous creation and release, thus improving performance! <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class='brush:php;toolbar:false;'>#!/usr/bin/python3 import redis,time # 导入redis模块,通过python操作redis 也可以直接在redis主机的服务端操作缓存数据库 pool = redis.ConnectionPool(host=&amp;#39;localhost&amp;#39;, port=6379, password=&quot;pwd@321&quot;, decode_responses=True) # host是redis主机,需要redis服务端和客户端都起着 redis默认端口是6379 r = redis.Redis(connection_pool=pool) r.set(&amp;#39;name&amp;#39;, &amp;#39;phyger-from-python-redis&amp;#39;) print(r[&amp;#39;name&amp;#39;]) print(r.get(&amp;#39;name&amp;#39;)) # 取出键name对应的值 print(type(r.get(&amp;#39;name&amp;#39;)))</pre><div class="contentsignin">Copy after login</div></div>

A brief analysis of how to use Redis in Python

You will find that in actual use, the effect of direct connection and using connection pool is the same, but there will be an obvious difference when concurrency is high. .

Basic Operation Practice

For the many

Redis

commands, we take the SET command as an example to demonstrate.

Format:

set(name, value, ex=None, px=None, nx=False, xx=False)

Parameters of the set command in redis-py:

Parameter nameexpxnxxxIf true, the current set operation will only be executed when name exists implement

ex

我们计划创建一个 kv 并且设置其 ex3,期待 3 秒后此 kv 会变为 None

#!/usr/bin/python3

import redis,time   # 导入redis模块,通过python操作redis 也可以直接在redis主机的服务端操作缓存数据库

pool = redis.ConnectionPool(host=&#39;localhost&#39;, port=6379, password="pwd@321", decode_responses=True)   # host是redis主机,需要redis服务端和客户端都起着 redis默认端口是6379
r = redis.Redis(connection_pool=pool)
r.set(&#39;name&#39;, &#39;phyger-from-python-redis&#39;,ex=3)
print(r[&#39;name&#39;])    # 应当有v
time.sleep(3)
print(r.get(&#39;name&#39;))  # 应当无v
print(type(r.get(&#39;name&#39;)))
Copy after login

A brief analysis of how to use Redis in Python

nx

由于 px 的单位太短,我们就不做演示,效果和 ex 相同。

我们计划去重复 set 前面已经 set 过的 name,不出意外的话,在 nx 为真时,我们将会 set 失败。但是人如果 set 不存在的 name1,则会成功。

#!/usr/bin/python3

import redis,time   # 导入redis模块,通过python操作redis 也可以直接在redis主机的服务端操作缓存数据库

pool = redis.ConnectionPool(host=&#39;localhost&#39;, port=6379, password="pwd@321", decode_responses=True)   # host是redis主机,需要redis服务端和客户端都起着 redis默认端口是6379
r = redis.Redis(connection_pool=pool)
r.set(&#39;name&#39;, &#39;phyger-0&#39;,nx=3) # set失败
print(r[&#39;name&#39;])    # 应当不生效
r.set(&#39;name1&#39;, &#39;phyger-1&#39;,nx=3) # set成功
print(r.get(&#39;name1&#39;))  # 应当生效
print(type(r.get(&#39;name&#39;)))
Copy after login

A brief analysis of how to use Redis in Python

如上,你会发现 nameset 未生效,因为 name 已经存在于数据库中。而 name1set 已经生效,因为 name1 是之前在数据库中不存在的。

xx

我们计划去重复 set 前面已经 set 过的 name,不出意外的话,在 nx 为真时,我们将会 set 成功。但是人如果 set 不存在的 name2,则会失败。

#!/usr/bin/python3

import redis,time   # 导入redis模块,通过python操作redis 也可以直接在redis主机的服务端操作缓存数据库

pool = redis.ConnectionPool(host=&#39;localhost&#39;, port=6379, password="pwd@321", decode_responses=True)   # host是redis主机,需要redis服务端和客户端都起着 redis默认端口是6379
r = redis.Redis(connection_pool=pool)
r.set(&#39;name&#39;, &#39;phyger-0&#39;,xx=3) # set失败
print(r[&#39;name&#39;])    # 应当变了
r.set(&#39;name2&#39;, &#39;phyger-1&#39;,xx=3) # set成功
print(r.get(&#39;name2&#39;))  # 应当没有set成功
print(type(r.get(&#39;name&#39;)))
Copy after login

A brief analysis of how to use Redis in Python

以上,就是今天全部的内容,更多信息建议参考 redis 官方文档。

更多编程相关知识,请访问:编程视频!!

The above is the detailed content of A brief analysis of how to use Redis in Python. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

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 Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

How is the GPU support for PyTorch on CentOS How is the GPU support for PyTorch on CentOS Apr 14, 2025 pm 06:48 PM

Enable PyTorch GPU acceleration on CentOS system requires the installation of CUDA, cuDNN and GPU versions of PyTorch. The following steps will guide you through the process: CUDA and cuDNN installation determine CUDA version compatibility: Use the nvidia-smi command to view the CUDA version supported by your NVIDIA graphics card. For example, your MX450 graphics card may support CUDA11.1 or higher. Download and install CUDAToolkit: Visit the official website of NVIDIACUDAToolkit and download and install the corresponding version according to the highest CUDA version supported by your graphics card. Install cuDNN library:

Detailed explanation of docker principle Detailed explanation of docker principle Apr 14, 2025 pm 11:57 PM

Docker uses Linux kernel features to provide an efficient and isolated application running environment. Its working principle is as follows: 1. The mirror is used as a read-only template, which contains everything you need to run the application; 2. The Union File System (UnionFS) stacks multiple file systems, only storing the differences, saving space and speeding up; 3. The daemon manages the mirrors and containers, and the client uses them for interaction; 4. Namespaces and cgroups implement container isolation and resource limitations; 5. Multiple network modes support container interconnection. Only by understanding these core concepts can you better utilize Docker.

Python vs. JavaScript: Community, Libraries, and Resources Python vs. JavaScript: Community, Libraries, and Resources Apr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

Redis: Classifying Its Database Approach Redis: Classifying Its Database Approach Apr 15, 2025 am 12:06 AM

Redis's database methods include in-memory databases and key-value storage. 1) Redis stores data in memory, and reads and writes fast. 2) It uses key-value pairs to store data, supports complex data structures such as lists, collections, hash tables and ordered collections, suitable for caches and NoSQL databases.

How to operate distributed training of PyTorch on CentOS How to operate distributed training of PyTorch on CentOS Apr 14, 2025 pm 06:36 PM

PyTorch distributed training on CentOS system requires the following steps: PyTorch installation: The premise is that Python and pip are installed in CentOS system. Depending on your CUDA version, get the appropriate installation command from the PyTorch official website. For CPU-only training, you can use the following command: pipinstalltorchtorchvisiontorchaudio If you need GPU support, make sure that the corresponding version of CUDA and cuDNN are installed and use the corresponding PyTorch version for installation. Distributed environment configuration: Distributed training usually requires multiple machines or single-machine multiple GPUs. Place

How to install nginx in centos How to install nginx in centos Apr 14, 2025 pm 08:06 PM

CentOS Installing Nginx requires following the following steps: Installing dependencies such as development tools, pcre-devel, and openssl-devel. Download the Nginx source code package, unzip it and compile and install it, and specify the installation path as /usr/local/nginx. Create Nginx users and user groups and set permissions. Modify the configuration file nginx.conf, and configure the listening port and domain name/IP address. Start the Nginx service. Common errors need to be paid attention to, such as dependency issues, port conflicts, and configuration file errors. Performance optimization needs to be adjusted according to the specific situation, such as turning on cache and adjusting the number of worker processes.

How to configure slow query log in centos redis How to configure slow query log in centos redis Apr 14, 2025 pm 04:54 PM

Enable Redis slow query logs on CentOS system to improve performance diagnostic efficiency. The following steps will guide you through the configuration: Step 1: Locate and edit the Redis configuration file First, find the Redis configuration file, usually located in /etc/redis/redis.conf. Open the configuration file with the following command: sudovi/etc/redis/redis.conf Step 2: Adjust the slow query log parameters in the configuration file, find and modify the following parameters: #slow query threshold (ms)slowlog-log-slower-than10000#Maximum number of entries for slow query log slowlog-max-len

See all articles
Interpretation
Expiration time (m)
Expiration time (ms)
If true, only name does not exist
##