Django-08 data processing (acquisition, return)

retrieve data

URL splicing parameters

request.GET.get('键') # 获取单个值,get('键',默认值)
request.GET.getlist('键') # 获取多个值,getlist('键',默认值)

Form

request.POST.getlist('键')

Non-Form Data

json.loads(request.body) # 直接获取请求体,再转化为字典

Request headers

request.META['CONTENT_TYPE']

Common request headers:

CONTENT_LENGTH – The length of the request body (as a string).

CONTENT_TYPE– The MIME type of the request body.

HTTP_ACCEPT– Acceptable content types for the response.

HTTP_ACCEPT_ENCODING– Acceptable encodings for the response.

HTTP_ACCEPT_LANGUAGE– Acceptable languages for the response.

HTTP_HOST– The HTTP Host header sent by the client.

HTTP_REFERER– The referring page, if any.

HTTP_USER_AGENT– The client’s user-agent string.

QUERY_STRING– The query string, as a single (unparsed) string.

REMOTE_ADDR– The IP address of the client.

REMOTE_HOST– The hostname of the client.

REMOTE_USER– The user authenticated by the Web server, if any.

REQUEST_METHOD– A string such as"GET"or"POST".

SERVER_NAME– The hostname of the server.

SERVER_PORT– The port of the server (as a string).

Other common HttpRequest object attributes

method: A string indicating the HTTP method used for the request. Common values ​​include:'GET','POST'.

user: The requested user object.

path: A string representing the complete path of the requested page, excluding the domain name and parameter part.

encoding: A string representing the encoding method of the submitted data.

	如果为None则表示使用浏览器的默认设置,一般为utf-8。

	这个属性是可写的,可以通过修改它来修改访问表单数据使用的编码,接下来对属性的任						何访问将使用新的encoding值。

FILES: A dictionary-like object that contains all uploaded files.

Return data

HttpResponse

HttpResponse(content=响应体, content_type=响应体数据类型, status=状态码)

Django provides a series of subclasses of HttpResponse, which can quickly set the status code

  • HttpResponseRedirect 301
  • HttpResponsePermanentRedirect 302
  • HttpResponseNotModified 304
  • HttpResponseBadRequest 400
  • HttpResponseNotFound 404
  • HttpResponseForbidden 403
  • HttpResponseNotAllowed 405
  • HttpResponseGone 410
  • HttpResponseServerError 500

JsonResponse

Return json data, automatically convert dictionary to json string

from django.http import JsonResponse

def response(request):
    return JsonResponse({'city': 'beijing', 'subject': 'python'})

redirect

from django.shortcuts import redirect

def response(request):
    return redirect('/get_header')

reverse analysis

When the page is frequently jumped, the address can be dynamically obtained.

Total routing

Use namespace to alias sub-applications

# path('',include(('子应用.urls','子应用名'),namespace='别名'))
path('',include(('request_response.urls','request_response'),namespace='request_response'))

Sub-application

Alias ​​the sub-routes of sub-applications

path('indexhaha/',views.IndexView.as_view(),name='index')

View

Use the alias of the route to dynamically resolve the real address of the route

# ret_url = reverse('子应用名:子路由名')
ret_url = reverse('request_response:index')
return redirect(ret_url)

Definition and use of middleware

Django presets six methods in the middleware. These six methods will be automatically executed at different stages to intervene in input or output.

  1. Initialization method:

Start the Django program and automatically call once when initializing the middleware to determine whether to enable the current middleware

def __init__(self, get_response=None):
  pass

2. The method before processing the request: (important)

Before processing each request, it is called automatically and returns None or HttpResponse object

def process_request(self, request):
  pass

3. The method before processing the view: (important)

Before processing each view, it is automatically called and returns None or HttpResponse object

def process_view(self, request, view_func, view_args, view_kwargs):
  pass

4. The method before processing the template response:

Before processing each template response, it is automatically called and returned to the response object that implements the render method

def process_template_response(self, request, response):
  pass

5. The method after processing the response: (important)

Before each response is returned to the client, it is automatically called and returns the HttpResponse object

def process_response(self, request, response):
  pass

6 Exception handling:

When the view throws an exception, it is automatically called and returns an HttpResponse object

def process_exception(self, request,exception):
  pass

Case study

Define middleware

The mymiddleware file can be created in the project directory

# 导入中间件的父类
from django.utils.deprecation import MiddlewareMixin


class TestMiddleware1(MiddlewareMixin):
    """自定义中间件"""
    def process_request(self, request):
        """处理请求前自动调用"""
        print('process_request1 被调用')

    def process_view(self, request, view_func, view_args, view_kwargs):
        # 处理视图前自动调用
        print('process_view1 被调用')

    def process_response(self, request, response):
        """在每个响应返回给客户端之前自动调用"""
        print('process_response1 被调用')
        return response

Register middleware

MIDDLEWARE = [
    'book.middleware.TestMiddleware1',  # 添加中间件
]

Define the view

def middleware(request):
    print('view 视图被调用')
    return HttpResponse('OK')

Execution order

Before the view function is processed, the middleware is executed sequentially from top to bottom

After the view function is processed, the middleware is executed sequentially from bottom to top

Guess you like

Origin blog.csdn.net/weixin_47761086/article/details/115378175