Note 3 --- Django view

view

Django's view, refers to a function, this function is to accept the request and return a response. Accomplish this is to view function (class), generally referred to as direct view.
Conversely, we write the view function or class, in order to effect within Django, must also meet the requirements of Django, i.e. accept the request, returns a response
called accept the request, refers to at least the view function (s) to contain special request object.
the so-called return the response, refers to must be a manner consistent with the HTTP protocol returns a response, the content of the response can be a page's HTML content, a redirect, a 404 error, an XML document, or a picture, and so on.
In fact, you can write code view at any location in the app catalog, view the current convention-related code in the project (project) or application (app) files in a directory named views.py in.

Although many view function written before, there is also need to make a note of the view function:

# 视图函数的例子
from django.http import HttpResponse
import datetime

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

View function must have a parameter which is HttpRequest object, which parameter names can take any, but generally are used as starting request. When Django view function call, the request is passed to the HTTP package and view function into HttpRequest object as a parameter.
the return value of a function of view, when the beginner Django know HttpResponse, render, redirect returns three methods, the three essential things return method returns, are good HttpResponse object package.
as long as the preparation of function in line with the requirement that a request is received a reply response, the then bundled and urls function, the function becomes a function of view.
when you have your view after a function in the browser requesting access to the Django urls link , Django requests from the browser will be packaged as a HttpRequest object, the object corresponding to the view passed as arguments, and returns the HTTP response wait view function, and then returns the response to the browser.

FBV and CBV

I mentioned the view function (class), which indicates that in addition to the functions, classes can also be used as a view. Both methods are called FBV (Function Based View) and CBV (Class Based View). Prior written all views Yes FBV mode, if write CBV of view, we need to define a class in views.py where, in addition to correspondence between the urls in a slightly different
look to add items like a rewrite of their own writing:

class Item_add(View):
    title = "新增物品"

    def get(self, request):
        type_li = models.Types.objects.all().order_by("id")
        return render(request, 'item_add.html', {"items": "items", "title": self.title, "type_list": type_li})

    def post(self, request):
        new_item_name = request.POST.get("item_name_new").strip()
        new_item_type_id = request.POST.get("item_type_id")
        if new_item_name and new_item_type_id:
            try:
                models.Items.objects.create(type_id=new_item_type_id, name=new_item_name).save()
                return redirect("/items/")
            except:
                type_li = models.Types.objects.all().order_by("id")
                return render(request, 'item_add.html',
                              {"items": "items", "title": self.title, "type_list": type_li, "warning": "名字不能重复"})
        else:
            type_li = models.Types.objects.all().order_by("id")
            return render(request, 'item_add.html',
                          {"items": "items", "title": self.title, "type_list": type_li, "warning": "名字或类型不能为空白"})

One advantage with the class to write that, unlike with the function to determine if post and get methods (guess there will be other methods) can effectively reduce the degree of coupling, make the code clearer.
After the need to use the class name in the urls in .as_view corresponds to ().

url(r'^item_add/', views.Item_add.as_view())

CBV can effectively use the advanced features of object-oriented Python, in actual industrial software development, CBV use more. Like class decorators and other frequently used in practical projects.

Request and Response object

Receive requests and responses back view actually two objects, in response to the request is encapsulated in Django Request object, it is returned Response object.

Request object properties and methods

When a page is requested, Django creates an HttpRequest object of this request contains the original information.
Django This object will be automatically passed to the view response function, general view function using convention receiving the object request parameter.

Official document describes the various attributes of HttpRequest, these properties can be obtained and used within view function:

Non-modifiable properties
Attributes Explanation
HttpRequest.scheme Representative HTTP request scheme, http or https typically returns a string
HttpRequest.body Request body expressed in byte form. HTTP is useful in the processing of non-time packets may be used HttpResponse.read () operation request to the body
HttpRequest.path Represents an access path components, site name, port number, url additional information not included in the results, the only path is the path to absolute path .path
HttpRequest.path_info Only the difference between the path to get a relative path portions, with the recommended alternative path to facilitate debugging
HttpRequest.method The method represents a request, typically the POST and GET strings, must use uppercase
HttpRequest.GET Dictionary-like object containing all the parameters GET request
HttpRequest.POST A dictionary-like object, if the request is included in the form data, the data will be packaged into QueryDict objects. If the form is empty, it will still generate QueryDict objects, so when judging method GET or POST method of the property must pass judgment, but can not determine the presence or absence of QueryDict
HttpRequest.encoding Not used, indicating a coding mode decoding HTTP byte stream, generally a UTF-8
HttpRequest.COOKIES COOKIES storing a dictionary of keys and values ​​are strings
HttpRequest.FILES A dictionary containing all uploaded files, followed by get ( "name") way (name is the value of the name attribute of input tag) to get the specific file. To upload a file, Form form of property enctype = "multipart / form- data, otherwise it will be an empty FILES dictionary.
HttpRequest.META This dictionary is the HTTP request header contains all the information. See specific information here . Popular client IP address is acquired and the user data and the like.

The property is above the original browser sent me the property .HttpRequest object also has some applications and middleware to set up properties. These properties are set up prior to the view function.

Applications and middleware set of attributes
Attributes Explanation
HttpRequest.current_app Process the request on behalf of the current app, template language url tag treats it as a parameter.
HttpRequest.urlconf This will be treated as the root path of the current request, and routing system related.
HttpRequest.user This is added by AuthenticationMiddleware middleware attributes for user authentication. This is not enabled middleware is of no use. Please be detailed later learning
HttpRequest.session I can read a dictionary-like objects but also to write, and represents the current session. Only available when Django enable support sessions. The future will learn.

HttpRequest object method is as follows:

HttpRequest methods
method Explanation
HttpRequest.get_host() Acquired host address from the request header. According to the HTTP_X_FORWARDED_HOST (if open USE_X_FORWARDED_HOST, default False) HTTP_HOST header information and returns the requested original host. If the two headers do not provide the appropriate values, and then using SERVER_NAME SERVER_PORT
HttpRequest.get_full_path() Return path, also returned with the query string if the string is present.
HttpRequest.get_port() Return to port
HttpRequest.is_secure() If the request is initiated by Https returns True, otherwise False
HttpRequest.is_ajax() If the request is initiated by the XMLHttpRequest, it returns True, HTTP_X_REQUESTED_WITH by checking whether the respective header string 'XMLHttpRequest'. The future will learn when using Ajax
HttpRequest.get_signed_cookie(key, default=RAISE_ERROR, salt=”, max_age=None) Cookie related. Cookie to return a value corresponding to the signed, if the signature is no longer legitimate django.core.signing.BadSignature is returned.

Because our program is currently written, no verification is stateless web applications, database operations basically just visual, but also for some advanced methods not covered, will be with the establishment of different sites in the subsequent verification and on-line applications way to learn step by step.

Response object properties and methods

HttpRequest是Django自行创建并传入到视图函数的,Response对象则必须由我们自行通过内置方法建立.
之前学过的三种返回方式 HttpResponse, redirect, render 都是通过给内置方法传入数据,实例化一个HttpResponse对象并且返回.
之前学习过HTTP协议可以知道,响应也有响应头和响应体.在生成一个HttpResponse对象后可以不急着返回,通过属性和方法对其做操作.
HttpResponse的使用方法:
实例化HttpResponse对象并进行操作:

res = HttpResponse("我是手动设置的响应")
res.write(r"这是write方法写入的内容")

上述返回后在屏幕上会把两部分信息都显示,可见write方法是追加写入.
还可以对对象设置响应头的键值:

res['Age'] = 120
del res['Age']

来看看HttpResponse对象的方法和属性:

HttpResponse的属性
属性 解释
HttpResponse.content 获取响应体,以字节形式显示
HttpResponse.charset 返回响应体内字符集的结果
HttpResponse.status_code 返回HTTP状态码.HTTP响应状态码和对应的默认原因字符串都可以在IETF官方网站上的HTTP协议1.1版中找到.
HttpResponse.reason_phrase 返回状态码对应的默认原因字符串,除非被单独设置,否则该部分会随着状态码的设置而自动返回对应的默认原因字符串
HttpResponse.streaming 这个值永远是False,该值的存在是为了给中间件处理流信息所用.不要改动

HttpResponse对象的方法主要是和cookie有关,以后会再学习.官方文档.

JsonResponse对象

JsonResponse是HttpResponse的子类,专门用来生成JSON编码的响应。我们目前写的页面每次都是发送HTTP响应,其实就是将整个页面又传送了一次.在今后学异步的时候,前后端通信经常发送的不是整个页面,而是JSON字符串供页面使用.这个时候虽然可以引入json模块,将dump之后的结果交给HttpResponse,但可以直接引入Django内写好的模块进行响应,例子如下:

from django.http import JsonResponse
response = JsonResponse({'foo': 'bar'})
print(response.content)
b'{"foo": "bar"}'

默认只能传递字典类型,如果要传递非字典类型需要设置一下safe关键字参数。但一般不推荐使用,还是传送标准的Json字符串比较好.
看完了HttpResponse之后,来看看三大返回响应中的render以及redirect

render函数

render 属于Django shortcut functions中的组件之一.在之前的项目中已经知道了render的三个参数分别是request对象,渲染的页面以及传入的数据.现在再来仔细看一下render:

render(request, template_name, context=None, content_type=None, status=None, using=None)

参数详解:

render 函数
参数 解释
request 要响应的request对象
template_name 模板名称,到settings里指定的模板目录去寻找文件
context=None context指一个字典,包含传入给页面的数据,称为上下文字典或者上下文变量.默认为None
content_type=None 响应的MIME方式,默认的None表示text/html也就是标准HTML文档.
status=None HTTP状态码,默认的None表示200即响应成功.
using 加载模板引擎使用的名称.

render函数生成的结果是一个HttpResponse对象.从Django shortcut functions引入的render实际上是为了使用简便,将HttpResponse对象的生成过程以及包含了.如果为了程序的统一性,应该先进行渲染得到结果,最后再用HttpResponse生成响应对象,例如:

from django.shortcuts import render

def my_view(request):
    # 视图的代码写在这里
    return render(request, 'myapp/index.html', {'foo': 'bar'})

这段代码可以改写成先通过模板渲染,然后生成HttpResponse对象的方式:

from django.http import HttpResponse
from django.template import loader

def my_view(request):
    # 视图代码写在这里
    t = loader.get_template('myapp/index.html')
    c = {'foo': 'bar'}
    return HttpResponse(t.render(c, request))

可见这里是调用了模板类的一个方法,载入一个模板,然后对模板采用render方法渲染后得到渲染好的页面,最后用该页面生成HttpResponse对象.
第二种写法更加结构化和标准化,所有的视图函数统一返回由HttpResponse生成的对象.既然Django shortcut functions提供了简单的render方法,也可以使用.

redirect函数

同之前的render函数一样,redirect函数也是由Django shortcut functions模块内提供的”便利”函数:

redirect(to, permanent=False, *args, **kwargs)

redirect函数可以接受三种参数:

  1. 一个ORM模型:将调用模型的get_absolute_url()函数
  2. 一个视图,可以带有参数:将使用urlresolvers.reverse 来反向解析名称
  3. 一个绝对的或相对的URL,将原封不动的作为重定向的位置。

默认返回一个临时的重定向;传递permanent=True 可以返回一个永久的重定向。

之前使用redirect只使用了第三种情况,即返回一个绝对或者相对的URL,如果是绝对URL,必须以http(s)开头,否则会被解析为相对当前网站根目录的相对路径.
所谓临时重定向(状态码302)和永久重定向(状态码301)对于普通用户来说功能一样,主要是针对搜索引擎.A页面临时重定向到B页面,那搜索引擎收录的就是A页面。A页面永久重定向到B页面,那搜索引擎收录的就是B页面。
重定向到模型和视图用于应对比较复杂的需求,在今后的学习中遇到再说.

Django的视图架构和使用相比模板要简单很多,不过这是因为业务逻辑本身才是最复杂的部分,所以视图函数相对的限制很少.

Guess you like

Origin www.cnblogs.com/bmxm/p/11927891.html