• python-Web-django-图形验证



    import
    random def get_random_color(): return (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)) def get_valid_code_img(request): # 方式1: # with open("lufei.jpg","rb") as f: # data=f.read() # 方式2: # pip install pillow # from PIL import Image # img=Image.new("RGB",(270,40),color=get_random_color()) # # with open("validCode.png","wb") as f: # img.save(f,"png") # # with open("validCode.png","rb") as f: # data=f.read() # 方式3: # from PIL import Image # from io import BytesIO # # img=Image.new("RGB",(270,40),color=get_random_color()) # f=BytesIO() # img.save(f,"png") # data=f.getvalue() # 方式4: from PIL import Image, ImageDraw, ImageFont from io import BytesIO import random img = Image.new("RGB", (270, 40), color=get_random_color())#生成一个宽270*高40的画布,背景颜色随机 draw = ImageDraw.Draw(img)#进行绘画 kumo_font = ImageFont.truetype("../static/font/ahronbd.ttf", size=42)#字体 字体大小 valid_code_str = "" for i in range(4): random_num = str(random.randint(0, 9))#0-9的随机数 9 random_low_alpha = chr(random.randint(97, 122))#a 到 z 随机的一个小写字母 b random_upper_alpha = chr(random.randint(65, 90))#A 到 Z 随机的一个大写字母 Q random_char = random.choice([random_num, random_low_alpha, random_upper_alpha]) #2 draw.text((i * 50 + 20, 5), random_char, get_random_color(), font=kumo_font) #往长方形上写字 # 保存验证码字符串 valid_code_str += random_char #85656 # width=270 height=40 # for i in range(10): # x1=random.randint(0,width) # y1=random.randint(0,height) # x2=random.randint(0,width) # y2=random.randint(0,height) # draw.line((x1,y1,x2,y2),fill=get_random_color()) #画线 # # for i in range(10): # draw.point([random.randint(0, width), random.randint(0, height)], fill=get_random_color())#画小点 x = random.randint(0, width) y = random.randint(0, height) draw.arc((x, y, x + 4, y + 4), 0, 90, fill=get_random_color()) #小线段 request.session["valid_code_str"] = valid_code_str.upper() ''' 1 sdajsdq33asdasd 2 COOKIE {"sessionid":sdajsdq33asdasd} 3 django-session session-key session-data sdajsdq33asdasd {"valid_code_str":"12345"} ''' f = BytesIO() img.save(f, "png") #png data = f.getvalue() return data

     views:

    from django.shortcuts import render,HttpResponse,redirect
    import json
    from app01.models import *
    
    def login(request):
        ''''''
        res = {'s': None, 'info': None}
        if request.method == 'POST':
            print(request.POST)
            username = request.POST.get('LoginName')
            pwd = request.POST.get('Password')
            code = request.POST.get('code')
            code = code.upper()
            if code != request.session['valid_code_str']:
                '''验证码输入错误'''
                res['s'] = 0
                res['info'] = '验证码输入错误'
                print(res)
                return HttpResponse(json.dumps(res))
    
            manage_obj = Manage.objects.filter(name=username, pwd=pwd).first()
            print(manage_obj)
            if not manage_obj:
                res['s'] = 0
                res['info'] = '登陆失败'
                print(2)
                print(res)
                return HttpResponse(json.dumps(res))
            request.session['manage_name'] = manage_obj.name
            request.session['manage_id'] = manage_obj.id
            print(3)
            res['s'] = 1
            res['info'] = '登陆成功'
            print(2)
            print(res)
            return HttpResponse(json.dumps(res))
    
        return render(request,'index/login.html',locals())
    
    def login2(request):
        '''图像码'''
        from app01.utils import validCode
        vc = validCode.get_valid_code_img(request)
        print(request.session['valid_code_str'])
        return HttpResponse(vc, 'image/png')
    
    
    from back.views.ddff import ddff
    @ddff
    def out(request):
        '''退出'''
        a = 'User, you have successfully quit, welcome to use next time'
        del request.session['manage_name']
        del request.session['manage_id']
        return render(request, 'index/login.html', locals())

    html:

    <form action="" method="post">
                    {% csrf_token %}
                        <ul>
                <li><input name="LoginName" type="text" class="loginuser" placeholder="admin"/></li>
                <li><input name="Password" type="text" class="loginpwd" placeholder="密码"/></li>
                <li class="yzm" style="230px;height:60px ;">
                    <span><input name="code" type="text" placeholder="验证码"/><img width="115" height="46" id="valid_code_img" src="/back/login/login2/" alt="" onclick="this.src='/back/login/login2/?'+Math.random()" style="position: absolute;"></span>
    
                </li>
    
                <li>
                    <input id="submitBtn" type="button" class="loginbtn" value="登录"/>
                    <label><input name="" type="checkbox" value="" checked="checked" />记住密码</label>
    {#                <label><a href="#">忘记密码?</a></label>#}
                </li>
            </ul>
                </form>
    
    <script>
        $(document).ready(function () {
            $("#submitBtn").click( function () {
                // 点击事件
                $.post("/back/login/login/",$('form').serialize() , function (data) {
                    //LoginName,Password,code
                    if (data['s'] == 1) {
                        layer.msg("登录成功!");
                        // 跳转主页面
                        location.href="{% url 'back:index/index/' %}";
                    } else {
                        //登陆失败
                        layer.msg(data['info']);
                    }
                    return false;
                    }, "json");
    
            })
        })
    </script>
  • 相关阅读:
    在排序数组中查找元素
    搜索旋转排序数组
    下一个排列
    括号生成(回溯法)
    PHP之表单
    PHP之超级全局变量
    PHP之数组
    PHP之字符串
    PHP之常量
    PHP之echo/print
  • 原文地址:https://www.cnblogs.com/person1-0-1/p/11318972.html
Copyright © 2020-2023  润新知