Django项目学习4--注册功能(流水账)

首先该django项目的注册页面,有个验证码,该验证码是死的,验证码其实就是一张图已经存好的图片。
《Django项目学习4--注册功能(流水账)》
这样肯定不符合要求。
这时,我们需要库pillow,安装:
《Django项目学习4--注册功能(流水账)》
然后把提供的包复制到项目根目录下的utiles下
《Django项目学习4--注册功能(流水账)》

一、设计接口的思路

  • 分析业务逻辑,明确在这个业务中需要涉及到几个相关子业务,将每个子业务当做一个接口来设计
  • 分析接口的功能任务,明确接口的访问方式与返回数据:
    • 接口的请求方式,如GET 、POST 、PUT等
    • 接口的URL路径定义
    • 需要前端传递的数据及数据格式(如路径参数、查询字符串、请求体表单、JSON等)
    • 返回给前端的数据及数据格式

二、业务的功能分析

  • 用户名判断是否存在
  • 手机号判断是否存在
  • 图片验证码
  • 短信验证码
  • 注册保存用户数据

图片验证码、短信验证码考虑到后续可能会在其他业务中也会用到,因此将验证码功能独立出来,创建一个新应用verifications,在此应用中实现图片验证码、短信验证码

三、图片验证码接口代码实现

1.图片验证码认证

请求方法GET

url定义/image_code/<uuid:image_code_id>/

请求参数:url路径参数

参数类型前端是否必须传描述
image_codesuuid字符串图片验证码编号

uuid:Universally unique identifier(eg. 123e4567-e89b-12d3-a456-426655440000)

2.后端视图实现

a.将生成图像验证码的模块文件夹(百度云盘有提供captcha文件夹)复制粘贴到项目根目录utils文件夹下

b.用于验证(图片验证、短信验证)功能,以后有可能在其他应用或项目中重用,所以单独创建一个应用来实现,所有验证相关的业务逻辑接口。在apps目录中创建一个verifications应用,并在settings.py文件中的INSTALLED_APPS列表中指定。

需要安装pillow包

# 在verifications/views.py文件中添加如下代码:


import logging

from django.shortcuts import render
from django.views import View
from django_redis import get_redis_connection
from django.http import HttpResponse

from utils.captcha.captcha import captcha
# 安装图片验证码所需要的 Pillow 模块
# pip install Pillow
from users.models import Users

# 导入日志器
logger = logging.getLogger('django')


class ImageCode(View):
    """ define image verification view # /image_codes/<uuid:image_code_id>/ """
    def get(self, request, image_code_id):
        text, image = captcha.generate_captcha()
        # 确保settings.py文件中有配置redis CACHE
        # Redis原生指令参考 http://redisdoc.com/index.html
        # Redis python客户端 方法参考 http://redis-py.readthedocs.io/en/latest/#indices-and-tables
        con_redis = get_redis_connection(alias='verify_codes')
        img_key = "img_{}".format(image_code_id).encode('utf-8')
        # 将图片验证码的key和验证码文本保存到redis中,并设置过期时间
        con_redis.setex(img_key,300, text)
        logger.info("Image code: {}".format(text))
        # HttpResponse(content=响应体, content_type=响应体数据类型, status=状态码)
        return HttpResponse(content=image, content_type="image/jpg")

d.本项目需要将图形验证码、短信验证码以及用户的会话信息保存到redis服务器中,所以需要在settings.py文件中指定如下配置信息:

# settings.py文件中加入如下内容:

CACHES = { 
    "default": { 
        "BACKEND": "django_redis.cache.RedisCache",  # 指定redis缓存后端
        "LOCATION": "redis://127.0.0.1:6379/0",
        "OPTIONS": { 
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
            # "PASSWORD": "mysecret"
        }
    },
    
    "verify_codes": { 
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "redis://127.0.0.1:6379/1",
        "OPTIONS": { 
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
        }
    },
}

e.在verifications应用下创建一个urls.py文件并添加如下内容:

# verifications应用下创建一个urls.py

from django.urls import path, re_path

from . import views

app_name = "verifications"

urlpatterns = [
    # re_path(r'^image_codes/(?P<image_code_id>[\w-]+)/$', view=views.ImageCodeView.as_view(), name="image_code"),
    # image_code_id为uuid格式
    path('image_code/<uuid:image_code_id>/', views.ImageCode.as_view(), name='image_code'),

]

3.前端代码实现

html代码:

{ % extends 'base/base.html' %}
{ % load static %}
<!-- css title start -->
{ % block title %}
  注册页
{ % endblock %}
<!-- css title end -->

{ % block link %}
<link rel="stylesheet" href="../../static/css/authPro/auth.css">
{ % endblock %}

{ % block main %}
<!-- container start -->
<main id="container">
  <div class="register-contain">
    <div class="top-contain">
      <h4 class="please-register">请注册</h4>
      <a href="{% url 'users:login' %}" class="login">立即登录 &gt;</a>
    </div>
    <form action="" method="post" class="form-contain">
      { % csrf_token %}
      <div class="form-item">
        <input type="text" placeholder="请输入用户名" name="username" id="user_name" class="form-control" autocomplete="off">
      </div>
      <div class="form-item">
        <input type="password" placeholder="请输入密码" name="password" class="form-control">
      </div>
      <div class="form-item">
        <input type="password" placeholder="请输入确认密码" name="password_repeat" class="form-control">
      </div>
      <div class="form-item">
        <input type="tel" placeholder="请输入手机号" name="telephone" class="form-control" id="mobile" autocomplete="off">
      </div>
      <div class="form-item">
        <input type="text" placeholder="请输入图形验证码" name="captcha_graph" id="input_captcha" class="form-captcha">
        <a href="javascript:void(0);" class="captcha-graph-img">
          <img src="" alt="验证码" title="点击刷新">
        </a>
      </div>
      <div class="form-item">
        <input type="text" placeholder="请输入短信验证码" name="sms_captcha" class="form-captcha" autocomplete="off">
        <a href="javascript:void(0);" class="sms-captcha" title="发送验证码">获取短信验证码</a>
      </div>
      <div class="form-item">
        <input type="submit" value="立即注册" class="register-btn">
      </div>
    </form>
  </div>
</main>
<!-- container end -->
{ % endblock %}

{ % block script %}
  <script src="{% static 'js/users/register.js' %}"></script>

{ % endblock %}

在js文件夹下创建一个users文件夹用户存放用户模块相关的js文件,在users文件下创建auth.js文件。

/**
 * Created 蓝羽教学 on 2019/11/18.
 */


$(function () { 

    let $img = $(".form-item .captcha-graph-img img");   // 获取图像

    // let $imgCodeText = $('#input_captcha');
    // console.log(img);
    genreate();
    $img.click(genreate);
    function genreate() { 
		let sImageCodeId = generateUUID()
        let imageCodeUrl = '/image_code/' + sImageCodeId + '/';

        $img.attr('src', imageCodeUrl)
    }

     // 生成图片UUID验证码
  function generateUUID() { 
    let d = new Date().getTime();
    if (window.performance && typeof window.performance.now === "function") { 
        d += performance.now(); //use high-precision timer if available
    }
    let uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) { 
        let r = (d + Math.random() * 16) % 16 | 0;
        d = Math.floor(d / 16);
        return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
    });
    return uuid;
  }

});

好。课件复制粘贴完毕,开始真正的流水账

《Django项目学习4--注册功能(流水账)》

配置好路由之后,就可以开始试一下了
直接访问这个url
《Django项目学习4--注册功能(流水账)》

既然图片拿到了,就需要把它放到注册页面的框框里。
《Django项目学习4--注册功能(流水账)》
但是这个图形验证码是不会改变的,此时当然会想到用点击事件,但事实上,我们还要到数据库上去验证,标识,并不能简单用点击事件。这时需要使用到uuid(通用唯一标识码的缩写,具体可查看百度百科)来标识我们的图形验证码。需要用到js代码。
可以新建:
《Django项目学习4--注册功能(流水账)》
然后在注册页面中引入
《Django项目学习4--注册功能(流水账)》
如果我们直接定义一个点击事件函数,那么在刚刷新页面的时候,是没有验证码出来的。
《Django项目学习4--注册功能(流水账)》
此时,就需要如此这般操作:
《Django项目学习4--注册功能(流水账)》
《Django项目学习4--注册功能(流水账)》
url中的路由为

《Django项目学习4--注册功能(流水账)》
拼接uuid是为了给图片一个标识,方便输入之后在数据库中比对是不是同一个验证码。

在redis数据库中添加多一个使用的配置,用于临时验证验证码。改为其他库。

# redis配置
CACHES = { 
	"default": { 
		"BACKEND": "django_redis.cache.RedisCache",
		"LOCATION": "redis://127.0.0.1:6379/0",
		"OPTIONS": { 
			"CLIENT_CLASS": "django_redis.client.DefaultClient",
		},
	},
	#添加redis库
	"verify_code": { 
		"BACKEND": "django_redis.cache.RedisCache",
		"LOCATION": "redis://127.0.0.1:6379/1",
		"OPTIONS": { 
			"CLIENT_CLASS": "django_redis.client.DefaultClient",
		},
	},
}
    原文作者:李玉斧
    原文地址: https://blog.csdn.net/weixin_43129747/article/details/104591385
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞