zoukankan      html  css  js  c++  java
  • Django基础之给视图加装饰器

    1. 使用装饰器装饰FBV

    FBV本身就是一个函数,所以和给普通的函数加装饰器无差: ```Python def wrapper(func): def inner(*args, **kwargs): start_time = time.time() ret = func(*args, **kwargs) end_time = time.time() print("used:", end_time-start_time) return ret return inner

    @wrapper
    def add_class(request):
    if request.method == "POST":
    class_name = request.POST.get("class_name")
    models.Classes.objects.create(name=class_name)
    return redirect("/classa/")
    return render(request, "add_class.html")

    <h2>2. 使用装饰器装饰CBV</h2>
    类中的方法与独立函数不完全相同,因此不能直接将函数装饰器应用于类中的方法,我们需要先将其转换为方法装饰器。<br>
    django中提供了method_decorator装饰器用于将函数装饰器转化为方法装饰器。<br>
    使用method_decorator有2种方法能装饰CBV。
    
    <h3>2.1 给dispatch方法加装饰器</h3>
    ```Python
    from django.vies import View
    from django.utils.decorators import method_decorator
    from django.shortcuts import render, HttpResponse, redirect
    
    def wrapper(func):
        def inner(*args, **kwargs):
            start_time = time.time()
            ret = func(*args, **kwargs)
            end_time = time.time()
            print("used:", end_time-start_time)
            return ret
        return inner
    
    class Login(View):
        @method_decorator(wrapper)
        def dispatch(self, request, *args, **kwargs):
            obj = super(Login, self).dispatch(request, *args, **kwargs)
            return obj
    
        def get(self, request):
            return render(request, "login.html")
    
        def post(self, request):
            print(request.POST.get("user"))
            return HttpResponse("Login.post")
    

    2.3 在类上添加装饰器(推荐)

    ```Python from django.views import View from django.utils.decorators import method_decorator from django.shortcuts import render, HttpResponse, redirect

    def wrapper(func):
    def inner(args, **kwargs):
    start_time = time.time()
    ret = func(
    args, **kwargs)
    end_time = time.time()
    print("used:", end_time-start_time)
    return ret
    return inner

    @method_decorator(wrapper, name="dispatch")
    class AddClass(View):

    def get(self, request):
        return render(request, "add_class.html")
    
    def post(self, request):
        class_name = request.POST.get("class_name")
        models.Classes.objects.create(name=class_name)
        return redirect("/class/")
    
  • 相关阅读:
    Eclipse Clojure 开发插件
    leiningen安装记录
    XX-NET史上最详细完整教程
    使用Chrome浏览器设置XX-net的方法
    Sublime text 3搭建Python开发环境及常用插件安装
    python集合(set)类型的操作
    python编码问题在此终结
    新版的 selenium已经放弃PhantomJS改用Chorme headless
    python爬虫积累(一)--------selenium+python+PhantomJS的使用(转)
    Pyinstaller打包selenium去除chromedriver黑框问题解决!!!
  • 原文地址:https://www.cnblogs.com/yang-wei/p/9997687.html
Copyright © 2011-2022 走看看