The layers view Django

View layer

Python is a function of a view. This first parameter is a function of the HttpRequest; HttpResponse it returns an instance. In order to function as a Python a recognizable Django view, which must satisfy two conditions.

Where is the code view function can be written, but the general convention is set in the project or application directory views.py file. 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.

HttpRequest object

The row django Request packets, the header information, to the contents of the package body HttpRequest class attributes. In addition to the special instructions of the others are read-only

Property of the request object

request.scheme: behalf of the requesting program, http or https

request.path: path requests, such as requests 127.0.0.1/org/list, and that the value is / org / list

request.method: http request method indicates the use of, GET or POST request

request.encoding: representation submitted encoding data

request.GET: a GET request

request.POST: a post acquisition request, such as user password submitted distal end, may be obtained by request.POST.get ()

request.COOKIES: contains all of the cookie

request.session: a subject can read but also write a dictionary-like, represents the current session. Only available when Django enable support sessions.

request.FILES: a similar object dictionary that contains all the uploaded file information. Each key is FILES <input type = "file" name = "" /> The name, the value compared with the corresponding data.

Note that, FILES, and only for the POST method request submitted <form> case with enctype = "multipart / form-data" will be included in the data. Otherwise, FILES will be a blank dictionary-like object. Also: If you use the POST uploaded file, the file information will be included in the property FILES

It contains all of the cookie

request.user: a AUTH_USER_MODELtype of object that the user currently logged on.

If the user is currently not logged in, useryou will be set to django.contrib.auth.models.AnonymousUseran instance of. You can () to distinguish them by is_authenticated. When the request passed to the front end, the front end by {% if request.user.is_authenticated%} determines whether the user login time

request.META: A standard Python dictionary containing all the header of HTTP. Specific header information depends on the client and the server, the following are some examples:

A standard Python dictionary containing all the HTTP headers. Specific header information depends on the client and the server, the following are some examples:

  • CONTENT_LENGTH - the length of the body of the request (a string).
  • CONTENT_TYPE - MIME type text request.
  • HTTP_ACCEPT - Content-Type Response receivable.
  • HTTP_ACCEPT_ENCODING - receiving the response may be encoded.
  • HTTP_ACCEPT_LANGUAGE - receiving the response may language.
  • HTTP_HOST - HTTP Host header sent by customer.
  • HTTP_REFERER - Referring page.
  • HTTP_USER_AGENT - user-agent string client.
  • QUERY_STRING - a single string in the form of a query string (not parsed form).
  • REMOTE_ADDR - IP address of the client.
  • REMOTE_HOST - Host name of the client.
  • REMOTE_USER - After the user authentication server.
  • REQUEST_METHOD- a string, e.g. "GET", or "POST".
  • SERVER_NAME - The host name of the server.
  • SERVER_PORT - the server port (a string)

Upload file example

def upload(request):
    """
    保存上传文件前,数据需要存放在某个位置。默认当上传文件小于2.5M时,django会将上传文件的全部内容读进内存。从内存读取一次,写磁盘一次。
    但当上传文件很大时,django会把上传文件写到临时文件中,然后存放到系统临时文件夹中。
    """
    if request.method == "POST":
        # 从请求的FILES中获取上传文件的文件名,file为页面上type=files类型input的name属性值
        filename = request.FILES["file"].name
        # 在项目目录下新建一个文件
        with open(filename, "wb") as f:
            # 从上传的文件对象中一点一点读
            for chunk in request.FILES["file"].chunks():
                # 写入本地文件
                f.write(chunk)
        return HttpResponse("上传OK")

HttpResponse object

There are three main forms of response object:

  • HttpResponse()
  • render()
  • redirect()

HttpResponse()

Brackets directly with a particular character string as a response thereof.

render()

render(request, template_name[, context])
参数:
     request: 用于生成响应的请求对象。
     template_name:要使用的模板的完整名称,可选的参数
     context:添加到模板上下文的一个字典。默认是一个空字典。如果字典中的某个值是可调用的,视图将在渲染模板之前调用它。

approach is to render a template syntax template page rendering, final rendering into a html page as response body.

redirect()

Deliver a hard-coded URL to redirect

def my_view(request):
    ...
    return redirect('/index/')

It can be a complete URL:

def my_view(request):
    ...
    return redirect('http://www.baidu.com/') 

JsonResponse objects

JsonResponse is HttpResponse subclass, designed to generate a response JSON-encoded.

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

The default dictionary type can be passed, if you want to pass a non-keyword dictionary type safe parameters need to set up.

response = JsonResponse([1, 2, 3], safe=False)

CBV and FBV

CBV based view (Function base view) based on a function of view (Class base view) and class FBV

FBV version:

# FBV版添加班级
def add_class(request):
    if request.method == "POST":
        class_name = request.POST.get("class_name")
        models.Classes.objects.create(name=class_name)
        return redirect("/class_list/")
    return render(request, "add_class.html")

CBV version:

# CBV版添加班级
from django.views import View
class AddClass(View):
    def get(self, request):
        return render(request, "add_class.html")
    def post(self, request):
        class_name = request.POST.get("class_name")
        models.Classes.objects.create(name=class_name)
        return redirect("/class_list/")

note:

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

# urls.py中
url(r'^add_class/$', views.AddClass.as_view()),

Guess you like

Origin blog.csdn.net/linwow/article/details/91462983