2021/6/14 django 视图层

'''
request
属性
.scheme 字符串形式,返回HTTP协议(https/http)
.body 二进制,返回请求体,即ajax json数据
.method 字符串,返回请求方式(GET/POST/PUT/PATCH/DELETE/HEAD/OPTIONS/TRACE)
.POST QueryDict字典,返回POST请求数据
.GET QueryDict字典,返回GET请求数据(GET请求中仅能最大包含4kb数据)
.get(k)
.getlist(k)
.path 返回url中,ip后面的路径,不包含路径中?后面的参数(/index/)
.path_info 和path一样
.encoding 字符串,返回前端提交数据的编码格式(utf8/gbk/none),none表示默认使用浏览器的编码格式
也可以用于设置后端读取前端数据时用的编码格式
.FILES 获取前端上传的文件数据(ajax上传FormData对象/form表单设置multipart/form-data)
.COOKIES 字典,包含所有的cookie
.META 字典,包含所有的HTTP头部
.user AUTH_USER_MODEL 类型的对象,表示当前登录的用户。
.session 一个既可读又可写的类似于字典的对象,表示当前的会话。只有当Django 启用会话的支持时才可用。
方法
.is_ajax() bool值,判断是否为ajax请求
.get_full_path() 字符串,返回ip后面的路径,包含路径中?后面的参数(/index/?username=xxx&password=xxx)
.get_host() 字符串,获取IP:Port
.is_secure() bool值,返回是否https协议
用户对象方法
is_authenticated() bool值,判断用户是否登录
set_password('new_password') 修改用户密码
.save() 保存修改
check_password(old_password) bool值,对比密码是否正确
HttpResponse
from django.shortcuts import HttpResponse
a = HttpResponse()
a['Content-Type'] = 'text/html'
del a['charset']
属性
.content 获得响应内容
.charset 获得响应的编码格式
.status_code 获得响应的状态码
JsonResponse
from django.http import JsonResponse
JsonResponse(data, json_dumps_params={'ensure_ascii':False}, safe=True)
ensure_ascii=False: 不对内部数据进行转码
safe=True (默认) 只能序列化字典
False 可以序列化其他数据

render
render(request,
'html',
{'前端调用名': 'xx'},
content_type='text/html',
status=200
using=None
)

redirect
redirect(
url,
permanent=False 默认,返回一个临时的重定向
True 永久,返回永久的重定向
)

from django.shortcuts import HttpResponse
def xxx(request):
return HttpResponse('xxx')

from django.views import View
class xxx(View):
def get(self, request, *args, **kwargs):
pass
def post(self, request, *args, **kwargs):
pass
def put(self, request, *args, **kwargs):
pass
def delete(self, request, *args, **kwargs):
pass
url('', views.xxx.as_view())
源码解释
在as_view()中会返回 view方法
view方法中会返回dispatch方法
dispatch方法中会进行反射,从而调用cbv中对应的方法

CBV装饰器-认证
@method_decorator(login_auth, name='')

request
属性
method
POST
GET
get(k)
getlist(k)
FILES
body

META
encoding
path
path_info
scheme
session
COOKIES
方法
is_ajax()
is_secure()
get_full_path()
get_host()
HttResponse
a = HttpResponse('xx')
a.content
a.charset
a.status_code
a['Content-Type'] = 'xx'
del a['xxx']
JsonResponse
(data, json.dumps.params=, ensure_ascii=True safe=True)

render
(request,
'',
{'':''},
content_type='text/html',
status=200
using=None
)
redirect
permanent=False/True
'''
posted @ 2021-06-14 21:31  zzwYYYYYY  阅读(63)  评论(0)    收藏  举报