Flask-blueprints

本文介绍了Flask中的Blueprint类,展示了如何定义蓝图,处理静态文件,注册CLI命令,并提供了用于访问资源文件的方法。重点在于send_file和open_resource等辅助功能的实现。
摘要由CSDN通过智能技术生成

from __future__ import annotations

import os

import typing as t

from datetime import timedelta

from .cli import AppGroup

from .globals import current_app

from .helpers import send_from_directory

from .sansio.blueprints import Blueprint as SansioBlueprint

from .sansio.blueprints import BlueprintSetupState as BlueprintSetupState  # noqa

from .sansio.scaffold import _sentinel

if t.TYPE_CHECKING:  # pragma: no cover

    from .wrappers import Response


 

class Blueprint(SansioBlueprint):

    def __init__(

        self,

        name: str,

        import_name: str,

        static_folder: str | os.PathLike[str] | None = None,

        static_url_path: str | None = None,

        template_folder: str | os.PathLike[str] | None = None,

        url_prefix: str | None = None,

        subdomain: str | None = None,

        url_defaults: dict[str, t.Any] | None = None,

        root_path: str | None = None,

        cli_group: str | None = _sentinel,  # type: ignore

    ) -> None:

        super().__init__(

            name,

            import_name,

            static_folder,

            static_url_path,

            template_folder,

            url_prefix,

            subdomain,

            url_defaults,

            root_path,

            cli_group,

        )

        #: The Click command group for registering CLI commands for this

        #: object. The commands are available from the ``flask`` command

        #: once the application has been discovered and blueprints have

        #: been registered.

        self.cli = AppGroup()

        # Set the name of the Click group in case someone wants to add

        # the app's commands to another CLI tool.

        self.cli.name = self.name

    def get_send_file_max_age(self, filename: str | None) -> int | None:

        """Used by :func:`send_file` to determine the ``max_age`` cache

        value for a given file path if it wasn't passed.

        By default, this returns :data:`SEND_FILE_MAX_AGE_DEFAULT` from

        the configuration of :data:`~flask.current_app`. This defaults

        to ``None``, which tells the browser to use conditional requests

        instead of a timed cache, which is usually preferable.

        Note this is a duplicate of the same method in the Flask

        class.

        .. versionchanged:: 2.0

            The default configuration is ``None`` instead of 12 hours.

        .. versionadded:: 0.9

        """

        value = current_app.config["SEND_FILE_MAX_AGE_DEFAULT"]

        if value is None:

            return None

        if isinstance(value, timedelta):

            return int(value.total_seconds())

        return value  # type: ignore[no-any-return]

类 Blueprint 继承自 SansioBlueprint 类,并提供了一些额外的方法和属性。该类的主要目的是为 Flask 应用程序定义蓝图并处理相关的静态文件和 CLI 命令。

代码引入了一些必要的模块,定义了 Blueprint 类。类中包含了一个初始化方法 __init__,该方法接受多个参数,用于设置蓝图的属性。除此之外,还定义了 get_send_file_max_age 方法,该方法用于确定文件的缓存时间,以及 self.cli 属性,用于注册 CLI 命令。 get_send_file_max_age 方法从 Flask 应用程序的配置中获取 SEND_FILE_MAX_AGE_DEFAULT 的值,然后根据不同情况返回合适的缓存时间。

    def send_static_file(self, filename: str) -> Response:

        """The view function used to serve files from

        :attr:`static_folder`. A route is automatically registered for

        this view at :attr:`static_url_path` if :attr:`static_folder` is

        set.

        Note this is a duplicate of the same method in the Flask

        class.

        .. versionadded:: 0.5

        """

        if not self.has_static_folder:

            raise RuntimeError("'static_folder' must be set to serve static_files.")

        # send_file only knows to call get_send_file_max_age on the app,

        # call it here so it works for blueprints too.

        max_age = self.get_send_file_max_age(filename)

        return send_from_directory(

            t.cast(str, self.static_folder), filename, max_age=max_age

        )

这段代码定义了send_static_file方法,它是用于从static_folder中提供文件的视图函数。当static_folder被设置时,该视图将会在static_url_path注册一个路由。

在方法内部,首先检查是否设置了static_folder,如果没有设置,则会抛出一个RuntimeError异常。然后调用get_send_file_max_age方法来获取max_age缓存值,并使用send_from_directory函数来发送文件,end_from_directory函数是在flask.helpers模块中定义的全局函数,可以直接在这里被调用。这种设计使得send_from_directory函数可以在不同类的方法中被共享和重用,而无需将其绑定到特定的实例上。

def open_resource(self, resource: str, mode: str = "rb") -> t.IO[t.AnyStr]:

        """Open a resource file relative to :attr:`root_path` for

        reading.

        For example, if the file ``schema.sql`` is next to the file

        ``app.py`` where the ``Flask`` app is defined, it can be opened

        with:

        .. code-block:: python

            with app.open_resource("schema.sql") as f:

                conn.executescript(f.read())

        :param resource: Path to the resource relative to

            :attr:`root_path`.

        :param mode: Open the file in this mode. Only reading is

            supported, valid values are "r" (or "rt") and "rb".

        Note this is a duplicate of the same method in the Flask

        class.

        """

        if mode not in {"r", "rt", "rb"}:

            raise ValueError("Resources can only be opened for reading.")

        return open(os.path.join(self.root_path, resource), mode)

这段代码定义了一个名为open_resource的方法,使用root_path打开资源文件进行读取。方法包含两个参数,resource表示相对于root_path的资源路径,mode表示打开文件的模式,默认为"rb"。如果mode不在{"r", "rt", "rb"}中,则会引发 ValueError,指出资源只能用于读取。方法返回打开的资源文件对象。主要功能是提供了一种在Flask应用中使用root_path读取资源文件的方法。用户可以使用这个方法来打开指定资源文件,并按照指定模式进行读取。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值