获取数据
url拼接的参数
request.GET.get('键') # 获取单个值,get('键',默认值)
request.GET.getlist('键') # 获取多个值,getlist('键',默认值)
表单
request.POST.getlist('键')
非表单 Non-Form Data
json.loads(request.body) # 直接获取请求体,再转化为字典
请求头headers中
request.META['CONTENT_TYPE']
常见的请求头:
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).
其他常用HttpRequest对象属性
method:一个字符串,表示请求使用的HTTP方法,常用值包括:‘GET’、‘POST’。
user:请求的用户对象。
path:一个字符串,表示请求的页面的完整路径,不包含域名和参数部分。
encoding:一个字符串,表示提交的数据的编码方式。
如果为None则表示使用浏览器的默认设置,一般为utf-8。
这个属性是可写的,可以通过修改它来修改访问表单数据使用的编码,接下来对属性的任 何访问将使用新的encoding值。
FILES:一个类似于字典的对象,包含所有的上传文件。
返回数据
HttpResponse
HttpResponse(content=响应体, content_type=响应体数据类型, status=状态码)
Django提供了一系列HttpResponse的子类,可以快速设置状态码
- HttpResponseRedirect 301
- HttpResponsePermanentRedirect 302
- HttpResponseNotModified 304
- HttpResponseBadRequest 400
- HttpResponseNotFound 404
- HttpResponseForbidden 403
- HttpResponseNotAllowed 405
- HttpResponseGone 410
- HttpResponseServerError 500
JsonResponse
返回json数据,将字典自动转为json字符串
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反解析
频繁跳转页面的时候,可以动态获得地址。
总路由
用namespace给子应用起别名
# path('',include(('子应用.urls','子应用名'),namespace='别名'))
path('',include(('request_response.urls','request_response'),namespace='request_response'))
子应用中
给子应用的子路由起别名
path('indexhaha/',views.IndexView.as_view(),name='index')
视图中
使用路由的别名,动态解析出该路由的真实地址
# ret_url = reverse('子应用名:子路由名')
ret_url = reverse('request_response:index')
return redirect(ret_url)
中间件的定义和使用
Django在中间件中预置了六个方法,这六个方法会在不同的阶段自动执行,对输入或输出进行干预。
- 初始化方法:
启动Django程序,初始化中间件时,自动调用一次,用于确定是否启用当前中间件
def __init__(self, get_response=None):
pass
2.处理请求前的方法:(重要)
在处理每个请求前,自动调用,返回None或HttpResponse对象
def process_request(self, request):
pass
3.处理视图前的方法:(重要)
在处理每个视图前,自动调用,返回None或HttpResponse对象
def process_view(self, request, view_func, view_args, view_kwargs):
pass
4.处理模板响应前的方法:
在处理每个模板响应前,自动调用,返回实现了render方法的响应对象
def process_template_response(self, request, response):
pass
5.处理响应后的方法:(重要)
在每个响应返回给客户端之前,自动调用,返回HttpResponse对象
def process_response(self, request, response):
pass
6 异常处理:
当视图抛出异常时,自动调用,返回一个HttpResponse对象
def process_exception(self, request,exception):
pass
案例
定义中间件
创建mymiddleware文件 可以在工程目录下
# 导入中间件的父类
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
注册中间件
MIDDLEWARE = [
'book.middleware.TestMiddleware1', # 添加中间件
]
定义视图
def middleware(request):
print('view 视图被调用')
return HttpResponse('OK')
执行顺序
在视图函数被处理前,中间件由上至下依次执行
在视图函数被处理后,中间件由下至上依次执行