Twenty-six .ajax login authentication code (session)

A. Ajax login authentication code

https://download.csdn.net/download/baobao267/10722491 Django's Form Ajax Form Validation and authentication summary
https://download.csdn.net/download/baobao267/10722491 Django's Form Ajax Form Validation and authentication summary 
HTTPS: //blog.csdn.net/HFZeng/article/details/98654307 
HTTPS: //blog.csdn. NET / kkorkk / Article This article was / Details / 80,150,644 
HTTPS: //www.jb51.net/article/165394 .htm 
HTTPS: //segmentfault.com/q/1010000009345281 
HTTPS: //blog.csdn.net/huangql517/article/details / 81259011

 

 templates

<!DOCTYPE html> <html lang="en"> <head> {% load staticfiles %} <meta charset="UTF-8"> <title>login</title> <link rel="stylesheet" type="text/css" href="{%static 'css/bootstrap.min.css'%}"> <script type="text/javascript" src="{%static 'js/jq.js'%}"></script> </head> <body> <h3 style="text-align: center">登录页面</h3> <div class="container"> <div class="row"> <div class="col-md-8 col-md-offset-2"> <form method="post" action=" "> {% csrf_token %} <div class="form-group"> <label for="user">用户:</label> <input type="text" class="form-control" name="user" id="user"> </div> <div class="form-group"> <label for="pwd">密码:</label> <input type="password" class="form-control" name="pwd" id="pwd"> </div> <div class="form-group"> <label for="#">验证:</label> <div class="row"> <div class="col-md-6"> <input type="text" class="form-control" name="code" id="code"> </div> <div class="col-md-6"> {# <img style="width:200px;height:37px; border-radius:3px;" src="{%static 'img/11.png'%}">#} <img style="width:160px;height:35px; border-radius:3px;" src="Picture"alt ="/ get_img /" id="img"> </div> </div> </div> <button class="btn btn-success pull-right" id="login_btn">登录</button> <span class="errs"></span> </form> </div> </div> </div> <script> $("#login_btn").click(function () { var user=$("#user").val(); var pwd=$("#pwd").val(); var code=$("#code").val(); var csl=$("[name='csrfmiddlewaretoken']").val(); $.ajax({ url:"/login/", type:"post", data:{"user":user,"pwd":pwd,"code":code,"csl":csl}, success:function (arg) { console.log(arg,typeof(arg)) if (arg.user){ {#登录成功了#} location.href="www.baidu.com" }else { {#失败#} $(".errs").html(arg.msg_err).css("color","red") } } }); {#<input type="hidden" name="csrfmiddlewaretoken" value="Sr7qsq3Y854eUp0Ef6vq3d7sO0joJmH6IMbU10ZNIrTnVh2WQdd48Nby4uTlo8AH">#} }); {#点击验证码刷新#} $("#img").click(function () { this.src+="?" }); </script> </body> </html>
views

from
django.shortcuts import render,HttpResponse from django.http import JsonResponse import random from django.contrib import auth def login(request): if request.method=="POST": # ===> request.is_ajax(): user=request.POST.get("user") pwd = request.POST.get("pwd") code = request.POST.get("code") print(user,pwd,code,"111111111111") # AJAX请求返回字典 response={"user":None,"msg_err":""} if code.upper()==request.session.get("keep_str").upper(): user_obj=auth.authenticate(username=user,password=pwd) if user_obj: response["user"]=user else: Response [ " msg_err " ] = " user name or password error !!!! " the else : Response [ " msg_err " ] = " Incorrect code !! " return jsonResponse (Response) the else : return the render (Request, " 01html / 01login .html " ) code DEF get_img (Request): # one way: to read the specified picture local disk # with Open (" myapp / statics / img / 11.png "," rb ") AS f1: # the Data = f1.read() # return HttpResponse(data) # Second way: read the specified images to create a verification code to generate images on a local disk from PIL import Image in reading the image based pollow module # from PIL import Image # DEF get_random_color (): Get Picture # random colors # return (Random. the randint (0,255), the random.randint (0,255), the random.randint (0,255)) # img_png = Image.new ( "the RGB", (350,60), get_random_color ()) # F1 = Open ( "MyApp / statics to / IMG / aa.png "," WB ") # img_png.save (F1," PNG ") # with Open (" MyApp / statics to / IMG / aa.png "," RB ") AS F1: # Data = F1. Read () # return the HttpResponse (Data) # three ways: generating a picture in the memory on the memory modules using memory IO Import as BinaryIO from from the PIL ImportImage, ImageDraw, ImageFont from IO Import BytesIO DEF get_random_color (): # Get Picture random colors return (random.randint (0,255), random.randint (0,255), random.randint (0,255 )) img_png = Image.new ( " RGB " , (200,38), get_random_color ()) # corresponds to give a artboards Draw = ImageDraw.Draw (img_png) # corresponds to give a brush font = ImageFont.truetype ( " MyApp / statics to / font / aaa.ttf " , 25 ) keep_str = "" for I in Range (. 6): random_num=str(random.randint(0,9)) random_lowalf = chr(random.randint(97, 122)) random_upperf = chr(random.randint(65,90)) random_chr=random.choice([random_num,random_lowalf,random_upperf]) draw.text((i*20+40,5), random_chr,get_random_color(),font=font) keep_str+=random_chr # 噪点燥线 width=200 height=38 for i in range(6): x1=random.randint(0,width) x2 = random.randint(0, width) y1=random.randint(0,height) y2 = random.randint(0, height) draw.line((x1,y1,x2,y2),fill=get_random_color()) for i in range(20): 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()) # 内存写与读 f=BytesIO () img_png.save (F, " PNG " ) Data = f.getvalue () Print (keep_str, " 1111111111111 " ) # verification code stored in the respective session makes request.session [ " keep_str " ] = keep_str return the HttpResponse (Data)
urls
from
django.contrib import admin from django.urls import path from home import index from myapp import views urlpatterns = [ path('admin/', admin.site.urls), path('', index.index), path('login/', views.login), path('get_img/', views.get_img), ]

 2. random codes

DEF get_img (Request):
     # one way: to read the specified picture Local Disk 
    # with Open ( "myapp / statics / img / 11.png", "rb") AS f1: 
    #       the Data = f1.read () 
    #   return HttpResponse (the Data) 


   # Second way: read the specified images to create a verification code to generate images on a local disk from PIL import Image in reading the image based pollow module 
   # from PIL import Image 
   # DEF get_random_color (): get picture # random colors 
   #           return (random.randint (0,255), random.randint (0,255), random.randint (0,255)) 
   # img_png = Image.new ( "RGB", (350,60), get_random_color ()) 
   # f1 = Open ( "myapp /statics/img/aa.png","wb ") 
   # img_png.save (f1," PNG ") 
   #Open with ( "MyApp / statics to / IMG / aa.png", "RB") AS F1: 
   #      Data = f1.read () 
   # return the HttpResponse (Data) 


   # Three ways: generating a picture in the memory on the memory use memory module IO Import BinaryIO from 
    from PIL Import Image, ImageDraw, ImageFont
     from   IO Import BytesIO
     Import random
     DEF get_random_color ():   # get picture random colors 
             return (random.randint (0,255), random.randint (0,255), random.randint (0,255 )) 
    img_png = Image.new ( " the RGB " , (200,38), get_random_color ())     # corresponds to give a artboards
    = ImageDraw.Draw Draw (img_png)     #   corresponds to give a brush 
    font = ImageFont.truetype ( " MyApp / statics to / font / aaa.ttf " , 25 ) 
    keep_str = "" 
    for I in Range (. 6 ): 
        random_num = STR ( the random.randint (0,9 )) 
        random_lowalf = CHR (the random.randint (97, 122 )) 
        random_upperf = CHR (the random.randint (65, 90, )) 
        random_chr = The random.choice ([random_num, random_lowalf, random_upperf]) 
        Draw .text ((I * 20 is + 40,5), random_chr, get_random_color (), font = font)
        keep_str+=random_chr
    # 噪点燥线
    width=200
    height=38
    for i in range(6):
        x1=random.randint(0,width)
        x2 = random.randint(0, width)
        y1=random.randint(0,height)
        y2 = random.randint(0, height)
        draw.line((x1,y1,x2,y2),fill=get_random_color())
    for i in range(20):
        draw.point([random.randint(0,width),random.randint(0,height)],fill=get_random_color ()) 
        X = the random.randint (0, width) 
        Y = the random.randint (0, height) 
        draw.arc ((X, Y, X +. 4, + Y. 4), 0,90, Fill = get_random_color ( ))
     # memory write and read 
    F = BytesIO () 
    img_png.save (F, " PNG " ) 
    Data = f.getvalue ()
     Print (keep_str, " 1111111111111 " )
     # verification code stored in the respective session 
    request.session [ " keep_str " ] = keep_str
     return the HttpResponse (Data)


 

 

Guess you like

Origin www.cnblogs.com/lovershowtime/p/11482222.html