如何在基于Django类的视图中定义transaction.atomic?

Jes*_*ose 6 django

我希望post基于类的视图中的方法是原子的.我已经定义了这个类:

class AcceptWith(View):
    @method_decorator(login_required)
    @method_decorator(user_passes_test(my_test))
    @method_decorator(transaction.atomic)
    def dispatch(self, *args, **kwargs):
        return super(AcceptWith, self).dispatch(*args, **kwargs)
Run Code Online (Sandbox Code Playgroud)
  1. 它是否正确?
  2. 我可以只使post方法原子化吗?

Kev*_*nry 18

假设您正在定义自己的方法来处理POST,只需将transaction.atomic装饰器直接应用于该方法即可.

class AcceptWith(View):
    @transaction.atomic
    def post(self, request, *args, **kwargs):
        # your code here will be executed atomically
Run Code Online (Sandbox Code Playgroud)

  • @madzohan:没必要.对于设计为在参数签名中返回没有`self`的函数的装饰器,需要`method_decorator`.`transaction.atomic` [不关心](https://github.com/django/django/blob/059f5d17c5fe92d6b4c5d189020ea59e9bed4472/django/db/transaction.py#L290)函数签名.请注意管理员代码中的[此示例](https://github.com/django/django/blob/731f313d604a6cc141f36d8a1ba9a75790c70154/django/contrib/auth/admin.py#L93). (3认同)
  • @rtindru:你通常将装饰器应用于`dispatch()`的原因是1)它作为所有HTTP请求方法的所有基于类的视图的公共入口点; 2)它的参数签名与基于函数的视图匹配(除了`self`,使用`method_decorator`处理),允许你使用相同的装饰器(例如`login_required`).除了这些不适用的考虑之外,装饰器的工作方式与您在任何方法上的预期一样. (2认同)