三种传输方式
三种传输方式中render和dedirect继承了HttpResponse的类
视图函数必须要返回一个HttpResponse对象
HttpResponse
render
redirect
内部简单原理:
from django.template import Template,Context
res = Template('<h1>{{ user }}</h1>') #放入html文件
con = Context({'user':{'username':'jason','password':123}}) # 模板语法参数设置
ret = res.render(con) # 传入模板语法
print(ret)
return HttpResponse(ret)
JsonResponse
1.将数据转化为json格式返回的两种方式
1.)导入json模块自己转化
def htp(request):
a = ['a',22,33,44,55,'帅']
b = json.dumps(a,ensure_ascii=False)
return HttpResponse(b)
如果要停止自动转化为bytes类型,将ensure_ascii设为False
2.)通过JsonResponse转化
1.如果要能够访问需要
safe=Flase
2.能够显示中文
json_dumps_params={'ensure_ascii': False}
如何获取文件
1.form表单如何传入文件?
method = 'post'
enctype = 'formdata'
2.如何获取文件数据?
request.FILES # 获取文件的相关信息
file_obj = request.FILES.get('file') # 拿到文件对象
file.obj.name # 拿到文件名字
# 存储文件对象
with open(...) as f:
for file in file_obj:
f.write(file)
request对象方法
1.GET
2.POST
3.method
4.FILES
5.body # 浏览器发过来的原二进制数据
6.path
7.path_info # 与6作用相同
8.get_full_path # 完整路径,能够获取完整url的参数
/htp/
/htp/
/htp/?a=1&b=2
FBV与CBV
视图函数即可以是类也可以是函数
1.函数
def func()
return
2.类
如何书写?
import django.views import View
class Mycbv(View): # 自动处理get和post请求
def get(self,request):
get请求相关
def post(self,request):
post请求相关
url路径中:
url(^'..',views.类名.as_view())
CBV源码分析
'''
1.as_view()是绑定给类调用的一种特殊方法,在自定义类继承的Views的父类之中(classmethod),允许后会自动将自定义类传入as_view()方法
2.as_view()是闭包函数,内部有view函数,
3.在view函数中定义类的对象(),将各种参数传入并且返回dispath()的执行对象
4.调用绑定给对象的dispatch方法,在该方法中会进行if判断,如果有请求发送过来,先判断请求类型,如果有请求类型则会使用反射方法getattr拿到类下的功能函数,执行并返回该对象函数的执行结果,而该函数就是所定义的get,post等函数,如果没拿到则会报没有定义,如果传入的请求方法不再django请求方法之中则也报错
'''
请求方法:http_method_names = ['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'trace']
@classonlymethod
def as_view(cls, **initkwargs): #绑定类方法调用类属性调用这个类会将类传入
"""
Main entry point for a request-response process.
"""
for key in initkwargs:
if key in cls.http_method_names:
raise TypeError("You tried to pass in the %s method name as a "
"keyword argument to %s(). Don't do that."
% (key, cls.__name__))
if not hasattr(cls, key):
raise TypeError("%s() received an invalid keyword %r. as_view "
"only accepts arguments that are already "
"attributes of the class." % (cls.__name__, key))
def view(request, *args, **kwargs):
self = cls(**initkwargs) # 生成一个类对象
if hasattr(self, 'get') and not hasattr(self, 'head'):
self.head = self.get # 如果有get且没有head,那么让head=get
self.request = request # 拿到request
# 接受参数
self.args = args
self.kwargs = kwargs
return self.dispatch(request, *args, **kwargs)
view.view_class = cls
view.view_initkwargs = initkwargs
# take name and docstring from class
update_wrapper(view, cls, updated=())
# and possible attributes set by decorators
# like csrf_exempt from dispatch
update_wrapper(view, cls.dispatch, assigned=())
return view
def dispatch(self, request, *args, **kwargs):
# self是在view内部创建的对象
# Try to dispatch to the right method; if a method doesn't exist,
# defer to the error handler. Also defer to the error handler if the
# request method isn't on the approved list.
if request.method.lower() in self.http_method_names:
# http_method_names有8中方法,get,post等等
handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
else:
handler = self.http_method_not_allowed
# handler会按照查找顺序找应该有的方法,如果没有则返回默认的报错信息
return handler(request, *args, **kwargs) # 返回函数,此时就为视图函数
def http_method_not_allowed(self, request, *args, **kwargs):
logger.warning(
'Method Not Allowed (%s): %s', request.method, request.path,
extra={'status_code': 405, 'request': request}
) # 打印日志
return http.HttpResponseNotAllowed(self._allowed_methods()) # 返回页面