Django关于图片验证码显示笔记

1.访问页面 /login/
    - 内部需要创建一张图片,并且给用户返回
    - 创建一个白板 Session存放验证码

2.POST
    - 根据用户提交的数据与session里面比较

3.登录界面 和 验证码 分开URL

1:创建一张图片 pip3 install Pillow
2:在图片中写入一个随机字符串
obj = object() #对象内部包含图片信息
3.将图片写入到指定文件
4.打开指定目录文件, 读取内容
5.HttpResponse(data)
6.session
7.check_code.py(依赖:Pillow, 字体文件)
src属性后面加上? 点击验证码就会刷新

img, code = create_validate_code()
print(img, code)
f = open('xxx.png', 'wb')
img.save(f, 'PNG')
return HttpResponse(open('xxx.png','rb').read())   这是写入到文件

from io import BytesIO  #字节的io操作  在内存开辟空间 进行写和读
stream = BytesIO()
img, code = create_validate_code()
img.save(stream,"PNG")
request.session['CheckCode'] = code
return HttpResponse(stream.getvalue())   #从内存读取

def login(request):
    """
    登录
    """
    if request.method == "POST":
        if request.session['CheckCode'].upper() == request.POST.get('check_code').upper():
            print("验证码成功")

        else:
            print('验证码错误')

    return render(request, 'login.html')

 <img src = '/check_code.html' onclick = "changeCheckCode(this)">

 <script>
    function changeCheckCode(ths){
        ths.src = ths.src + "?"; #URL需要改一下 浏览器才会改变 机智的写法
    }
 <script>

猜你喜欢

转载自www.cnblogs.com/Liang-jc/p/9265850.html