zoukankan      html  css  js  c++  java
  • Django --- 视图层

    1.视图函数

    视图函数简称视图,是一个简单的python函数,他接收web请求并返回文本响应,响应可以是一个网页,一个重定向,或者是字符串,什么都可以,但是一定要又响应。

    2.小白必会三板斧

    1.HttpResponse

    可以返回字符串

    2.render

    可以调用HTML文件进行操作

    3.redirect

    重定向

    3.JsonResponse

    可以将数据按照json串的格式传给前端,但是默认的是只能传字典,字符编码默认是ascii。

    from django.http import JsonResponse
    def index(request):
        # dic = {'username':'wang','hobby':'骑行'}
        dic = ['上海']
        return JsonResponse(dic,safe=False,json_dumps_params = {'ensure_ascii':False},)
    
    # 1.json_dumps_params = {'ensure_ascii':False},)   更改字符编码格式
    # 2.safe=False   更改传入的数据类型
    

    4.FBV与CBV

    FBV:基于函数的视图

    CBV:基于类的视图

    # views视图中
    from django.views import View
    
    class MyLogin(View):
        def get(self,request):
            print('我是mylogin里面的get方法')
            return render(request,'login.html')
    
        def post(self,request):
            print('我是mylogin里面的post方法')
            return render(request,'ceshi.html')
        
    # urls.py中
     url(r'^login/',views.MyLogin.as_view())
    

    5.CBV源码

    # View源代码
    class View(object):
    
        http_method_names = ['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'trace']
    
        def __init__(self, **kwargs):
            for key, value in six.iteritems(kwargs):
                setattr(self, key, value)
    
        @classonlymethod
        def as_view(cls, **initkwargs):
            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
                self.request = request
                self.args = args
                self.kwargs = kwargs
                return self.dispatch(request, *args, **kwargs)
            view.view_class = cls
            view.view_initkwargs = initkwargs
    
            update_wrapper(view, cls, updated=())
    
            update_wrapper(view, cls.dispatch, assigned=())
            return view
    
        def dispatch(self, request, *args, **kwargs):
        
            if request.method.lower() in self.http_method_names:
                handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
            else:
                handler = self.http_method_not_allowed
            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())
        
    # views.py中的代码
    class MyLogin(View):
        def get(self,request):              #  方法名一定是八大请求方法的名字
            print('我是mylogin里面的get方法')
            return render(request,'login.html')
    
        def post(self,request):
            print('我是mylogin里面的post方法')
            return render(request,'ceshi.html')
     
    # urls.py中的代码
    url(r'^login/',views.MyLogin.as_view()),    本质上还是FBV,
    

    6.给CBV加装饰器

    1.直接放在类中方法的上面

    2.使用内置模块,放在类方法上面 ----- 推荐

    from django.utils.decorators import method_decorator
    
    @method_decorator(outter)    # 括号内写上装饰器函数,放在需要被装饰的类方法上
    

    3.使用内置方法,直接放在类上面

    from django.utils.decorators import method_decorator
    
    @method_decorator(outter,name='post')
    

    7.form表单传文件需要注意的事项:

    1.mothod必须改成post

    2.enctype改成formdata格式

    前期在使用post超后端发送请求的时候,需要去settings配置文件中注释掉一个中间件crf。

    # 针对于文件的操作使用的是
    file_obj = request.FILES         # django会将文件数据放在request.FILES中
    file_obj.name 
    
    with open(file_obj.name,'wb') as f:
        for line in file_obj:
            f.write(line)
    
  • 相关阅读:
    读 Kafka 源码写优雅业务代码:配置类
    如何安装FTP服务器,并实现文件共享
    Merge into用法总结
    Insomnia 跟 Postman 类似的软件
    iOS dealloc中初始化weak指针崩溃防护
    Centos7安装febootstrap
    获取 linux 系统 CPU、内存、磁盘 IO 等信息的脚本
    Git本地远程仓库
    网络及服务故障的排查思路
    Git配置远程仓库(密匙链接)
  • 原文地址:https://www.cnblogs.com/whkzm/p/11939973.html
Copyright © 2011-2022 走看看