django 实战篇之视图层

视图层(views.py)

django必会三板斧
HttpResponse >>> 返回字符串
render >>> 支持模板语法,渲染页面,并返回给前端
redirect >>> 重定向(即可以重定向到别人的网址,也可以重定向到自己路由)

django返回的数据都是HttpResponse对象

JsonResponse(返回json格式的数据)  如何将json打包的汉字不被编译

用到了一个技术点:

from django.http import JsonReponse
import json

def  index(reuqest):
    return JsonReponse({"name":"大帅比”,“age”:18},json_dumps_params = {"ensure_ascii":False})

FBV与CBV
FBV:基于函数的视图
CBV:基于类的视图(查看源码发现用到了 闭包技术  和反射技术)

from django.views import View

class Login(View):
def get(self,request):
# return HttpResponse('get')
return render(request,'login.html')

def post(self,request):
return HttpResponse('post')
源码补充:
第一个疑问:
url(r'^login/',views.Login.as_view()) # >>>等价于 url(r'^login/',views.view)

第二个疑问:
为什么我get请求就走get方法,post请求就走post方法

文件上传
前端需要注意的地方
form表单method必须是post
enctype必须是multipart/form-data

文件上传
    前端需要注意的地方
        form表单method必须是post
        enctype必须是multipart/form-data
        def upload(request):
            if request.method == 'POST':
                # print(request.FILES)
                # print(type(request.FILES))
                # print(request.FILES.get('myfile'))
                # print(type(request.FILES.get('myfile')))
                # 获取文件对象
                file_obj = request.FILES.get('myfile')
                # print(file_obj.name)
                # 获取文件名
                file_name = file_obj.name
                # 文件读写操作
                with open(file_name,'wb') as f:
                    # for line in file_obj:
                    for line in file_obj.chunks():
                        f.write(line)
            return render(request,'upload.html')

猜你喜欢

转载自www.cnblogs.com/tangda/p/10719478.html