• 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')
  • 相关阅读:
    浏览器为何禁止跨域(同源策略)
    viewPager
    How to remove focus without setting focus to another control?
    android ANR
    解决Ubuntu系统中文乱码显示问题
    USB 3.0规范中译本 第6章 物理层
    库&框架-----CDN网络引用总结
    18_如何排错
    17_今日回顾
    16_sql注入的原理及处理
  • 原文地址:https://www.cnblogs.com/tangda/p/10719478.html
Copyright © 2020-2023  润新知