Rails 控制器继承的 Django 等价物

Django equivalent(s) of Rails controller inheritance

我在 Rails 中使用的一个常见模式是控制器继承。我会将各种共享功能放入一个基本控制器中,ApplicationController 或更多 domain-/concern-specific 控制器,然后从该基本控制器继承以创建单独的控制器。

以下是我已经完成或看到的一些 Rails 应用程序与控制器继承有关的事情。

以下是我做过或看到各种 Django 应用程序做过的一些事情。它们与上述内容不太一致,并且存在一些我不确定如何以干净的方式复制的差距。

在 Django 中实现上述目标的 recommended/idiomatic 方法是什么?当然,Rails 和 Django 在哲学和架构上存在一些差异,因此 "equivalent of X" 不会是绝对的 one-to-one。尽管如此,我还是希望对如何执行这些操作有所了解 commonly-desired use-cases.

感谢阅读这面文字墙,并提前感谢您的见解!

P.S., 一个相关的问答,涉及其中的一些要点: Django equivalent to Rails application_controller

对于等效的 django methods/functions:

Place for certain kinds of shared code to live.

如果它在视图中,请使用 Class Based Views;因为这些就像普通的 classes,你可以从它们继承并扩展它们(称为 "mixins" - 因为你混合了你需要的功能)。

参考:Class Based Views

Apply shared pre-/post-filters to the request. Potentially, modify the incoming request, modify the outgoing response, or alter the flow of the request, using e.g. before_filter. Common use-cases include authentication/authorization, request validation, and app state pre-condition checking.

有很多方法可以做到这一点;取决于您希望实施的具体程度或通用程度:

  1. 装饰器(用于函数和基于 class 的视图)
  2. Class 继承(对于基于 class 的视图)
  3. URL 级别的包装函数(类似于装饰器,但外推到 URL 映射器)。
  4. 中间件(更高层次的抽象)。

Provide shared rendering context for state-/session-dependent parts of parts of shared base template, e.g. a filter sets some instance variables which the base template then uses. For example, a site has a shared header which displays certain domain-specific details of the current user and session.

在 django 中,这种模板范围的功能由 template context processors 提供;它接受请求和 return 一个字典(映射),然后在所有模板中都可用。