zoukankan      html  css  js  c++  java
  • 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')
  • 相关阅读:
    读者试读怎么评价这本书
    性能优化是数据库应用的核心问题
    ExtJS 4 Grid组件
    发挥你的SATA硬盘
    MOSS 修改了服务器账号密码后的问题
    速度真快,ExtJS第5个预览版发布
    Ext JS 4 Preview Release 4发布
    显卡性能排行榜
    手机操作系统发展史
    程序解读身份证的密码
  • 原文地址:https://www.cnblogs.com/tangda/p/10719478.html
Copyright © 2011-2022 走看看