This article is participating in “Python Theme Month”. Check out Python Authoring season to show off your Python articles – $2000 limited prize waiting for you to win
Views view
Summary of view
- Views are view functions, transaction functions that receive Web requests and return web responses
- A response is anything that meets the requirements of the HTTP protocol, including JSON, String, HTML, and so on
- This chapter ignores transaction processing and focuses on how to handle the return result
Other simple views
- Django. HTTP gives us many simple views similar to HttpResponse, as we know by looking at the django. HTTP code
- This type of view is used in much the same way and can be returned to the browser as direct feedback via a return statement
- Http404 is an Exception subclass, so raise is required
HttpResponse,
- methods
- Init: Instantiate an HttpResponse object using web page content
- Write (Content): Write as a file
- Flush (): Outputs the cache as a file
- Set_cookie (key, value= “, max_age=None, Expires =None): Sets the cookie
- Both key and value are strings
- Max_age is an integer that expires after a specified number of seconds
- An expires is a datetime or timedelta object at which the session will expire,
- Choose max_age or Expires
- If the expiration time is not specified, it will expire in two weeks
- Delete_cookie (key): Deletes the Cookie of the key, and nothing happens if the key does not exist
HttpResponseRedirect
- Redirection, redirect the server
- The first argument to the constructor specifies the address to be redirected to
The Request object
- The Request is introduced
- After receiving the HTTP request, the server creates an HttpResponse object based on the packet
- The first argument to the view function is an HttpResponse object
- An API for HttpResponse objects is defined in the Django. HTTP module
- attribute
- The properties below are read-only unless otherwise noted
- Path: A string representing the full path to the requested page, excluding the domain name
- Method: A string representing the HTTP method used in the request. Common values include: ‘GET’, ‘POST’
- Encoding: A string that specifies the encoding method of the submitted data
- If None, the browser’s default setting is used, which is generally UTF-8
- This property is writable and can be modified to modify the use of access form data
- GET: a dictionary-like object that contains all the parameters of the GET request
- POST: A dictionary-like object that contains all the parameters of the POST request
- FILES: a dictionary-like object that contains all uploaded FILES
- COOKIES: A standard Python dictionary containing all COOKIES with strings of keys and values
- Session: a dictionary-like object that is readable and writable and represents the current session,
- This is only available if Django has session support enabled
- See “State holding” for details.
- methods
- Is_ajax (): Returns True if the request was initiated via XMLHttpResponse
QueryDict object
- Defined in django. HTTP. QueryDict
- The GET and POST properties of the Request object are QueryDict objects
- Unlike Python dictionaries, objects of type QueryDict deal with multiple values for the same key
- Method get(): gets the value based on the key
- Only one value of the key can be obtained
- If a key has multiple values, get the last value
- Method getList (): gets values based on keys
- Multiple values of a key can be obtained by returning the key values as a list
The GET property
- Objects of type QueryDict
- Contains all the parameters of the GET request
- Corresponds to the parameter in the URL request address, located at? behind
- The parameter format is key-value pair, that is, key1 = value1
- Multiple parameters are connected with am&, for example, key1=value1&key2=value2
- Keys are determined by the developer, and values are mutable
- Case/views/v12_get
def v12_get(request) :
rst = ""
for k,v in request.GET.items():
rst += k + '-->' + v
rst += ', '
return HttpResponse("Get value of Request is {0}".format(rst))
Copy the code
POST properties
- Objects of type QueryDict
- Contains all parameters of the POST request mode
- Corresponds to a control in the Form form
- Controls in the form must have a name attribute, where name is the key and value is the value
- Checkbbox has multiple values with one key
- Keys are determined by the developer, and values are mutable
- Case/views/v9_post
- Set the template position in settint
- Set the urls and functions of the GET page
def v9_post(request) : rst = ' ' for k, v in request.POST.items(): rst += k + '- >' + v rst += ', ' return HttpResponse("Get value of POST is {0}".format(rst)) Copy the code
Writing views manually
- The experiment purpose
- Write view handlers manually using Django shortcuts
- Understand how views work while writing
- Analysis of the
- Django wraps all request information into a request
- Django connects the request to the event handler via the urls module and passes the request as a parameter
- In the corresponding handler, we need to do two parts
- Deal with business
- To wrap and return the result, we can either use HttpResponse or handle this function ourselves
- This case does not cover business processing, but focuses on how to render the result and return it
- render(request, template_name[, context][, context_instance][, content_type][, status][, current_app][, dirs][, using])
- Returns an HttpResponse object for render and, using a template and a given context
- Request: An incoming request from Django
- Template_name: indicates the template name
- Content_instance: Context
- See ruochen_views/teacher_app/views/render_test for an example
def rander_test(request) : # Environment variables # c = dict() rsp = render(request, "render.html") # rsp = HttpResponse(request, "render.html") return rsp Copy the code
- render_to_response
- Render the given template according to the given context dictionary. Returns the rendered HttpResponse
- Built-in system view
-
Built-in system view, which can be used directly
-
404
- default.page_not_found(request, template_name=’404.html’)
- Triggered when the system raises Http404
- The default is to pass the request_PATH variable to the template, which is the URL that caused the error
- DEBUG=True does not call 404, but instead sends debugging messages
- The 404 view is passed a RequestContext object and can access variables provided by the template context handler (MEDIA_URL, etc.)
-
500(server error)
- defaults.server_error(request, template_name=’500.html’)
- DEBUG=False is required, otherwise not called
-
403 (HTTP Forbidden) View
- defaults.permission_denied(request, template_name=’403.html’)
- Triggered by PermissionDenied
-
400 (Bad Request) view
- defaults.bad_request(request, template_name=’400.html’)
- DEBUG=False
-
Class-based view
A quick word about class-based views
- The advantages and differences between and function-based views:
- HTTP methods of methode can have their own methods and do not need to use conditional branches to solve
- OOP techniques can be used (such as mixins)
- An overview of the
- The core is to allow different instance methods to correspond to different HTTP request methods, bypassing conditional branching implementations
- The as_view function, which creates an instance and calls the dispatch method, dispatches the request according to the request method, if the
Method, which is not defined, raises HttpResponseNotAllowed
- Class attribute usage
- Overrides directly at class definition time
- When calling as_view, use last night arguments directly, for example:
urlpatterns = [ url(r'^about/', GreetingView.as_view(greeting="G'day")), ] Copy the code
- There are roughly three ways to extend class-based views: Mixin, decorated AS_view, and decorated dispatch
- The use of a Mixin
- A form of multiple inheritance in which actions and attributes from Frey are grouped together
- Solve multiple inheritance problems
- View subclasses can only be inherited single-inheritance, and multiple inheritance causes unpredictability
- Problems with multiple inheritance:
- Complicated structure
- Fuzzy priorities
- Functional conflict
- The solution
- Specification inheritance – Java Interface
- Implement inheritance – Python, Ruby
- Decorate in URLconf
from django.contrib.auth.decorators import login_required, permission_required from django.views.generic import TemplateView from .views import VoteView urlpatterns = [ url(r'^about/', login_required(TemplateView.as_view(template_name="secret.html"))), url(r'^vote/', permission_required('polls.can_vote')(VoteView.as_view())), ] Copy the code
- Decoration class
- Class methods, unlike stand-alone methods, do not apply a decorator directly. Instead, use methode_decorator
from django.contrib.auth.decorators import login_required from django.utils.decorators import method_decorator from django.views.generic import TemplateView class ProtectedView(TemplateView): template_name = 'secret.html' @method_decorator(login_required) def dispatch(self, *args, **kwargs): return super(ProtectedView, self).dispatch(*args, **kwargs) Copy the code
- Class methods, unlike stand-alone methods, do not apply a decorator directly. Instead, use methode_decorator
The relevant code
The relevant code used in the view section is as follows
- urls.py
from django.conf.urls import include, url
from django.contrib import admin
from teacher_app import views as v
urlpatterns = [
# Examples:
# url(r'^$', 'ruochen_views.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^teacher/', v.teacher),
url(r'^v2_exp/', v.v2_exception),
url(r'^v10_1/', v.v10_1),
url(r'^v10_2/', v.v10_2),
url(r'^v11_hello/', v.v11, name='v11'),
url(r'^v12/', v.v12_get),
url(r'^v9_get/', v.v9_get),
url(r'^v9_post/', v.v9_post),
url(r'render_test/', v.rander_test),
url(r'render2_test/', v.rander2_test),
url(r'render3_test/', v.rander3_test),
url(r'render1_to_res/', v.render4_test),
url(r'^get404/', v.get404),
]
Copy the code
- views.py
from django.shortcuts import render, render_to_response
from django.http import HttpResponse, Http404, HttpResponseRedirect
from django.core.urlresolvers import reverse
# Create your views here.
def teacher(r) :
return HttpResponse('This is a view of teacher')
def v2_exception(r) :
raise Http404
return HttpResponse('OK')
def v10_1(r) :
return HttpResponseRedirect(reverse('v11'))
def v10_2(r) :
return HttpResponseRedirect(reverse('v11'))
def v11(r) :
return HttpResponse('V11 access return')
def v12_get(request) :
rst = ""
for k,v in request.GET.items():
rst += k + '-->' + v
rst += ', '
return HttpResponse("Get value of Request is {0}".format(rst))
def v9_get(request) :
Render a template and return
return render_to_response('for_post.html')
def v9_post(request) :
rst = ' '
for k, v in request.POST.items():
rst += k + '- >' + v
rst += ', '
return HttpResponse("Get value of POST is {0}".format(rst))
def rander_test(request) :
# Environment variables
# c = dict()
rsp = render(request, "render.html")
# rsp = HttpResponse(request, "render.html")
return rsp
def rander2_test(request) :
# Environment variables
c = dict()
c['name'] = "ruochen"
c['name2'] = "ruochen2"
c['name3'] = "ruochen3"
rsp = render(request, "render2.html", context=c)
return rsp
def rander3_test(request) :
from django.template import loader
# get template
t = loader.get_template('render2.html')
print(type(t))
r = t.render({"name": "ruochen"})
print(type(r))
return HttpResponse(r)
def render4_test(request) :
# feedback to m template render2.html
rsp = render_to_response("render2.html", context={"name": "ruochen"})
return rsp
def get404(request) :
from django.views import defaults
return defaults.page_not_found(request, template_name="render.html")
Copy the code
- templates
- for_post.html
<html> <head> <title>Title</title> </head> <body> <form method="post" action="/v9_post/">Name:<input type="text" name="uname"/><br>Password:<input type="password" name="upwd"/><br>Gender:<input type="radio" name="ugender" value="1"/>male<input type="radio" name="ugender" value="0"/>female<br>Hobbies:<input type="checkbox" name="uhobby" value="Just the rice"/>Just a meal<input type="checkbox" name="uhobby" value="Jump"/>Jump off a building<input type="checkbox" name="uhobby" value="Drinking"/>drinking<input type="checkbox" name="uhobby" value="Jump"/>Climbing the mountain<br> <input type="submit" value="Submit"/> </form> </body> </html> Copy the code
- render.html
<! DOCTYPEhtml> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>Render example by ruochen</h1> </body> </html> Copy the code
- render2.html
<! DOCTYPEhtml> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>WebPage for rander with {{name}}</h1> </body> </html> Copy the code
- settings.py
"" Django Settings for ruochen_views project. Generated by 'django-admin startproject' using Django 1.8. for more information on this file, See https://docs.djangoproject.com/en/1.8/topics/settings/ For a full list of Settings and their values. See "https://docs.djangoproject.com/en/1.8/ref/settings/" "
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'a^-vz9v! e2ks%m=d*&fu$r)qc42vpgkqny9jl36plg$(3jtp#q'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ["*"]
# Application definition
INSTALLED_APPS = (
'django.contrib.admin'.'django.contrib.auth'.'django.contrib.contenttypes'.'django.contrib.sessions'.'django.contrib.messages'.'django.contrib.staticfiles'.'teacher_app',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware'.'django.middleware.common.CommonMiddleware'.# 'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware'.'django.contrib.auth.middleware.SessionAuthenticationMiddleware'.'django.contrib.messages.middleware.MessageMiddleware'.'django.middleware.clickjacking.XFrameOptionsMiddleware'.'django.middleware.security.SecurityMiddleware',
)
ROOT_URLCONF = 'ruochen_views.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates'.'DIRS': [os.path.join(BASE_DIR, "templates")].'APP_DIRS': True.'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug'.'django.template.context_processors.request'.'django.contrib.auth.context_processors.auth'.'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'ruochen_views.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3'.'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),}}# Internationalization
# https://docs.djangoproject.com/en/1.8/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.8/howto/static-files/
STATIC_URL = '/static/'
Copy the code