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

03_ Django get request and post request - design pattern and template layer

編輯:Python

List of articles

  • GET Request and POST request
    • Definition
    • GET Handle
    • POST Handle
  • Django Design pattern and template layer
    • MVC and MTV
      • Conventional MVC
      • Django Of MTV Pattern
    • Formwork layer
      • What is a template
      • Template configuration
      • Loading method of template
      • Interaction between view layer and template layer

Blog links https://blog.csdn.net/cPen_web
Video link https://www.bilibili.com/video/BV1vK4y1o7jH


GET Request and POST request

Definition

  • Whether it's GET still POST, Unified view functions receive requests , By judgment request.method Distinguish between specific request actions
  • Examples :
if requests.method == 'GET':
Handle GET Business logic at request
elif requests.method == 'POST':
Handle POST The business logic of the request
else:
Other request business logic
  • demonstration
# < Under the folder with the same name of the project >/views.py
def test_get_post(request):
if request.method == 'GET':
pass
elif request.method == 'POST':
# Process user submitted data 
pass
else:
pass
return HttpResponse('--test get post is ok--')

GET Handle

  • GET Request action , It is generally used to send messages to the server get data

  • Capable of producing GET The scene of the request :
    – Enter... In the browser address bar URL, After returning
    – <a href=“ Address ? Parameters = value & Parameters = value ”>
    form Forms Medium method by get

  • GET In the way of request , If there is data to be passed to the server , Usually I use Query string (Query String) Pass on 【 Be careful : Don't pass sensitive data

  • URL Format :xxx? Parameter name 1= value 1& Parameter name 2= value 2…
    – Such as :http://127.0.0.1:8000/page1?a=100&b=200

  • The server side receives parameters
    – Get client request GET Requested data

  • Method example :

request.GET[' Parameter name '] # QueryDict
request.GET.get(' Parameter name ', ' The default value is ')
request.GET.getlist(' Parameter name ')
# mypage?a=100&b=200&c=300&b=400
# request.GET=QueryDict({'a': ['100'], 'b': ['200', '400'], 'c': ['300']})
# a = request.GET['a']
# b = request.GET['b'] # Error
  • demonstration
http://127.0.0.1:8000/test_get_post?a=400
--test get post is ok--
# terminal 
<QueryDict: {
'a': ['400', '200', '100']}>
100
['400', '200', '100']
no c
# < Under the folder with the same name of the project >/urls.py
urlpatterns = [
...
path('test_get_post', views.test_get_post)
]
# < Under the folder with the same name of the project >/views.py
def test_get_post(request):
if request.method == 'GET':
print(request.GET)
print(request.GET['a'])
# The questionnaire survey = form get Hobby - Check box 
print(request.GET.getlist('a'))
print(request.GET.get('c', 'no c'))
elif request.method == 'POST':
# Process user submitted data 
pass
else:
pass
return HttpResponse('--test get post is ok--')
  • reflection
    reflection : Previous calculator functions , Can I take the query string as ?
    – http://127.0.0.1:8000/ Integers / The operator / Integers
    – http://127.0.0.1:8000/cal?x=10&y=20&op=add

POST Handle

  • POST Request action , Commonly used in Submit a large number of... To the server / Privacy data
  • The client uses forms and so on POST Request to pass the data to the server , Such as :
  • Server side Receiving parameters
         adopt request.method To determine whether it is POST request , Such as :
if request.method == 'POST':
Handle POST Request data and respond
else:
Dealing with non POST Response to the request
  • Use post Method to receive client data
request.POST[' Parameter name '] # request.POST binding QueryDict
request.POST.get(' Parameter name ', '')
request.POST.getlist(' Parameter name ')
  • Cancel csrf verification , otherwise Django Will reject the message from the client POST request , newspaper 403 Respond to
# Cancel csrf verification
- Forbid to drop settings.py in MIDDLEWARE Medium CsrfviewsMiddleWare Middleware
MIDDLEWARE = [
...
# 'django.middleware.csrf.CsrfViewMiddleware',
...
]
  • demonstration
http://127.0.0.1:8000/test_get_post

post is ok
# terminal 
uname is cpen
# < Under the folder with the same name of the project >/urls.py
urlpatterns = [
...
path('test_get_post', views.test_get_post)
]
# < Under the folder with the same name of the project >/views.py
POST_FORM = ''' <form method='post' action='/test_get_post'> user name : <input type='text' name='uname'> <input type='submit' value=' Submit '> </form> '''
def test_get_post(request):
if request.method == 'GET':
return HttpResponse(POST_FORM)
...
  • Section
    Django Handle GET request
             Query string - Small amount of data transfer
    Django Handle POST request
             Dedicated to browser submission data

Django Design pattern and template layer

MVC and MTV

Conventional MVC

MVC representative Model-View-Controller( Model - View - controller ) Pattern .
    √ M The model layer (Model), It is mainly used to encapsulate the database layer
    √ V View layer (View), Used to present results to users (WHAT + HOW)
    √ C control (Controller), Used to process requests 、 get data 、 Return results ( important )

effect : Reduce the coupling between modules ( decoupling )

Django Of MTV Pattern

MTV representative Model-Template-View( Model - Templates - View ) Pattern .
    √ M The model layer (Model) Responsible for interacting with the database
    √ T Formwork layer (Template) Responsible for rendering content to the browser (HOW)
    √ V View layer (View) Is the core , Responsible for receiving requests 、 get data 、 Return results (WHAT)

effect : Reduce the coupling between modules ( decoupling )

attach :MTV- Birth notes

Formwork layer

What is a template

  1. According to the template Dictionaries The data is dynamic html Webpage
  2. Template can The corresponding dictionary is generated dynamically according to the dictionary data passed in the view HTML Webpage

Template configuration

  • Create template folder < Project name >/templates
  • stay settings.py in TEMPLATES Configuration item
  1. BACKEND: Specify the engine for the template
  2. DIRS: Search directory for templates ( It can be one or more )
  3. APP_DIRS: Whether to use in the application templates Search for template files in folders
  4. OPTIONS: Options for templates
  • In the configuration item Parts to be modified
         Set up DIRS - 'DIRS': [os.path.join(BASE_DIR, 'templates')],

  • demonstration

# < Under the folder with the same name of the project >/settings.py
TEMPLATES = [
{

...
'DIRS': [os.path.join(BASE_DIR, 'templates')],
...

Loading method of template

  • programme 1 - adopt loader Access to the template , adopt HttpResponse To respond ( characteristic : trouble )
  • In the view function :
from django.template import loader
# 1. adopt loader Load template 
t = loader.get_template(" Template file name ")
# 2. take t convert to HTML character string 
html = t.reader( Dictionary data )
# 3. Use the response object to return the converted String content to the browser 
return HttpResponse(html)
  • demonstration
http://127.0.0.1:8000/test_html

# < Under the folder with the same name of the project >/urls.py
urlpatterns = [
...
path('test_html', views.test_html)
]
# < Under the folder with the same name of the project >/views.py
def test_html(request):
from django.template import loader
t = loader.get_template('test_html.html')
html = t.render()
return HttpResponse(html)
# < Project folder >/templates/test_html.html
<h3> I'm from the template layer ~~~~</h3>
  • programme 2 - adopt render() Directly load and respond to the template ( characteristic : convenient , Extensive use of this )
  • In the view function :
from django.shortcuts import render
return render(request, ' Template file name ', Dictionary data )
  • demonstration
http://127.0.0.1:8000/test_html

 < Under the folder with the same name of the project >/views.py
def test_html(request):
# programme 2
from django.shortcuts import render
return render(request, 'test_html.html')

Interaction between view layer and template layer

  1. In the view function Python Variables are encapsulated into Dictionaries Pass to template
  • Examples :
def xxx_view(request):
dic = {

" Variable 1": " value 1",
" Variable 2": " value 2",
}
return render(request, 'xxx.html', dic)
  1. In the template , We can use { { Variable name }} The grammar of Call the variable passed in from the view
  • demonstration
http://127.0.0.1:8000/test_html

# < Under the folder with the same name of the project >/urls.py
urlpatterns = [
...
path('test_html', views.test_html)
]
# < Under the folder with the same name of the project >/views.py
def test_html(request):
from django.shortcuts import render
dic = {
'username': 'peng', 'age': 23}
return render(request, 'test_html.html', dic)
# < Project folder >/templates/test_html.html
<h3>{
{
 username }} It's the template layer ~~~~</h3>

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