程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Django view

編輯:Python

For complete content, please visit :https://www.emperinter.info/2022/05/31/django-view/

View

summary

  • effect :
    • The view accepts web request , And respond to Web request
  • The essence :
    • The view is One Python The function in
  • Response content :
    • Webpage
      • Redirect
      • Wrong view
        • 404:url Can't find
        • 500: Server internal error
    • JSON data

URL To configure

The configuration process

  • stay settings.py It is specified in Root level URL The configuration file :ROOT_URLCONF = 'project.urls', By default .
  • urlpatterns:
    • One url The object of the instance
    • url object
      • Regular expressions
      • View name
      • name ( Used for reverse parsing )
  • url Considerations for matching regularities :
    • If you want to go from url To get a value , You need to add parentheses to the regular
    • The match is correct , There is no need to add a small slash in front /, Usually add at the end
    • You need to add... Before regularization r Representation string No escape

Introduce other url To configure

  • Generally, it is created in the application urls.py file , Define the of this application url To configure , In the engineering urls.py Use... In the document include() Method : url(r'^', include('myApp.urls',namespace='myApp')),

Matching process

  • engineering url-> application url-> View

URL Reverse resolution of ( agent ):

  • summary
    • If in view / Hard coded connections are used in the template , stay url When the configuration changes , Dynamically generate the address of the link .
  • Solutions
    • When using links , adopt url Configuration name , Dynamic generation url Address .
  • effect
    • Use url The template

The view function

Define views :

  • The essence : A function
  • View parameters :
    • request One HttpRequest Example
    • adopt url Parameters obtained by regular expression
  • Location :
    • Generally in views.py In the definition of

Wrong view

  • 404 View
    • Web page not found (url The match didn't work ) When to return to .
    • You can define yourself .
      • stay templates define 404.html
        • request_path: URL causing error .
      • To configure settings.py
        • DEBUG If True forever No Would call 404.html page
        • ALLOWED_HOSTS = [*]
  • 500 View
    • An error occurred in the view code ( Server code ).
  • 400 View
    • The error is the customer's operation .

HttpRequest object

Concept

  • receive HTTP After the request , It will be created according to the message HttpRequest object
  • The first parameter of a view is HttpRequest object
  • Djano Object created , Then the call attempts to pass to the view

attribute

  • path
    • The full path of the request ( Domain name and port are not included )
  • method
    • How to express a request , Commonly used GET、POST
  • encoding
    • Represents the encoding method of the data submitted by the browser , It's usually utf-8
  • GET
    • Dictionary like objects , Contains get All parameters requested
  • POST
    • Dictionary like objects , Contains post All parameters requested
  • FILES
    • Dictionary like objects , Contains all uploaded files .
  • COOKIES
    • Dictionaries , All inclusive cookie
  • session
    • Dictionary like objects , Represents the current session

Method

  • is_ajax()
    • If it is XMLHttpRequest Sponsored , return True

QueryDict object

  • request Object GET、POST All objects belong to QueryDict object
  • Method
    • get()
      • effect : Get value from key
      • Only one value can be obtained
      • www.baidu.com/abc?a=1&b=2&c=3
    • getlist()
      • Return the value of the key as a list
      • You can get multiple values
      • www.baidu.com/abc?a=1&a=2&c=3 ( Note that there are two a)

GET attribute

# obtain get Data transferred 
def get1(request):
a = request.GET.get("a")
b = request.GET["b"]
c = request.GET.get("c")
return HttpResponse(a + " " + b + " " + c)
def get2(request):
a = request.GET.getlist('a')
a1 = a[0]
a2 = a[1]
b = request.GET.get('c')
return HttpResponse(a1 + " " + a2 + " " + b)

POST attribute

  • Use forms to simulate submission post request
  • close CSRF:
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
# 'django.middleware.csrf.CsrfViewMiddleware', 
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
  • test case
def showregister(request):
name = request.POST.get("username")
gender = request.POST.get("gender")
age = request.POST.get("age")
hobby = request.POST.getlist("hobby") # checkbox 
info = str("name:\t" + name + "\tgender:" +gender + "\tage:" + age + "\thobby"+ str(hobby))
print(info)
return HttpResponse(info)

HttpResponse object

For more information, please visit :https://www.emperinter.info/2022/05/31/django-view/


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved