The path to learning in Python -2018/7/11

Source: Internet
Author: User

The path to learning in Python -2018/7/10 3. Feature Development 3.1 Login verification login.html
<! DOCTYPE html>
views.py
From django.shortcuts import Render, Httpresponsefrom django.http import Jsonresponsefrom django.views.decorators.csrf  Import csrf_exemptfrom django.contrib Import authfrom blog.utils.verify_code import * @csrf_exemptdef login (Request): if Request.method = = "GET": Return render (Request, "login.html") elif Request.method = = ' POST ': username = Request. Post.get ("username") Password = Request. Post.get ("password") Verify_codes = Request. Post.get ("Verify_code") Verify_code_str = Request.session.get ("verify_code_str") response = {"User": None, " MSG ": None} if verify_codes.upper () = = Verify_code_str.upper (): User = Auth.authenticate (username=userna Me, Password=password) if User:auth.login (request, user) response["user"] = user . Username else:response["MSG"] = "username or password error!" "else:response[" msg "] =" CAPTCHA Error! "Return Jsonresponse (response) def VErify_code (Request): data = Get_verify_code (Request) return HttpResponse (data) def index (request): Return render (R Equest, "index.html")
verify_code.py
Import randomfrom PIL import Image, Imagedraw, Imagefont, imagefilterfrom io import bytesiodef random_color (): color =  (Random.randint (255), random.randint (+, 255), Random.randint (+, 255)) return Colordef Random_color2 (): color = (Random.randint (+, 127), Random.randint (+, 127), Random.randint (+, 127)) return Colordef Random_char (): "" "with  Number of machines/letters "" "Random_num = str (random.randint (0, 9)) Random_low = Chr (random.randint (122)) # A~z Random_upper = Chr (Random.randint (+)) # A~z random_chars = Random.choice ([Random_num, Random_low, Random_upper]) return RA    Ndom_charsdef Get_verify_code (Request): "" "Dynamically Generate Captcha" "" Image = Image.new ("RGB", (183, 40), (255, 255, 255))    Image_font = Imagefont.truetype ("Static/blog/font/arial.ttf", +) Draw = Imagedraw.draw (image) # Fill in the color for each coordinate, fill the noise For x in range (183):-Y in range: Draw.point ((x, y), Fill=random_color ()) Verify_code_str = " "For I in Range (5):       Random_chars = Random_char () verify_code_str + = Random_chars draw.text ((20+i*30, 0), Random_chars, fo  Nt=image_font, Fill=random_color2 ()) image = Image.filter (imagefilter.blur) # obfuscation # placed on disk, but slower, recommended in memory #     With open ("Verify_code.png", "WB") as F: # Image.Save (f) # # with open ("Verify_code.png", "RB") as F: #    data = F.read () request.session["verify_code_str"] = verify_code_str f = Bytesio () image.save (F, "PNG") data = F.getvalue () return data

The login interface effect looks like this:

Summarize:
    1. A request is accompanied by multiple static requests, such as a request for a CSS file
    2. Using PIL module to make verification code dynamically
    3. The verification code uses session storage (session first generates a SessionID, then stores the SessionID in the cookie, and then inserts the data into the session table, including SessionID and session content, A browser corresponding to a session data)
    4. Verification code Refresh, each time you click the Verification feature picture, at the end of its src add?, so that each click on the image will refresh the verification code
    5. Follow the "high coupling low cohesion" principle to store the ability to dynamically generate verification codes in another py file
Advanced-Sliding Verification code

First you need to install the Social-auth-app-django module

pip install social-auth-app-django

Then download the geetest.py from https://github.com/GeeTeam/gt-python-sdk/and put it in the project

Login.html

<! DOCTYPE html>

Blog.css

a:hover { cursor: pointer; text-decoration: none;}.login-head { margin-bottom: 10px; border-bottom: 1px solid #ddd;}.login-head a { margin-left: 287px; color: #5cb85c;}

Blog.js

var handlerpopup = function (captchaobj) {//successful callback captchaobj.onsuccess (function () {var validate = Captcha Obj.getvalidate (); $.ajax ({url: "/login/",//two validation type: "Post", DataType: "JSON", data: { Username: $ (' #username '). Val (), Password: $ (' #password '). Val (), Geetest_challeng E:validate.geetest_challenge, Geetest_validate:validate.geetest_validate, Geetest_seccode: Validate.geetest_seccode}, Success:function (data) {if (data["user"]) { Location.href = "/index/"} else {$ ("#error"). html (data["MSG"]). CSS ({"Color": "Red"})//Hint error message}}); }); $ (". Login-btn"). Click (function () {captchaobj.show (); }); Add the verification code to the element with ID captcha captchaobj.appendto ("#popup-captcha"); More Interface Reference: HTTP://Www.geetest.com/install/sections/idx-client-sdk.html};//validation begins with the need to get id,challenge,success (whether failback enabled) to the site master $.ajax ( {URL: "/pc-geetest/register?t=" + (new Date ()). GetTime (),//plus random number to prevent cache type: "Get", DataType: "JSON", success: function (data) {//using Initgeetest interface//Parameter 1: Configuration parameters//Parameter 2: Callback, Callback's first parameter Authenticode object, which can then be used to do events such as Appendto Initgeetest ({gt:data.gt, challenge:data.challenge, Product: "Popup",//Products form, including: Floa T,embed,popup. Note Only for the PC version of the verification code valid offline:!data.success//indicates that the user background detection of the server is down, generally do not need to pay attention//More configuration parameters See: http://www.geetest.com /install/sections/idx-client-sdk.html#config}, Handlerpopup); }});

views.py

from django.http import JsonResponsefrom django.views.decorators.csrf import csrf_exemptfrom blog.utils.geetest import GeetestLibfrom django.contrib import auth@csrf_exemptdef login(request): if request.method == "GET": return render(request, "login.html") elif request.method == ‘POST‘: # 滑动验证码,利用geetest插件 gt = GeetestLib(pc_geetest_id, pc_geetest_key) status = request.session[gt.GT_STATUS_SESSION_KEY] username = request.POST.get("username") password = request.POST.get("password") response = {"user": None, "msg": None} if status: user = auth.authenticate(username=username, password=password) if user: auth.login(request, user) response["user"] = user.username else: response["msg"] = "用户名或者密码错误!" return JsonResponse(response)

Display effect:

3.2 Members

First create the Media folder in the project, create the Avatars folder in the media directory, this file mainly contains the files uploaded by the user

Django has two static files, static and media,static mainly store the server's own files such as js,css,img, while media mainly store users upload files.

We need to configure the media information in the settings MEDIA_ROOT = os.path.join(BASE_DIR, "media") and configure it to be stored in the/media/avatars directory each time the user uploads the file, Django will automatically create the directory if the user does not create the Avatars directory.

Register.html
{% extends "login.html" %}{% block head %}    

Blog.css
#avatar_img {    width: 60px;    height: 60px;    margin-left: 20px;}.error{    color: red;}
Blog.js
The input tag content changes event, which is the Avatar upload $ ("#avatar"). Change (function () {var file = $ (this) [0].files[0];  Get picture path var reader = new FileReader ();  Text Reader Reader.readasdataurl (file); The path of the Read file Reader.onload = function () {$ ("#avatar_img"). attr ("src", reader.result)//The path of the picture is written to the IMG tag in SRC});    Registered user $ (". Reg-btn"). Click (function () {var formdata = new Formdata ();  var request_list = $ ("#form"). Serializearray ();         Name and Value $.each (request_list, function (index, data) {Formdata.append (Data.name, data.value) that contain all the labels in the form form            /* Equivalent to: formdata.append ("username", $ ("#id_username"). Val ());            Formdata.append ("Password", $ ("#id_password"). Val ());            Formdata.append ("Re_password", $ ("#id_re_password"). Val ());        Formdata.append ("Email", $ ("#id_email"). Val ());    */    });    Formdata.append ("Avatar", $ ("#avatar") [0].files[0]);        $.ajax ({url: "/register/", type: "POST", contenttype:false,//must add parameterProcessdata:false,//must add parameter Data:formdata, success:function (data) {$ ("Span.error"). HTML ("");  Remove the last error message $ (". Has-error"). Removeclass ("Has-error");            Remove the last Error message box style if (data.user) {location.href = "/login/"//register successfully return to login interface}                else {var error_list = data.msg; $.each (Error_list, Function (field, error) {if (field = = "__all__") {$ ("#id_re_ Password "). Next (). HTML (Error[0]). Parent (). addclass (" Has-error ")//individual handling of global hooks} $ ("  #id_ "+ field"). Next (). HTML (error[0]);  Locate the span label after the input tag for the corresponding ID and write the error message to $ ("#id_" + field). Parent (). addclass ("Has-error"); Add CSS style} to input tag with error message})});
my_forms.py
From Django Import formsfrom. Models import *from django.core.exceptions Import validationerrorwid_1 = Forms.widgets.Text Input (attrs={"class": "Form-control", "AutoComplete": "Off"}) Wid_2 = Forms.widgets.PasswordInput (attrs={"class": " Form-control "}) class UserForm (forms. Form): username = forms. Charfield (max_length=32, label= "user name", widget=wid_1, error_messages={"required": "The field cannot be empty! }) Password = forms. Charfield (min_length=8, label= "password", Widget=wid_2, error_messages={"min_length": "Password length at least 8 bits! "," required ":" The field cannot be empty! }) Re_password = forms. Charfield (min_length=8, label= "Confirm password", widget=wid_2, error_messages={"min_length": "Password length at least 8 bit! "," required ":" The field cannot be empty! "}") email = forms. Emailfield (label= "Mailbox", Widget=wid_1, error_messages={"invalid": "Bad mailbox format! "}) def Clean_usernaMe (self): username = self.cleaned_data.get ("username") user = User.objects.filter (username=username) If not User:return username else:raise validationerror ("The user has been registered! ") def clean: password = self.cleaned_data.get (" password ") Re_password = Self.cleaned_data.get (" Re_ Password ") if password = = Re_password:return Self.cleaned_data else:raise Validation Error ("Two times password inconsistent!") ")
views.py
from blog.my_forms import *def register(request):    user = UserForm()    if request.method == "GET":        return render(request, "register.html", locals())    elif request.method == "POST":        response = {"user": None, "msg": None}        user = UserForm(request.POST)        if user.is_valid():            username = user.cleaned_data.get("username")            response["user"] = username            password = user.cleaned_data.get("password")            email = user.cleaned_data.get("email")            avatar_obj = request.FILES.get("avatar")            if avatar_obj:  # 如果用户上传了头像,则创建用户时将其传入,没有则传递其他填写的信息                user_obj = User.objects.create_user(username, email, password, avatar=avatar_obj)            else:                user_obj = User.objects.create_user(username, email, password)        else:            response["msg"] = user.errors  # 包含了所有的错误信息        return JsonResponse(response)

Display effect:

Summarize:
    1. Label label to add a for property (the content is the ID of a tag), click the label equivalent to click the tag in the For property. With this feature, the file upload input is hidden, a label is added to its binding, and an IMG is added to the label, so clicking on the image will allow the file to be uploaded.
    2. The path to the file is passed $(xx)[0].files[0] to get
    3. The implementation of the upload Avatar Preview is divided into three main steps, the first to get the path of the picture, the second step to read the path of the picture, the third step to write the picture path to the IMG tag
    4. The readasdataurl in the text reader is asynchronous, so there is no way to read the picture path is written, resulting in a Unknow object, so you need to use the OnLoad method, OnLoad will run after all the resources have been loaded.
    5. You need to use Formdata when uploading a file, you must add contentType: false,processData: false the two parameters in Ajax when using Formdata
    6. When inserting data into formdata, you can reduce the $("xxx").serializeArray() amount of code by looping through (containing the name and value of all the input boxes in the form form)
    7. Media configuration, the server's files are stored in static, the user uploaded files stored in the Media/avatars

The path to learning in Python -2018/7/11

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.