西维蜀黍

【Django】Django 使用 Redis

安装 Dependency

$ pip install django-redis

作为 cache backend 使用配置

为了使用 django-redis , 在你项目下的setting.py中添加如下代码:

CACHES = {
    "default": {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "redis://127.0.0.1:6379/1",
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
        }
    }
}

为了更好的互操作性并使连接字符串更加 “标准”, 从 3.8.0 开始 django-redis 使用 redis-py native url notation 作为连接字符串.

  ...


【Redis】自动过期

自动过期

Redis中有个设置时间过期的功能,通过 setex 或者 expire 关键字来实现。

redis 127.0.0.1:6379> hset expire:me name tom
(integer) 0
redis 127.0.0.1:6379> hget expire:me name
"tom"
 
redis 127.0.0.1:6379> expire expire:me 20
(integer) 1
redis 127.0.0.1:6379> ttl expire:me     # 获得还有多久过期,比如这里就是就有 19 秒才过期
(integer) 19
 
...
...
...
 
redis 127.0.0.1:6379> ttl expire:me
(integer) -1
redis 127.0.0.1:6379> hget expire:me name

即对存储在Redis数据库中的键值对(key-value pair)可以设置一个过期时间。作为一个缓存数据库,这是非常实用的。如我们一般项目中的token、登录信息或者短信验证码都是有时间限制的,按照传统的数据库处理方式,一般都是自己判断过期,这样无疑会严重影响项目性能。

Redis对存储值的过期处理实际上是针对该值的键(key)处理的,即时间的设置也是设置key的有效时间。

Expires字典保存了所有键的过期时间,Expires也被称为过期字段。

  ...


【Python】变量作用域

Python的作用域分类

Python的作用域一共有4种,分别是:

  • L (Local) 局部作用域
  • E (Enclosing) 闭包函数外的函数中
  • G (Global) 全局作用域
  • B (Built-in) 内建作用域

以 L –> E –> G –>B 的顺序去查找,即:当在局部作用域中找不到时,便会去局部作用域之外的作用域去找(例如闭包),再找不到就会去全局作用域中找,再者去内建作用域中找。最终,如果仍没有找到,则会抛出NameError错误。

下面举一个实用LEGB法则的例子:

globalVar = 100           #G

def test_scope():
    enclosingVar = 200    #E
    def func():
        localVar = 300    #L
print __name__            #B
  ...


【Redis】Redis 常用命令

Redis中的所有数据结构均不支持数据类型的嵌套。比如,集合类型的每个元素都只能是字符串,而不能是另一个集合或散列表(Hash)。

字符串(String)

SET - 插入数据

SET key value [EX seconds|PX milliseconds|KEEPTTL] [NX|XX] [GET]
  • Time complexity: O(1)

Set key to hold the string value. If key already holds a value, it is overwritten, regardless of its type.

如果当前 key 已经存在 value,则用新 value 覆盖原有的value值。

一旦设置成功(无论当前有没有发生覆盖),则返回OK;如果没设置成功,返回 nil (比如 options中包含了 nx,这时,只有当当前 key 不存在 value时,才会真正去设置value,即无覆盖发生。否则,就会返回 nil)。

Return Value

  • Simple string reply: OK if SET was executed correctly.
  • Null reply: a Null Bulk Reply is returned if the SET operation was not performed because the user specified the NX or XX option but the condition was not met.

Options

The SET command supports a set of options that modify its behavior:

  • EX seconds – Set the specified expire time, in seconds.

  • PX milliseconds – Set the specified expire time, in milliseconds.

  • NX – Only set the key if it does not already exist.

    127.0.0.1:6379> set a cc
    OK
    127.0.0.1:6379> set a cccc
    OK
    127.0.0.1:6379> set a ddd NX
    (nil)
    
  • XX – Only set the key if it already exist.

  • KEEPTTL – Retain the time to live associated with the key.

  • GET – Return the old value stored at key, or nil when key did not exist.

GET - 读数据

  • Time complexity: O(1)

Get the value of key. If the key does not exist the special value nil is returned. An error is returned if the value stored at key is not a string, because GET only handles string values.

即,如果当前key没有value值,则返回null

GETSET key value

  • Time complexity: O(1)

将键 key 的值设为 value , 并返回键 key 在被设置之前的旧值。

返回值

返回给定键 key 的旧值。

如果键 key 没有旧值, 也即是说, 键 key 在被设置之前并不存在, 那么命令返回 nil

当键 key 存在但不是字符串类型时, 命令返回一个错误。

APPEND - 数据追加

  • 如果当前key的value有值则附加到原有string后面,如果没有则写入。返回值为追加后的数据长度

DEL - 数据删除

  • Time complexity: O(N) where N is the number of keys that will be removed. When a key to remove holds a value other than a string, the individual complexity for this key is O(M) where M is the number of elements in the list, set, sorted set or hash. Removing a single key that holds a string value is O(1).

Removes the specified keys. A key is ignored if it does not exist.

Return value

Integer reply: The number of keys that were removed.

127.0.0.1:6379> set name wei
OK
127.0.0.1:6379> get name
"wei"
127.0.0.1:6379> append name isgreat
(integer) 10
127.0.0.1:6379> get name
"weiisgreat"
127.0.0.1:6379> del wei
(integer) 0
127.0.0.1:6379> get wei
(nil)
  ...


【Redis】安装 Redis

Via docker

$ mkdir redis_config; touch redis_config/redis.conf
$ docker run -itd --restart unless-stopped --name redis -p 6379:6379 redis

Access from another host

redis-cli -h 192.168.18.129
192.168.18.129:6379> ping
PONG
192.168.18.129:6379>

macOS 安装

Installation - Via brew

$ brew install redis

后台运行 redis 服务

$ brew services start redis

前台运行 Redis 服务

$ redis-server

可以直接运行 redis-server 以启动 Redis 服务(在服务端中输入 quit 可以退出)。然后另外开一个终端,运行 redis-cli 以启动一个客户端。

  ...