Python Basics (Django second article)

Source: Internet
Author: User

One, the Django routing system

Description: The URL for each request in Django must have a corresponding function to handle, and when the request arrives, it will match the rule from top to bottom according to the urls.py file configuration, and a match will no longer match down.

Configuration file: urls.py

How to configure:

Static routes: A URL corresponds to a function in the views.

Example: URL (r ' ^index/$ ', Views.index),

Dynamic routing: Multiple URLs correspond to a function in the views, where the URLs are more regular matches.

Example: URL (r ' ^index/(. *)/$ ', Views.index),

Default route: When all rules above this rule are not matched, it will eventually match all. Typically used to handle situations where the request address does not exist.

Example: URL (r '. * ', Views.warn),


Second, Django Middleware

Description: In Django Middleware (middleware), in Django, middleware is actually a class, and after the request arrives and ends, Django executes the appropriate method in the middleware at the right time according to its own rules.

Configuration file: settings.py

How to configure:

Middleware_classes = (The middleware is all that is configured)

Middleware can be customized, and the meaning of customization is that you can make some custom processing operations when each request is reached or returned. such as log records, IP restrictions, and so on.

However, no description is made here.


Third, Django Cache

Description: The meaning of caching is caching (sounds like nonsense).

1. Configuration (added in settings.py)

CACHES = {

' Default ': {

' Backend ': ' Django.core.cache.backends.filebased.FileBasedCache ', #使用文件缓存

' Location ': Os.path.join (base_dir, ' cache '), #文件名为cache

' TIMEOUT ': #缓存超时时间为600秒

' OPTIONS ': {

' Max_entries ': #最大缓存条目数为1000

}

}

}

2. Application

From django.shortcuts import Render, HttpResponse

From Django.views.decorators.cache import Cache_page

@cache_page #以装饰器的形式配置, on which function to cache the data of which function return

def func (Request):

return HttpResponse (' xxx ')


Iv. Cookies and session

Description: A cookie is a string that is stored locally on the client (browser) (depending on the type of cookie can be saved in memory or saved on the hard disk).

Session is saved on the server side, storing all the information with the client session.

What to use in Django:

1, to determine whether the user is logged in

2, according to different users to return different content

Working principle:

When the client (browser) accesses the server, the server creates a seesion for this session and generates a unique sessionid that uses the SessionID as an identifier to access the server-side session storage space. And SessionID this data is saved to the client, that is, stored in the cookie, the user submits the request, will also submit the SessionID to the server side, to access the session data. This process is not a developer intervention. So once the client disables cookies, the session will also expire.

Usage:

1, request.session[' username '] = Username #往session中存储一个值 (Key,value way to store)

2, Request.session.get (' username ') #根据key从session中获取一个值

3, del request.session[' username '] #根据key从session中删除一个值


V. Form

Description: Django's form has two functions:

1. Verify user input

2. Output HTML

Example:

views.py

From django.shortcuts import render, render_to_responsefrom django.http import  httpresponse,httpresponseredirectfrom django import forms    # Import the Forms Module Class userinfo (forms. Form):     #定义一个类   classes inherit forms. Form    email = forms. Emailfield (required=false)      #required =false indicates that the field can be empty     name =  forms. Charfield ()     pwd = forms. Charfield () Def login (req):     obj = userinfo ()     # Instantiate an object     if req.method ==  ' POST ':         user_input_obj = userinfo (req. POST)      #获取form生成的整个html代码以及客户端输入的内容         if  user_input_obj.is_valid ():         #is_valid方法用于判断客户端提交的内If the tolerance is not available (for example, if it cannot be empty)             data =  User_input_obj.clean ()      #获取客户端手动输入的内容 (dictionary form)              if data[' name '] ==  ' Test '  and data[' pwd '] ==  ' 123 ':                 req.session[' Is_login '] = true     #往session中存储一个值                  return httpresponseredirect ('/home/')             else:                 return httpresponse (' Login error  ! ')         else:             error_msg = user_input_obj.errors     #客户端输入错误的提示信息              return render_to_response (' login.html ', {' obj ': user_input_obj, ' Errors ' : error_msg})     return render_to_response (' login.html ', {' obj ': obj})

Login.html

<! Doctype html>

this blog part of the content and ideas organized from Wu Jianzi blog .

This article from "A rookie on the Sky" blog, please be sure to keep this source http://rmeos.blog.51cto.com/761575/1752521

Python Basics (Django second article)

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.