django 有没有类似于flask的before_request


django的views.py中有木有像flask那样的before_request的操作?

python-django

gurgu 9 years, 9 months ago

不知道你要控制多大范围. 如果是整个应用控制可以用使用@phodal所说的Middle
但是django和flask不一样flask有 blueprint 的存在, 可以方便的应用在部分应用上.
貌似django没有这个功能. 想要统一处理的话科研室试试 class View , 做一个 View 基类.初始化就可以达到before_request的功能了, 然后继承这个view就可以了.

smooth answered 9 years, 9 months ago

Django的before_request叫 Middleware

看看 settings.py 会有类似下面的内容:


 MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware',
    'django.contrib.redirects.middleware.RedirectFallbackMiddleware',
    "core.middleware.TemplateForDeviceMiddleware",
)

御坂御坂御坂 answered 9 years, 9 months ago

Your Answer