跳转到主要内容

当开启维护模式时显示503错误页面。

项目描述

django-maintenance-mode

django-maintenance-mode在开启维护模式时显示503错误页面。

它在应用级别工作,因此您的Django实例应该启动。

它不使用数据库,也不阻止数据库访问。

安装

  1. 运行pip install django-maintenance-mode下载django-maintenance-mode并将维护模式包添加到您的项目中
  2. 在自定义应用程序之前,将 maintenance_mode 添加到 settings.INSTALLED_APPS
  3. maintenance_mode.middleware.MaintenanceModeMiddleware 添加到 settings.MIDDLEWARE 作为最后一个中间件
  4. 添加您的自定义 templates/503.html 文件
  5. 重启您的应用程序服务器

配置(可选)

设置

所有这些设置都是可选的,如果没有在 settings.py 中定义,将使用以下默认值。

# if True the maintenance-mode will be activated
MAINTENANCE_MODE = None
# by default, to get/set the state value a local file backend is used
# if you want to use the db or cache, you can create a custom backend
# custom backends must extend 'maintenance_mode.backends.AbstractStateBackend' class
# and implement get_value(self) and set_value(self, val) methods
MAINTENANCE_MODE_STATE_BACKEND = "maintenance_mode.backends.LocalFileBackend"

# alternatively it is possible to use the default storage backend
MAINTENANCE_MODE_STATE_BACKEND = "maintenance_mode.backends.DefaultStorageBackend"

# alternatively it is possible to use the static storage backend
# make sure that STATIC_ROOT and STATIC_URL are also set
MAINTENANCE_MODE_STATE_BACKEND = "maintenance_mode.backends.StaticStorageBackend"

# alternatively it is possible to use the cache backend
# you can use a custom cache backend by adding a `maintenance_mode` entry to `settings.CACHES`,
# otherwise the default cache backend will be used.
MAINTENANCE_MODE_STATE_BACKEND = "maintenance_mode.backends.CacheBackend"
# the fallback value that backends will return in case of failure
# (actually this is only used by "maintenance_mode.backends.CacheBackend")
MAINTENANCE_MODE_STATE_BACKEND_FALLBACK_VALUE = False
# by default, a file named "maintenance_mode_state.txt" will be created in the settings.py directory
# you can customize the state file path in case the default one is not writable
MAINTENANCE_MODE_STATE_FILE_PATH = "maintenance_mode_state.txt"
# if True admin site will not be affected by the maintenance-mode page
MAINTENANCE_MODE_IGNORE_ADMIN_SITE = False
# if True anonymous users will not see the maintenance-mode page
MAINTENANCE_MODE_IGNORE_ANONYMOUS_USER = False
# if True authenticated users will not see the maintenance-mode page
MAINTENANCE_MODE_IGNORE_AUTHENTICATED_USER = False
# if True the staff will not see the maintenance-mode page
MAINTENANCE_MODE_IGNORE_STAFF = False
# if True the superuser will not see the maintenance-mode page
MAINTENANCE_MODE_IGNORE_SUPERUSER = False
# list of ip-addresses that will not be affected by the maintenance-mode
# ip-addresses will be used to compile regular expressions objects
MAINTENANCE_MODE_IGNORE_IP_ADDRESSES = ()
# the path of the function that will return the client IP address given the request object -> 'myapp.mymodule.myfunction'
# the default function ('maintenance_mode.utils.get_client_ip_address') returns request.META['REMOTE_ADDR']
# in some cases the default function returns None, to avoid this scenario just use 'django-ipware'
MAINTENANCE_MODE_GET_CLIENT_IP_ADDRESS = None

使用 django-ipware 获取用户的真实 IP 地址

MAINTENANCE_MODE_GET_CLIENT_IP_ADDRESS = "ipware.ip.get_ip"
# the path of the function that will return the response context -> 'myapp.mymodule.myfunction'
MAINTENANCE_MODE_GET_CONTEXT = None
# list of urls that will not be affected by the maintenance-mode
# urls will be used to compile regular expressions objects
MAINTENANCE_MODE_IGNORE_URLS = ()
# if True the maintenance mode will not return 503 response while running tests
# useful for running tests while maintenance mode is on, before opening the site to public use
MAINTENANCE_MODE_IGNORE_TESTS = False
# if True authenticated users will be logged out from their current session
MAINTENANCE_MODE_LOGOUT_AUTHENTICATED_USER = False
# the absolute url where users will be redirected to during maintenance-mode
MAINTENANCE_MODE_REDIRECT_URL = None
# the type of the response returned during maintenance mode, can be either "html" or "json"
MAINTENANCE_MODE_RESPONSE_TYPE = "html"
# the template that will be shown by the maintenance-mode page
MAINTENANCE_MODE_TEMPLATE = "503.html"
# the HTTP status code to send
MAINTENANCE_MODE_STATUS_CODE = 503
# the value in seconds of the Retry-After header during maintenance-mode
MAINTENANCE_MODE_RETRY_AFTER = 3600 # 1 hour

上下文处理器

如果您想在模板中访问 maintenance_mode 状态,请将 maintenance_mode.context_processors.maintenance_mode 添加到 settings.py 中的上下文处理器列表中。

TEMPLATES = [
    {
        # ...
        "OPTIONS": {
            "context_processors": [
                # ...
                "maintenance_mode.context_processors.maintenance_mode",
                # ...
            ],
        },
        # ...
    },
]

日志记录

在维护模式启用时,您可以禁用向管理员发送 503 错误的电子邮件

LOGGING = {
    "filters": {
        "require_not_maintenance_mode_503": {
            "()": "maintenance_mode.logging.RequireNotMaintenanceMode503",
        },
        ...
    },
    "handlers": {
        ...
    },
    ...
}

上下文管理器

您可以使用上下文管理器强制代码块在维护模式下或不运行

from maintenance_mode.core import maintenance_mode_off, maintenance_mode_on

with maintenance_mode_on():
    # do stuff
    pass

with maintenance_mode_off():
    # do stuff
    pass

URLs

如果您想允许超级用户通过 URL 设置维护模式,请将 maintenance_mode.urls 添加到 urls.py

urlpatterns = [
    # ...
    re_path(r"^maintenance-mode/", include("maintenance_mode.urls")),
    # ...
]

视图

您可以使用视图装饰器在视图级别强制开启/关闭维护模式

基于函数的视图

from maintenance_mode.decorators import force_maintenance_mode_off, force_maintenance_mode_on

@force_maintenance_mode_off
def my_view_a(request):
    # never return 503 response
    pass

@force_maintenance_mode_on
def my_view_b(request):
    # always return 503 response
    pass

基于类的视图

from maintenance_mode.decorators import force_maintenance_mode_off, force_maintenance_mode_on

urlpatterns = [
    # never return 503 response
    path("", force_maintenance_mode_off(YourView.as_view()), name="my_view"),

    # always return 503 response
    path("", force_maintenance_mode_on(YourView.as_view()), name="my_view"),
]

使用方法

Python

from maintenance_mode.core import get_maintenance_mode, set_maintenance_mode

set_maintenance_mode(True)

if get_maintenance_mode():
    set_maintenance_mode(False)

from django.core.management import call_command
from django.core.management.base import BaseCommand


class Command(BaseCommand):

    def handle(self, *args, **options):

        call_command("maintenance_mode", "on")

        # call your command(s)

        call_command("maintenance_mode", "off")

模板

{% if maintenance_mode %}
<!-- html -->
{% endif %}

终端

运行 python manage.py maintenance_mode <on|off>

这不适合 Heroku,因为 任何执行 heroku runmanage.py 都将在一个独立的 worker dyno 上运行,而不是在 web dyno 上。因此,状态文件被设置,但在错误的机器上。您应该使用自定义的 MAINTENANCE_MODE_STATE_BACKEND。)

URLs

超级用户可以使用以下 URL 更改维护模式

/maintenance-mode/off/

/maintenance-mode/on/

测试

# clone repository
git clone https://github.com/fabiocaccamo/django-maintenance-mode.git && cd django-maintenance-mode

# create virtualenv and activate it
python -m venv venv && . venv/bin/activate

# upgrade pip
python -m pip install --upgrade pip

# install requirements
pip install -r requirements.txt -r requirements-test.txt

# install pre-commit to run formatters and linters
pre-commit install --install-hooks

# run tests
tox
# or
python runtests.py
# or
python -m django test --settings "tests.settings"

许可证

在 MIT 许可下发布。


支持

  • :star: 在 GitHub 上星标此项目
  • :octocat: 在 GitHub 上关注我
  • :blue_heart: 在 Twitter 上关注我
  • :moneybag: 在 Github 上赞助我

另请参阅

  • django-admin-interface - 默认管理界面,管理员本身可以自定义。弹出窗口被模态窗口取代。 🧙 ⚡

  • django-colorfield - 管理员中简单颜色字段,具有漂亮的颜色选择器。 🎨

  • django-extra-settings - 使用 django admin 仅通过配置和管理类型化额外设置。 ⚙️

  • django-redirects - 具有完全控制的重定向。 ↪️

  • django-treenode - 可能是您基于树的功能的最佳抽象模型和管理员。 🌳

  • python-benedict - 支持键列表/键路径的字典子类,I/O 快捷方式(base64、csv、json、pickle、plist、查询字符串、toml、xml、yaml)以及许多实用工具。 📘

  • python-codicefiscale - 编码/解码意大利税号 - codifica/decodifica del Codice Fiscale。 🇮🇹 💳

  • python-fontbro - 友好的字体操作。 🧢

  • python-fsutil - 懒惰开发者的文件系统实用工具。 🧟‍♂️

项目详情


下载文件

下载适合您平台的文件。如果您不确定选择哪个,请了解更多关于安装包的信息。

源分发

django-maintenance-mode-0.21.1.tar.gz (17.7 kB 查看哈希值)

上传时间

构建分发

django_maintenance_mode-0.21.1-py3-none-any.whl (16.5 kB 查看哈希值)

上传时间 Python 3

支持者