Django之验证码 + session 认证
. └── project ├── app01 │ ├── admin.py │ ├── apps.py │ ├── __init__.py │ ├── migrations │ │ └── __init__.py │ ├── models.py │ ├── tests.py │ └── views.py ├── backend │ ├── check_code.py │ └── __init__.py ├── db.sqlite3 ├── manage.py ├── Monaco.ttf ├── project │ ├── __init__.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── static │ └── jquery │ └── jquery-1.12.4.js └── templates └── login.html
相关文件
代码
- login.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> </head> <body> <form action="/login/" method="POST"> <input type="text" name="username" /> <input type="text" name="pwd" /> <input type="text" name="check_code" /> <img src="/check_code/" onclick="ChangeCode(this);"> <input type="submit" /> </form> <script> function ChangeCode(this){ ths.src = ths.src + '?'; } </script> </body> </html>
- views.py
from django.shortcuts import render from django.shortcuts import HttpResponse import os import json import io from backend import check_code as CheckCode # Create your views here. def check_code(request): """ 生成图片,将图片上的文字保存到session中 将图片内容返回给用户 :param request: :return: """ stream = io.BytesIO() # img图片对象,code在图像中写的内容 img, code = CheckCode.create_validate_code() img.save(stream, "png") request.session["CheckCode"] = code # 放入到session中 return HttpResponse(stream.getvalue()) def login(request): if request.method == "POST": input_code = request.POST.get("check_code") print(input_code.upper(), request.session['CheckCode'].upper()) return render(request, "login.html")
posted on 2019-04-26 13:10 与落霞齐飞12138 阅读(155) 评论(0) 编辑 收藏 举报