Redis 是一种内存中的键值对 NoSQL 数据存储,通常用于 Web 应用程序会话、瞬态数据并用作任务队列的代理。 redis-py 是用于与 Redis 交互的通用 Python 代码库。让我们学习如何在 Ubuntu 上启动和运行 Redis,然后开始在简单的 Python 应用程序中使用它。
我们需要的工具
本教程使用 Python 3.5 进行了测试,但 Python 2 或 3 应该适用于此处编写的所有内容。只需转到终端并键入python --version
,确保您的系统上安装了一个版本。除了 Python 本身,以下是我们将在本文其余部分使用的软件:
- Ubuntu 16.04(这些说明也适用于早期的 Ubuntu 版本)
- pip 和 virtualenv 来处理 theredis-py 应用程序依赖性
- Redis
- redis-py
如果您不确定如何安装 pip 和 virtualenv,请查看如何在 Ubuntu 16.04 LTS 上设置 Python 3、Flask 和 Green Unicorn 指南的前几个步骤。
安装Redis
安装Redis的方式有很多种,比如从源码下载编译。但是在Ubuntu上我们可以通过apt
来安装一个系统包。此方法的优点是apt
进程将负责将redis-server
安装为系统服务。打开终端并运行以下命令:
sudo apt-get install redis-server
输入您的 sudo
密码,当系统提示您是否要安装新包时,输入“是”。
片刻之后,下载和处理应该完成,您将回到提示符处。
Redis 现已安装,Redis 服务器作为系统服务在后台运行。即使我们安装了 redis-server
包,安装也附带了 Redis 命令行客户端。客户端对于直接连接到 Redis 服务器非常有用,无需任何 Python 代码。通过在命令提示符中键入以下内容来尝试redis-cli
:
redis-cli
Redis 客户端连接到本地主机服务器并给出一个新提示以表明它已准备好接受命令:
使用 keys *
或 set a 1
等 Redis 命令尝试提示。项目文档中提供了 Redis 命令的完整列表。
虚拟环境和安装redis-py
我们需要弄清楚我们的python3
位置,然后创建一个virtualenv,激活virtualenv,然后用pip
安装redis-py。用python3
命令确定你的which
可执行位置。
which python3
您会看到如下图所示的输出。
在您的主目录或您存储项目虚拟环境的任何地方创建一个新的虚拟环境。指定您的python3
installation 的完整路径。
# specify the system python3 installation virtualenv --python=/usr/bin/python3 venvs/redistest
激活虚拟环境。
source ~/venvs/redistest/bin/activate
接下来我们可以使用 pip
命令从 PyPI 安装 redis-py Python 包。
pip install redis
好的,现在它已经安装在我们的虚拟环境中了。让我们写一些简单的 Python 代码来试试 give redis-py!
从 Python 使用 Redis
使用python
或python3
命令启动Python REPL。也可以在“testredis.py”等Python文件中编写如下代码,然后用python testredis.py
执行。
import redis # create a connection to the localhost Redis server instance, by # default it runs on port 6379 redis_db = redis.StrictRedis(host="localhost", port=6379, db=0) # see what keys are in Redis redis_db.keys() # output for keys() should be an empty list "[]" redis_db.set('full stack', 'python') # output should be "True" redis_db.keys() # now we have one key so the output will be "[b'full stack']" redis_db.get('full stack') # output is "b'python'", the key and value still exist in Redis redis_db.incr('twilio') # output is "1", we just incremented even though the key did not # previously exist redis_db.get('twilio') # output is "b'1'" again, since we just obtained the value from # the existing key redis_db.delete('twilio') # output is "1" because the command was successful redis_db.get('twilio') # nothing is returned because the key and value no longer exist
这是对一些常用的 Redis 命令的快速介绍,这些命令由它们的 Python 绑定通过 redis-py 库调用。查看 theredis-py 官方文档,详细了解可用于在 Redis 中创建、读取、修改和删除键和值的广泛命令列表。
有问题吗?发送推文@fullstackpython 或在 Full Stack Python Facebook 页面上发布消息。看到这篇文章有什么问题吗?在 GitHub 上创建此页面的源代码并提交拉取请求。