Python django-3 View

Source: Internet
Author: User
Tags install django pip install django timedelta

View
    • View accepts Web requests and returns Web responses
    • The view is a Python function that is defined in the views.py
    • The response can be a Web page of HTML content, a redirect, a 404 error, and so on
    • The response processing process is as follows:

URLconf
    • Specify the configuration of the root-level URL in the settings.py file by root_urlconf
    • Urlpatterns is a list of URL () instances
    • A URL () object includes:
      • Regular expressions
      • View functions
      • Names name
    • Note for writing urlconf:
      • To capture a value from a URL, you need to set a pair of parentheses around it
      • Do not need to add a leading backslash, such as should write ' test/', and should not write '/test/'
      • R in front of each regular expression indicates that the string is not escaped
    • The requested URL is considered to be a normal Python string that does not include parameters and domain names for GET or post requests when matching
http://www.itcast.cn/python/1/?i=1&p=new,只匹配“/python/1/”部分
    • Regular expression non-named group, passed to the view by positional parameters
url(r‘^([0-9]+)/$‘, views.detail, name=‘detail‘),
    • A regular expression named group, passed to the view by keyword argument, the keyword parameter in this case is ID
url(r‘^(?P<id>[0-9]+)/$‘, views.detail, name=‘detail‘),
    • Parameter matching rules: takes precedence over named arguments, and uses positional parameters if no named arguments are used
    • Each captured parameter is passed to the view as a normal Python string
    • Performance: each regular expression in Urlpatterns is compiled the first time they are accessed, which makes the system fairly fast
Contains other Urlconfs.
    • Create a urls.py file in your app, define the urlconf in this app, and then use include () in the settings of your project
from django.conf.urls import include, urlurlpatterns = [    url(r‘^‘, include(‘booktest.urls‘, namespace=‘booktest‘)),]
    • Matching process: match with main urlconf first, and then use the remainder to match the urlconf in the application.
请求http://www.itcast.cn/booktest/1/在sesstings.py中的配置:url(r‘^booktest/‘, include(‘booktest.urls‘, namespace=‘booktest‘)),在booktest应用urls.py中的配置url(r‘^([0-9]+)/$‘, views.detail, name=‘detail‘),匹配部分是:/booktest/1/匹配过程:在settings.py中与“booktest/”成功,再用“1/”与booktest应用的urls匹配
    • Use the include to remove urlconf redundancy
    • Parameters: The view receives all parameters captured from the parent urlconf, the current urlconf
    • Defining namespaces through namespace in include for inverse parsing
Reverse parsing of URLs
    • If you use hard-coded links in your views, templates, maintenance is a very troublesome thing when urlconf changes.
    • Workaround: Dynamically generate a link address when making a link by pointing to the name of the urlconf
    • Views: Using the Django.core.urlresolvers.reverse () function
    • Templates: Using URL template tags
Defining views
    • Essence is a function
    • Parameters of the View
      • A HttpRequest instance
      • Positional parameters obtained from a regular expression group
      • Keyword parameters obtained from regular expression groups
    • In the application directory, the default views.py file, the general view is defined in this file
    • If you have too many processing functions, you can define functions into different py files
新建views1.py#coding:utf-8from django.http import HttpResponsedef index(request):    return HttpResponse("你好")在urls.py中修改配置from . import views1url(r‘^$‘, views1.index, name=‘index‘),
Error view
    • Django native comes with several default views for handling HTTP errors
404 (page not found) view
    • Defaults.page_not_found (Request, template_name= ' 404.html ')
    • The default 404 view will pass a variable to the template: Request_path, which is the URL that caused the error
    • If Django does not find a match after detecting each regular expression in urlconf, it will also call 404 view
    • If debug is set to true in Settings, then the 404 view will never be called, but the urlconf is displayed with some debugging information
    • Create 404.html in Templates
<!DOCTYPE html>
    • modifying debugging in Settings.py
DEBUG = FalseALLOWED_HOSTS = [‘*‘, ]
    • Request a non-existent address
http://127.0.0.1:8000/test/
(Server error) view
    • Defaults.server_error (Request, template_name= ' 500.html ')
    • A run-time error occurred in the View Code
    • The default 500 view does not pass variables to the 500.html template
    • If debug is set to true in Settings, then the 505 view will never be called, but the urlconf is displayed with some debugging information
(Bad Request) view
    • Defaults.bad_request (Request, template_name= ' 400.html ')
    • Error from the client operation
    • When a user is doing a security-related action, such as tampering with a session cookie
Httpreqeust Object
    • After the server receives the HTTP protocol request, it creates a HttpRequest object based on the message
    • The first parameter of a view function is the HttpRequest object
    • API for HttpRequest objects defined in the Django.http module
Property
    • Properties are read-only unless specifically stated below
    • Path: A string that represents the full path of the requested page, not including the domain name
    • Method: A string that represents the HTTP method used by the request, common values include: ' GET ', ' POST '
    • Encoding: A string that represents the encoding of the submitted data
      • If none means using the browser's default settings, typically Utf-8
      • This property is writable and can be modified to modify the encoding used to access the form data, and then any access to the property will use the new encoding value
    • Get: A dictionary-like object that contains all the arguments for how a get is requested
    • Post: A dictionary-like object that contains all the parameters of the POST request method
    • Files: A dictionary-like object that contains all the uploaded files
    • Cookies: A standard Python dictionary that contains all cookies, keys and values are strings
    • Session: A read-and-write dictionary-like object that represents the current session and is available only if Django enables session support, as detailed in "State hold"
Method
    • Is_ajax (): Returns True if the request was initiated through XMLHttpRequest
Querydict Object
    • Defined in Django.http.QueryDict
    • The properties of the request object get, post are objects of type querydict
    • Unlike a Python dictionary, an object of type querydict is used to handle a condition 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 more than one value at a time, get the last value
dict.get(‘键‘,default)或简写为dict[‘键‘]
    • Method GetList (): Gets the value by key
      • Returns the value of the key as a list and can get multiple values for a key
dict.getlist(‘键‘,default)
Get property
    • Objects of type Querydict
    • All parameters containing the GET request method
    • corresponding to the parameters in the URL request address, located behind the
    • The format of the parameter is a key-value pair, such as key1=value1
    • Between multiple parameters, use & Connect, such as Key1=value1&key2=value2
    • The key is determined by the developer, and the value is variable
    • Examples such as the following
    • Create a view getTest1 is used to define a link, getTest2 is used to receive a one-key value, GETTEST3 is used to receive one-key multi-value
def getTest1(request):    return render(request,‘booktest/getTest1.html‘)def getTest2(request):    return render(request,‘booktest/getTest2.html‘)def getTest3(request):    return render(request,‘booktest/getTest3.html‘)
    • Configure URLs
url(r‘^getTest1/$‘, views.getTest1),url(r‘^getTest2/$‘, views.getTest2),url(r‘^getTest3/$‘, views.getTest3),
    • Create gettest1.html, define Links
    • Perfecting the code for view GetTest2
def getTest2(request):    a=request.GET[‘a‘]    b=request.GET[‘b‘]    context={‘a‘:a,‘b‘:b}    return render(request,‘booktest/getTest2.html‘,context)
    • Create gettest2.html, show receive results
    • Perfecting the code for view GetTest3
def getTest3(request):    a=request.GET.getlist(‘a‘)    b=request.GET[‘b‘]    context={‘a‘:a,‘b‘:b}    return render(request,‘booktest/getTest3.html‘,context)
    • Create gettest3.html, show receive results
Post Properties
    • Objects of type Querydict
    • All parameters containing the method of POST request
    • Corresponds to a control in a form form
    • Q: What controls in the form are submitted?
    • A: The control needs to have the Name property, the value of the Name property is the key, the Value property is the key, and the key value pair commits
      • For the CheckBox control, the Name property is a group, and when the control is selected it is committed and there is a one-key multi-value case
    • The key is determined by the developer, and the value is variable
    • Examples such as the following
    • Defining views PostTest1
def postTest1(request):    return render(request,‘booktest/postTest1.html‘)
    • Configure URLs
url(r‘^postTest1$‘,views.postTest1)
    • Create a template posttest1.html
    • Create a view PostTest2 receive the requested data
def postTest2(request):    uname=request.POST[‘uname‘]    upwd=request.POST[‘upwd‘]    ugender=request.POST[‘ugender‘]    uhobby=request.POST.getlist(‘uhobby‘)    context={‘uname‘:uname,‘upwd‘:upwd,‘ugender‘:ugender,‘uhobby‘:uhobby}    return render(request,‘booktest/postTest2.html‘,context)
    • Configure URLs
url(r‘^postTest2$‘,views.postTest2)
    • Create a template posttest2.html
    • Note: Use form submission to comment out the middleware in settings.py CRSF
HttpResponse Object
    • API for HttpResponse objects defined in the Django.http module
    • HttpRequest objects are created automatically by Django, and HttpResponse objects are created by programmers
    • Return data directly without invoking a template
#coding=utf-8from django.http import HttpResponsedef index(request):    return HttpResponse(‘你好‘)
    • Invoke template
from django.http import HttpResponsefrom django.template import RequestContext, loaderdef index(request):    t1 = loader.get_template(‘polls/index.html‘)    context = RequestContext(request, {‘h1‘: ‘hello‘})    return HttpResponse(t1.render(context))
Property
    • Content: Indicates what is returned, String type
    • CharSet: Represents the encoded character set used by response, String type
    • Status_code: HTTP response status code for the response
    • Content-type: Specifies the MIME type of the output
Method
    • Init: Instantiating a HttpResponse object using page content
    • Write (content): written as a file
    • Flush (): Output buffers in file mode
    • Set_cookie (Key, value= ", Max_age=none, Expires=none): Set cookies
      • Key, value are string types
      • Max_age is an integer that indicates that it expires after a specified number of seconds
      • Expires is a datetime or Timedelta object, and the session expires at this specified date/time, noting that datetime and Timedelta values can be serialized only when Pickleserializer is used
      • Max_age and expires two select one
      • Expires after two weeks if the expiration time is not specified
from django.http import HttpResponsefrom datetime import *def index(request):    response = HttpResponse()    if request.COOKIES.has_key(‘h1‘):        response.write(‘
    • Delete_cookie (key): Delete the specified key cookie, and nothing happens if key does not exist
Sub-class Httpresponseredirect
    • Redirect, server-side jump
    • The first parameter of a constructor is used to specify the address of the redirect
在views1.py中from django.http import HttpResponse,HttpResponseRedirectdef index(request):    return HttpResponseRedirect(‘js/‘)def index2(request,id):    return HttpResponse(id)在应用的urls.py中增加一个url对象url(r‘^([0-9]+)/$‘, views1.index2, name=‘index2‘),
    • Request Address Bar

    • The address bar of the request result

    • Recommended use of Reverse parsing
from django.core.urlresolvers import reversedef index(request):    return HttpResponseRedirect(reverse(‘booktest:index2‘, args=(1,)))
Sub-class Jsonresponse
    • Returns JSON data, typically used for asynchronous requests
    • _init _ (data)
    • Help users create JSON-encoded responses
    • Parameter data is a Dictionary object
    • The default content-type for Jsonresponse is Application/json
from django.http import JsonResponsedef index2(requeset):    return JsonResponse({‘list‘: ‘abc‘})
Shorthand function Render
    • Render (Request, template_name[, context])
    • Combines a given template and a given context dictionary, and returns a rendered HttpResponse object
    • Request: This request is used to generate the response
    • Template_name: The full name of the template to use
    • Context: A dictionary that is added to the template context, and the view will call it before rendering the template
from django.shortcuts import renderdef index(request):    return render(request, ‘booktest/index.html‘, {‘h1‘: ‘hello‘})
redirect
    • Redirect (To)
    • Returns httpresponseredirect for passed in parameters
    • To recommend using reverse parsing
from django.shortcuts import redirectfrom django.core.urlresolvers import reversedef index(request):    return redirect(reverse(‘booktest:index2‘))
Get object or return 404
    • get_object_or_404 (Klass, args, *Kwargs)
    • The Get () method is called through the Model manager or query set, and if no object is found, the model's doesnotexist exception is raised, but the Http404 exception is thrown
    • Klass: Gets the model class, manager object, or Queryset object of the object
    • **kwargs: The parameters of the query, the format should be accepted by get () and filter ()
    • Multipleobjectsreturned exception is thrown if multiple objects are found
from django.shortcuts import *def detail(request, id):    try:        book = get_object_or_404(BookInfo, pk=id)    except BookInfo.MultipleObjectsReturned:        book = None    return render(request, ‘booktest/detail.html‘, {‘book‘: book})将settings.py中的DEBUG改为False将请求地址输入2和100查看效果
Get a list or return 404
    • get_list_or_404 (Klass, args, *Kwargs)
    • Klass: Gets a model, manager, or Queryset instance of the list
    • **kwargs: The parameters of the lookup, the format should be accepted by get () and filter ()
from django.shortcuts import *def index(request):    # list = get_list_or_404(BookInfo, pk__lt=1)    list = get_list_or_404(BookInfo, pk__lt=6)    return render(request, ‘booktest/index.html‘, {‘list‘: list})将settings.py中的DEBUG改为False
Status hold
    • The HTTP protocol is stateless: Each request is a new request and will not remember the state of the previous communication
    • A client-to-server communication is a session
    • How to implement state retention: Store data about sessions on the client or server side
    • Storage methods include cookies, sessions, and session objects
    • Use cookies, all data stored on the client, and be careful not to store sensitive information
    • It is recommended to use the Sesison method, where all data is stored on the server side and stored in the client cookie session_id
    • The purpose of the state hold is to track the requester's state over a period of time, enabling the data for the current requestor to be accessed across the page
    • Note: This data is not shared between different requesters, and is corresponding to the requestor
Enable session
    • Projects created by using Django-admin startproject are enabled by default
    • In the settings.py file
项INSTALLED_APPS列表中添加:‘django.contrib.sessions‘,项MIDDLEWARE_CLASSES列表中添加:‘django.contrib.sessions.middleware.SessionMiddleware‘,
    • Disable session: Delete The two values specified above, disabling sessions will save some performance consumption
Use session
    • After the session is enabled, each HttpRequest object will have a session property, which is a class Dictionary object
    • Get (Key, Default=none): Gets the value of the session based on the key
    • Clear (): Clear All sessions
    • Flush (): Deletes the current session data and deletes the session's cookie
    • Del request.session[' member_id ': delete session
User Login Example
    • Operating effects such as:

    • Create a view in a views.py file
from django.shortcuts import render, redirectfrom django.core.urlresolvers import reversedef index(request):    uname = request.session.get(‘uname‘)    return render(request, ‘booktest/index.html‘, {‘uname‘: uname})def login(request):    return render(request, ‘booktest/login.html‘)def login_handle(request):    request.session[‘uname‘] = request.POST[‘uname‘]    return redirect(reverse(‘main:index‘))def logout(request):    # request.session[‘uname‘] = None    # del request.session[‘uname‘]    # request.session.clear()    request.session.flush()    return redirect(reverse(‘main:index‘))
    • Configure URLs
主url:from django.conf.urls import include, urlurlpatterns = [    url(r‘^‘, include(‘booktest.urls‘, namespace=‘main‘))]应用url:from django.conf.urls import urlfrom . import viewsurlpatterns = [    url(r‘^$‘, views.index, name=‘index‘),    url(r‘login/$‘, views.login, name=‘login‘),    url(r‘login_handle/$‘, views.login_handle, name=‘login_handle‘),    url(r‘logout/$‘, views.logout, name=‘logout‘)]
    • Create a template index.html
<!DOCTYPE html>
    • Create a template login.html
<!DOCTYPE html>
Session Expiration Time
    • Set_expiry (value): Sets the timeout period for the session
    • Expires after two weeks if not specified
    • If value is an integer, the session expires after values seconds are inactive
    • If value is a Imedelta object, the session will expire at the current time plus the specified date/time
    • If value is 0, then the cookie for the user session expires when the user's browser is closed
    • If value is None, then the session never expires
    • Modify the Login_handle function in the view to see the effect
def login_handle(request):    request.session[‘uname‘] = request.POST[‘uname‘]    # request.session.set_expiry(10)    # request.session.set_expiry(timedelta(days=5))    # request.session.set_expiry(0)    # request.session.set_expiry(None)    return redirect(reverse(‘main:index‘))
Storage session
    • Using the settings.py session_engine key, you can use the storage session to specify
    • Database-based sessions: This is the default Django session store, which needs to be added django.contrib.sessions to the Installed_apps settings, run manage.py migrate install the session table in the database, and display the specified
SESSION_ENGINE=‘django.contrib.sessions.backends.db‘
    • Cache-based sessions: only local intrinsic, if lost, can not be recovered, faster than the database read and write
SESSION_ENGINE=‘django.contrib.sessions.backends.cache‘
    • You can use both the cache and the database: take precedence from the local cache and get from the database if not
SESSION_ENGINE=‘django.contrib.sessions.backends.cached_db‘
Using the Redis cache session
    • Sessions also support files, pure cookies, Memcached, Redis, and other means of storage, and the following demo uses Redis storage
    • Install package
pip install django-redis-sessions
    • Modify the configuration in the settings to add the following
SESSION_ENGINE = ‘redis_sessions.session‘SESSION_REDIS_HOST = ‘localhost‘SESSION_REDIS_PORT = 6379SESSION_REDIS_DB = 0SESSION_REDIS_PASSWORD = ‘‘SESSION_REDIS_PREFIX = ‘session‘
    • Commands for managing Redis
启动:sudo redis-server /etc/redis/redis.conf停止:sudo redis-server stop重启:sudo redis-server restartredis-cli:使用客户端连接服务器keys *:查看所有的键get name:获取指定键的值del name:删除指定名称的键

Python django-3 View

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.