Request and response
request
Request construction
Start line + request header + request body
HTTP request method
- The page information specified by the GET request returns the entity subject
- HEAD is similar to get request. There is no specific content in the return response. It is generally used to debug and obtain the message header**
- POST submits data processing requests to specified resources, such as submitting forms. The data is contained in the request body. It may lead to the establishment of new resources or the modification of existing resources
- The data transmitted by PUT to the server replaces the content of the formulated document and is updated
- DELETE requests the server to DELETE the specified page
- CONNECT HTTP/1.1 gives you the ability to connect to the proxy server changed to pipeline mode to access the Internet scientifically.
- OPTIONS allows you to view the performance of the server
- The request received by the TRACE echo server is mainly used for testing or diagnosis
Django's request
The first parameter in the view function, HttpRequest object
- path_info:URL string
- Method: indicates the request method
- GET: QueryDict query dictionary object, request data
- POST: QueryDict queries dictionary objects and requests data
- FILES: similar to the dictionary object, it contains the uploaded file information
- Cookies sessioin body scheme
- request.get_full_path() requests the full path
- request. Metadata (message header) in meta request, such as request Meta ['REMOTE_ADDR'] client IP address
Extract the corresponding request data from the view function
def test_request(request): print("URL%s"%request.path_info) print("method%s"%request.method) print("GET Request data:",request.GET) return HttpResponse('Return to page')
request http://localhost:8000/testrequest?name=%E9%94%8B%E5%93%A5
response
Starting line [agreement, status code] + response header + response body
HTTP status code:
- 200 request succeeded
- 301 permanent redirection, resources are permanently transferred to other URLs, such as changing domain names
- 302 temporary redirection. Such as user login
- 401 the requested resource does not exist
- 500 internal server error, code error?
Response object in Django
HttpResponse (content responder, content_type responder, CT header, status code)
Type of CT head:
GET\POST request
All requests are received by the view function through the judgment of request Method distinguish request actions:
def test_get_post(request): if request.method == 'GET': res = '<h1>You submitted GET</h1>' elif request.method == 'POST': res = '<h1>Handled post Data from</h1>' return HttpResponse(res)
In the get method, you can pass in multiple parameters and use request GET. GetList ("a") can obtain all the values of keyword parameters, such as localhost \ views? A = 1 & A = 2 & A = 333, you can get the terminal return value {"a": [1,2333]},
If you use request Get ['a'], you can only get 333 in the above request
If you use request GET. Get ('c ',' no c ') returns "no c" because the C parameter is not defined in the keyword parameter
POST processing
Namely
if request.method == 'POST': request.POST['Parameter name'] request.POST.get('Parameter name','The return value of the keyword parameter was not obtained') request.POST.getlist('Parameter name') # It is the same as getting the GET method # Cancel csrf verification, otherwise the post request sent by the client will be rejected and reported as 403 Cancel the search and comment the corresponding statement
The GET query string cannot be sensitive data, and a small amount of data is passed
Django's design pattern and template layer
MVC traditional structure
Mode view controller
The function is to reduce the coupling between modules
Layer M mainly encapsulates the database layer,
V is used to show the results to users (solve two problems, what data to display and how to display),
C core brain, processing requests, obtaining data and returning results
MTV structure (Django)
Model template view mode
M is responsible for interacting with the database
T is responsible for rendering content to browsers, css and js
V is the core, responsible for receiving requests, obtaining data and returning results
Template layer
The template is an HTML web page that changes dynamically according to dictionary data.
1. Create templates folder;
2. Set settings Py, mainly DIRS
3. Edit view function
4. Add route
Create template folder < project name > / templates
In settings TEMPLATES configuration item in PY
- BACKEND: Specifies the engine of the template
- DIRS: search directory of the template (can be one or more)
- APP_DIRS: do you want to search for template files in the templates folder in the app
- OPTIONS: OPTIONS for templates
The part to be modified in the configuration item
Set DIRS - 'DIRS': [os.path.join(BASE_DIR,' templates')]
View function editing
Reference render function to simplify the method of template reference, pass in dictionary for the interaction between template and database, and use double curly brackets to reference data on the template page
from django.shortcuts import render def test_html(request): dic = {'username':'admin','age':18} return render(request,'test_html.html Template page',dic Dictionary for incoming template)
Web page template
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Template view</title> </head> <body> <h1>Template layer</h1> <p>user name:{{username}}</p> <p>Age:{{age}}</p> </body> </html>
Variable types that can be passed into the template layer
- character string
- integer
- array
- tuple
- Dictionaries
- method
- Class instantiation object
Syntax for using variables in templates
{{variable name}}
{{variable name. index}}
{{variable name. key}}
{{object. Method}}
{{function name}}
Template layer variable instance
# Define the function referenced later def test_html_func(): return 'function import!' # Define the class referenced later class testclass: def say(self): return 'test_class_say_hello' # View function def test_html(request): dic = {} dic['username'] = 'bigfeng' dic['age'] = 33 dic['friends'] = ['ares', 'peter', 'jack'] dic['fav'] = {'fruit': 'apple', 'sport': 'swim'} dic['func'] = test_html_func dic['class'] = testclass return render(request, 'test_html.html', dic)
template file
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Template view</title> </head> <body> <h1>Template layer</h1> <p>user name:{{username}}</p> <p>Age:{{age}}</p> <p>Friend's name:{{friends}}</p> <p>First friend:{{friends.0}}</p> <p>Favorite fruit:{{fav.fruit}}</p> <p>Favorite sports:{{fav.sport}}</p> <p>Function reference:{{func}}</p> <p>Class reference:{{class.say}}</p> </body> </html>
Return to page