Django view function of three basic

Django view function of three basic

A view Django view function

A view function (class), referred to as a view, Python is a simple function (class) that accepts the request and returns Web Web response.

The response may be a page's HTML content, a redirect, a 404 error, an XML document, or a picture.

No matter what the view itself contains logic, it must return a response. Write the code where it does not matter, as long as it is in your current directory project. In addition there is no more requirement - and you can say, "There's nothing magical place." In order to put the code in the name somewhere, we agreed to a vulgar place the view in the project (project) or application (app) directory views.pyfile.

A simple view

  Here is a view returns the current date and time in the form of an HTML document:

from django.http import HttpResponse
import datetime

def current_datetime(request):
    now = datetime.datetime.now()
    html = "<html><body>It is now %s.</body></html>" % now
    return HttpResponse(html)

Let's explain the above code line by line:

  • First of all, from the django.httpimported module HttpResponseclass, as well as the Python datetimelibrary.

  • Then, we define the current_datetimefunction. It is the view function. Each view function using HttpRequestan object as the first parameter, and is commonly known request.

    Note that the name of the view function does not matter; do not need a unified approach to naming names, in order to allow Django to recognize it. We will name it current_datetime, because this name can more accurately reflect the function it implements.

  • This view will return an HttpResponseobject that contains the generated response. Each view function is responsible for returning an HttpResponseobject.

  Django uses request and response state objects to pass through the system.

  When a browser requests a page from the server, Django create an HttpRequest object that contains metadata about the request. Then, Django loads the appropriate view, this view HttpRequest object to function as the first parameter.

  Each view is responsible for returning an HttpResponse object. View layer, to master two objects: Object Request (request) and response objects (the HttpResponse)

Two CBV and FBV

FBV (function base views) is to use the processing functions in the view request.

    Before FBV mode are written in code, so I do not write the examples.

CBV (class base views) is used in the view request handling.

  Python is an object-oriented programming language, if only a function to develop, there are many advantages of object-oriented missing out (inheritance, encapsulation, polymorphism). So Django later joined the Class-Based-View. It allows us to use the class to write View. The advantage of this is mainly the following two:

  1. Improve the reusability of code, object-oriented techniques may be used, such as Mixin (multiple inheritance)
  2. May be processed for various different functions HTTP method, in many if not determining, improve code readability

If we want to write a view GET method of treatment, then write a function like this below.

def login(request):
   if request.method == 'GET':
      return render(request, 'login.html')

If you write a class-based view, then, it is this:

#类写法:
class LoginView(View):
   def get(self,request):
      print('get方法执行了')
      return render(request,'login2.html')
    def post(self,request):
        username=request.POST.get('username')
        password=request.POST.get('password')
        print('post方法执行了')
        print(username,password)
        return HttpResponse('cg')

Django's request url is assigned to a function call, rather than a class. To address this issue, class-based view provides a as_view()static method (that is, the class method), calling this method creates an instance of a class, then by example calling dispatch()method, dispatch()the method will be based on the respective different call method of request method processing request (eg get(), post()etc.). Here, the methods and almost function-based view, to be received request, to obtain a response returned. If the method is not defined, an exception will be thrown HttpResponseNotAllowed.

    Note : When using CBV, urls.py also make the corresponding changes ::

from django.conf.urls import url,include
from django.contrib import admin
from app01 import views

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^login2/$', LoginView.as_view()),

]

 CBV parameter passing, FBV, and the like, known packets, packet unknown

    url writing: unknown packets

 url(r'^cv/(\d{2})/', views.Myd.as_view(),name='cv'),
 url(r'^cv/(?P<n>\d{2})/', views.Myd.as_view(name='xxx'),name='cv'),#如果想给类的name属性赋值,前提你的Myd类里面必须有name属性(类属性,定义init方法来接受属性行不通,但是可以自行研究一下,看看如何行通,意义不大),并且之前类里面的name属性的值会被覆盖掉

Three using Mixin (understand)

I feel the need to understand django of class-based-view (hereinafter referred to as cbv), we must first understand what the purpose of introducing cbv of django Yes. Before django1.3, generic view so-called generic view, the use of function-based-view (fbv), i.e. view Function. Some people think fbv more pythonic than cbv, I humbly believe otherwise. One of the important characteristics of python is object-oriented. The cbv better reflect the python object-oriented. cbv view is achieved by a method of the class manner. function with respect to the class, the more specific use of polymorphism, it is easier to abstract from the more common functions within the program on the macro level. About polymorphism, not much explanation, interested students own Google. In short it can be understood as a thing with a variety of forms (properties). The principle by looking CBV django source it is readily apparent, generally by the url is then routed to the CBV, distributed through the inside of the dispatch methods CBV, the get request cbv.get distributed processing method, the post requests distributed CBV .post method of treatment, similar to other methods. How the use of polymorphism it? cbv was introduced the concept of a mixin. Mixin is written some basic class and become the ultimate desired Mixin class through different combinations.

  So, understanding cbv is based on understanding Mixin. Django Mixin used to reuse code, a View Class can inherit multiple Mixin, but can only inherit a View (including a subclass of View), it is recommended to write the rightmost View, Mixin write more on the left.

Four to the view plus decorator

Decorator decoration FBV

    FBV is itself a function, and so add to the normal function decorators no difference:

from django.shortcuts import render, HttpResponse, redirect
def wrapper(f):
   def innser(*args, **kwargs):
      print('执行前')
      ret = f(*args, **kwargs)
      print('执行后')
      return ret
   return innser

@wrapper
def index(request):
   print('12321')
   return render(request, 'index.html')

Decorator decoration CBV

    Method class independent functions are not identical, the method can not be directly applied to a function of decorator class, we need to first convert it to a method decorators.

    Django provides method_decorator decorative function for converting a method decorator decorators.

def wrapper(f):
   def innser(*args, **kwargs):
      print('执行前')
      ret = f(*args, **kwargs)
      print('执行后')
      return ret

   return innser

from django.views import View
from django.utils.decorators import method_decorator
@method_decorator(wrapper,name='get')
class LoginView(View):
    # 使用CBV时要注意,请求过来后会先执行dispatch()这个方法,如果需要批量对具体的请求处理方法,如get,post等做一些操作的时候,这里我们可以手动改写dispatch方法,这个dispatch方法就和在FBV上加装饰器的效果一样。
    # @method_decorator(wrapper)
    def dispatch(self, request, *args, **kwargs):
        # print('之前')
        ret=super().dispatch(request, *args, **kwargs)
        # print('之后')
        return ret

    # @method_decorator(wrapper)
    def get(self,request):
        print('get方法执行了')
        return render(request,'login2.html')

    # @method_decorator(wrapper)
    def post(self,request):
        username=request.POST.get('username')
        password=request.POST.get('password')
        print('post方法执行了')
        print(username,password)
        return HttpResponse('cg')

Also add a decorator to cbv time (as first understand):

  • In the dispatch added directly inside, so that each function will be executed

    from django.utils.decorators import method_decorator
    
    @method_decorator(login_test)
    def dispatch(self, request, *args, **kwargs):
    res = super(IndexView, self).dispatch(request, *args, **kwargs)
    return res
  • Add each function

    from django.utils.decorators import method_decorator
    
    @method_decorator(login_test)
    def get(self, request, *args, **kwargs):
    return render(request, 'index.html')
  • Directly add the class, behind only to get the name indicates adding decorator

    from django.utils.decorators import method_decorator
    
    @method_decorator(login_test, name='get')

    is added to get get method (in this way if you want to add the plurality of decoration method, a multilayer decorative need to write, a name because the value of this parameter must be a string, and the two methods can not be written simultaneously)

     @method_decorator(login_test, name='post')  post是给post方法加
         class IndexView(View):
        def get(self,request):
          pass
  • You must be imported from django.utils.decorators import method_decorator before adding decorator

  • Add a decorator's format must be @method_decorator (), brackets for the decorator function name

  • Is added to the class name must be declared

  • Note csrf-token decorators particularity, it is only in CBV added dispatch mode above (for later)

  Here it is csrf_token decorators:

  @csrf_protect, forced to current function CSRF prevention function, even if the settings are not provided csrfToken global middleware.

  @csrf_exempt, cancels the current function CSRF prevention function, even if the global settings set in the middleware.

  注意:from django.views.decorators.csrf import csrf_exempt,csrf_protect

Five request object official documents

Property methods associated with the request (request - HttpRequest object)

def index(request): #http相关请求信息---封装--HttpRequest对象

    if request.method == 'GET':
        print(request.body)  #获取post请求提交过来的原始数据
        print(request.GET)   #获取GET请求提交的数据
        # print(request.META)  # 请求头相关信息,就是一个大字典
        print(request.path) #/index/ 路径
        print(request.path_info) #/index/ 路径
        print(request.get_full_path())  #/index/?username=dazhuang&password=123
        
        return render(request,'index.html')
    else:
        print(request.body)  # b'username=dazhuang'
        print(request.POST) #获取POST请求提交的数据
        return HttpResponse('男宾三位,拿好手牌!')

Six response object

Compared with the HttpRequest object is created automatically by Django, HttpResponse objects are our terms of reference of. We write each view will need to be instantiated, fill and return an HttpResponse.

  HttpResponse class located django.http module.

HttpResponse  --- 回复字符串的时候来使用
render --- 回复一个html页面的时候使用
redirect -- 重定向
    示例:
    def login(request):
        if request.method == 'GET':
            return render(request,'login.html')
        else:
            username = request.POST.get('username')
            password = request.POST.get('password')
            if username == 'taibai' and password == 'dsb':
                # return render(request,'home.html')
                return  redirect('/home/')  #重定向
            else:
                return HttpResponse('滚犊子,赶紧去充钱!!!')

    #首页
    def home(request):
        return render(request,'home.html')
    
    
HttpResponse.content:响应内容
HttpResponse.charset:响应内容的编码
HttpResponse.status_code:响应的状态码

redirect (): browser to a 30x status code

  Parameters can be:

  1. A model: The model will be called get_absolute_url()function

   2 a view, may have parameters: the use urlresolvers.reverseto reverse resolve the name

   3. an absolute or relative URL, will remain intact as the redirection location.

   Default returns a temporary redirect; deliver permanent=Truereturns a permanent redirect.

   Example:

You can use a variety of ways redirect()function.

def login(request):
   if request.method == 'GET':
      return render(request, 'login.html')
   else:
      username = request.POST.get('username')
      password = request.POST.get('password')
      if username == 'anwen@123' and password == '123':
         return redirect('/app01/home/')  ##重定向到/app01/home/路径,这也是发送了一个请求,别忘了在上面引入这个redirect类,和render、Httpresponse在一个地方引入
      else:
         return HttpResponse('登录失败!')


def home(request):
   return render(request, 'home.html')
#app01里的 urls.py
from django.conf.urls import url
from app01 import views
urlpatterns=[
   url(r'^$',views.login),
   url(r'^home/',views.home),
]

After a few files above a good job, we restart Django project, and then enter the URL of the landing page, note that the URL you have entered the port and the port you want to start a project like django.

| A click on the submit button, you look at the network which sent several requests: two requests, one is the login request, a request index. |

Further reading: ** key twice requested, with respect to 301 and 302:   

1)301和302的区别。
  301和302状态码都表示重定向,就是说浏览器在拿到服务器返回的这个状态码后会自动跳转到一个新的URL地址,这个地址可以从响应的Location首部中获取
  (用户看到的效果就是他输入的地址A瞬间变成了另一个地址B)——这是它们的共同点。

  他们的不同在于。301表示旧地址A的资源已经被永久地移除了(这个资源不可访问了),搜索引擎在抓取新内容的同时也将旧的网址交换为重定向之后的网址;

  302表示旧地址A的资源还在(仍然可以访问),这个重定向只是临时地从旧地址A跳转到地址B,搜索引擎会抓取新的内容而保存旧的网址。 SEO302好于301

2)重定向原因:
(1)网站调整(如改变网页目录结构);
(2)网页被移到一个新地址;
(3)网页扩展名改变(如应用需要把.php改成.Html或.shtml)。
        这种情况下,如果不做重定向,则用户收藏夹或搜索引擎数据库中旧地址只能让访问客户得到一个404页面错误信息,访问流量白白丧失;再者某些注册了多个域名的
    网站,也需要通过重定向让访问这些域名的用户自动跳转到主站点等。
    
    
    临时重定向(响应状态码:302)和永久重定向(响应状态码:301)对普通用户来说是没什么区别的,它主要面向的是搜索引擎的机器人。
  A页面临时重定向到B页面,那搜索引擎收录的就是A页面。
  A页面永久重定向到B页面,那搜索引擎收录的就是B页面。
  用redirect可以解释APPEND_SLASH的用法!

Guess you like

Origin www.cnblogs.com/an-wen/p/11204171.html