12.django缓存+图片验证码

摘要:
Redis0库#默认值:存储Redis2库“img_code”:“Location”:“OPTIONS”:{“CLIENT_CLASS”:request):

1. django缓存设置

django的六种缓存:https://www.cnblogs.com/xiaonq/p/7978402.html#i6

1.1 Django缓存作用

  • 由于Django是动态网站,所有每次请求均会去数据进行相应的操作,当程序访问量大时,耗时必然会更加明显
  • 缓存将一个某个views的返回值保存至内存或者memcache中,5分钟内再有人来访问时,则不再去执行view中的操作
  • 而是直接从内存或者Redis中之前缓存的内容拿到,并返回

1.2 Django中提供了6种缓存方式

  1. 开发调试缓存
  2. 内存缓存
  3. 文件缓存
  4. 数据库缓存
  5. Memcache缓存(两种)

1.3 安装Django缓存模块

pip install django-redis==4.12.1

1.4 syl/settings.py中配置缓存

# 缓存配置
CACHES = {
    # django存缓默认位置,redis 0号库
    # default: 连接名称
    "default": {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "redis://127.0.0.1:6379/0",
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
        }
    },
    # django session存 reidis 1 号库(现在基本不需要使用)
    "session": {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "redis://127.0.0.1:6379/1",
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
        }
    },
    # 图形验证码,存redis 2号库
    "img_code": {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "redis://127.0.0.1:6379/2",
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
        }
    }
}

# 配置session使用redis存储
SESSION_ENGINE = "django.contrib.sessions.backends.cache"
# 配置session存储的位置: 使用cache中的 session配置
SESSION_CACHE_ALIAS = "session"

2. 新建应用verifications

2.1 在apps文件夹下新建应用: verifications
python ../manage.py startapp verifications # 切换到apps文件夹下执行创建命令

2.2 在syl/settings.py中添加应用
INSTALLED_APPS = [
    'verifications.apps.VerificationsConfig',
]

2.3 在syl/urls.py主路由中添加
path('verify/', include('verifications.urls')),

2.4 添加子路由: verifications/urls.py
from django.urls import path
from . import views
urlpatterns = [
    # path('image_codes/', views.ImageCodeView.as_view())
]


3. 图形验证码captcha使用

1.下载captcha压缩包captcha.zip,放到项目packages文件夹下
2.解压captcha.zip到syl/libs文件夹下
    - cd /root/shiyanlou_project/packages
    - unzip captcha.zip -d /root/shiyanlou_project/syl/libs
3.右键运行captcha.py即可生成验证码

4. 在verifications/views.py中使用

from django.http import HttpResponse, HttpResponseForbidden
from django.views import View
from django_redis import get_redis_connection
from libs.captcha.captcha import captcha


class ImageCodeView(View):
    def get(self, request):
        # 1.接收数据
        uuid = request.GET.get('uuid')
        # 2.校验数据
        if not uuid:
            return HttpResponseForbidden('uuid无效')

        # 3.处理业务
        # 获取图片文本内容和图片二进制代码
        text, image = captcha.generate_captcha()

        # 4.把uuid和图片文本存入redis
        redis_client = get_redis_connection('img_code')  # 获取redis客户端
        # 5.写入redis(是字符串)
        redis_client.setex(uuid, 60 * 5, text)
        # 6.返回响应图片
        return HttpResponse(image, content_type='image/jpg')



5. 流程图

12.django缓存+图片验证码第1张

6. 测试接口

http://192.168.56.100:8888/verify/image_codes/?uuid=e271324c-b2e2-4185-abee-841bac421d4b

在redis中查看:

redis-cli
127.0.0.1:6379># select 2
OK
127.0.0.1:6379[2]># keys *
1) "66ea64aa-fbe6-11ea-a3d3-005056c00008"
127.0.0.1:6379[2]># get 66ea64aa-fbe6-11ea-a3d3-005056c00008
"JEZ6"

7.vue联调

// 生成uuid
	getUuid() {
      var d = new Date().getTime()
      if (window.performance && typeof window.performance.now === 'function') {
        d += performance.now()
      }
      var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c)     {
        var r = (d + Math.random() * 16) % 16 | 0
        d = Math.floor(d / 16)
        return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16)
      })
      return uuid
    },

    // 动态生成图形验证码URL
    getImgUrl() {
      let uuid = this.getUuid()
      this.uuid = uuid
      let url = 'http://192.168.56.100:8888/verify/image_codes/?uuid=' + uuid
      // let url = 'http://192.168.56.100:8888/verify/image_codes/?uuid=66ea64aa-fbe6-11ea-a3d3-005056c00008'
      this.imgUrl = url
    },

免责声明:文章转载自《12.django缓存+图片验证码》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇Jmeter生成HTML性能测试报告maven缺少依赖包,强制更新命令下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

django安装xadmin中出现的报错汇总

报错一:ModuleNotFoundError: No module named 'django.core.urlresolvers' 1 ModuleNotFoundError: No module named 'django.core.urlresolvers' 解决方法:按照提示找到出错的文件, 将所有 import django.core.urlr...

CentOS7 连网 拨号上网 PPoe网

CentOS7  连网  拨号上网  PPoe网 在安装之前,请确定是否安装  rp-pppoe-3.5.rmp  如果没有安装,请使用 --replacepkgs  先强制安装它  (CentOS-7-x86_64-Everything-1511.iso 包文件夹内有) 如果没有安装,下面的请不要看了 [flx@localhost ~]$ su root...

在Django / DRF中正确处理日期时间/时区

我正在尝试为我的网络应用程序进行正确的日期处理设置.我有一个看起来像这样的模型 class Entity(models.Model): name = models.CharField(max_length=255) date = models.DateTimeField() 用户可以向我的DRF端点/ api / v1 / entity /...

pyinstaller深入使用,打包指定模块,打包静态文件

1.标准用法:     pyinstall  **.py  直接打包    pyinstall -F **.py  打包成单文件    pyinstall -W **.py  去掉控制台窗口,黑窗口    pyinstall -i ***.ico **.py  添加图标 *** 2.高级用法:     打包一遍以后,会在py文件目录下生成spec文件,是...

Vue入门笔记三(Vuex)

《Vue.js项目实战》 Vuex 集中式的状态管理 Vuex从Flux(由Facebook开发)的概念中获取得灵感。Flux又一系列指导原则构成,阐明了如何使用集中式store来实现组件之间的单向数据流。 Vuex的核心元素是store,是进行数据存储和数据处理的主要架构。 store包含如下信息: state // 存储应用状...

easyui icon的使用相关

easyui的默认图标有以下这些: .icon-blank{ background:url('icons/blank.gif') no-repeat; } .icon-add{ background:url('icons/edit_add.png') no-repeat; }...