Django视图层
'''
HttpResponse,返回字符串
render,返回html页面,并且可以给html文件传值
redirect,重定向
视图函数一定会返回一个HttpResponse对象
'''
JsonResponse
from django.http import JsonResponse
user_dict = {'姓名': '123', '年龄': '123'}
return JsonResponse(user_dict, {'ensure_ascii': False})
'''ensure_ascii=True是json关键字参数默认值,通过向JsonResponse类传入用于修改这个默认值的字典可以使json不再将中文字符转为unicode编码'''
user_hobby_list = [1,2,3,4,5,6]
return JsonResponse(user_hobby_list,safe=False)
# 将非字典类型序列化需要将safe参数值设置为False
# 前后端序列化与反序列化
javascript | python
---|---
JSON.stringify() | json.dumps()
JSON.parse() | json.loads()
form表单上传文件及后端获取
# form表单上传文件类型的数据:1.method指定为post 2.enctype指定为form-data
# request.POST只能获取普通键值对信息
'''
<form action="" method="post" enctype="multipart/form-data">
<p>username:<input type="text" name="username" class="form-control"></p>
<p>password:<input type="text" name="password" class="form-control"></p>
<p>file:<input type="file" name="file"></p>
<input type="submit" value="提交">
</form>
def upload_file(request):
if request.method == 'POST':
file_obj = request.FILES.get('file')
with open(file_obj.name,'wb') as f: # 没有指定文件路径,默认保存在项目文件夹下
for line in file_obj:
f.write(line)
return render(request,'form.html')
'''
request对象方法
'''
request.method
request.POST
request.GET
request.Files
request.path/request.path_info 只获取路由部分
request.get_full_path() 获取用户提交url中除去ip和port后所有的路径信息(包含?后的参数)
request.body 浏览器发来的原生二进制数据
'''
FBV与CBV
# 视图层既可以是视图函数,也可以是类
url(r'^login/', views.MyLogin.as_view(), name='app02_login'),
class MyLogin(View):
def get(self, request):
return HttpResponse('你提交了get请求,这个请求被django识别并交由这里的代码处理')
def post(self,request):
return HttpResponse('你提交了post请求,这个请求被django识别并交由这里的代码处理')
CBV源码
url('login/',views.MyLogin.as_view()),
# 回顾,函数名/方法名()执行优先级最高
@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(
'The method name %s is not accepted as a keyword argument '
'to %s().' % (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) # self = MyLogin(**initkwargs) 产生一个Mylogin对象
self.setup(request, *args, **kwargs)
if not hasattr(self, 'request'):
raise AttributeError(
"%s instance has no 'request' attribute. Did you override "
"setup() and forget to call super()?" % cls.__name__
)
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
# as_view()内定义了闭包函数view(),并且返回值就是view函数的内存地址,在django启动后立即执行as_view(),即得:
url('login/',views.view),