跳转到主要内容

Flask的htmx支持

项目描述

htmx-Flask

htmx-Flask是Flask的扩展,为您的应用程序添加了htmx支持。通过增强全局request对象并提供新的make_response函数,它简化了htmx与Flask的使用。

安装

只需pip install htmx-flask即可。这是一个纯Python包,只需要flask(显而易见的原因!)。

使用方法

Htmx请求

在使用增强的request之前,您需要使用以下命令初始化扩展:

from flask import Flask
from htmx_flask import Htmx

htmx = Htmx()

app = Flask(__name__)
htmx.init_app(app)

之后,您可以使用htmx_flask.request.htmx轻松访问htmx请求头。例如,而不是

from flask import request
from my_app import app

@app.route("/")
def hello_workd():
    if request.headers.get("HX-Request") == "true":
        is_boosted = "Yes!" if request.headers.get("HX-Boosted") == "true" else "No!"
        current_url = request.headers.get("HX-Current-URL")
        return (
            "<p>Hello World triggered from a htmx request.</p>"
            f"<p>Boosted: {is_boosted}</p>"
            f"<p>The current url is {current_url}."
        )
    else:
        return "<p>Hello World triggered from a regular request.</p>"

您可以这样做

from htmx_flask import request
from my_app import app

@app.route("/")
def hello_workd():
    if request.htmx:
        is_boosted = "Yes!" if request.htmx.boosted else "No!"
        current_url = request.htmx.current_url
        return (
            "<p>Hello World triggered from a htmx request.</p>"
            f"<p>Boosted: {is_boosted}</p>"
            f"<p>The current url is {current_url}."
        )
    else:
        return "<p>Hello World triggered from a regular request.</p>"

Htmx响应

您可能对向响应中添加htmx响应头感兴趣。为此,请使用htmx_flask.make_response。例如,而不是

import json
from flask import make_response
from my_app import app

@app.route("/hola-mundo")
def hola_mundo():
    body = "Hola Mundo!"
    response = make_response(body)
    response.headers["HX-Push-URL"] = "false"
    trigger_string = json.dumps({"event1":"A message", "event2":"Another message"})
    response.headers["HX-Trigger"] = trigger_string
    return response

您可以这样做

from htmx_flask import make_response
from my_app import app

@app.route("/hola-mundo")
def hola_mundo():
    body = "Hola Mundo!"
    return make_response(
        body,
        push_url=False,
        trigger={"event1": "A message", "event2": "Another message"},
    )

智能感知

使用 htmx-Flask,您还可以在您的 IDE 中获得代码补全、参数信息和快速信息的好处。请查看 PyCharm 的这些截图。

request.htmx autocomplete

make_response quick info

make_response parameter info

如何贡献

本项目使用 pre-commit 钩子在每次提交时运行 black、isort、pyupgrade 和 flake8。要在您的环境中自动运行,请使用以下命令安装项目:

pip install -e .[dev]

然后运行一次

pre-commit install

从现在开始,每次您在这个项目中提交文件,它们都会被上述工具自动处理。

如何运行测试

您可以使用以下命令安装 pytest 和其他必需的依赖项:

pip install -e .[tests]

然后运行测试套件

pytest

项目详情


下载文件

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

源分发

htmx_flask-0.1.0.tar.gz (126.1 kB 查看哈希值)

上传时间

构建分发

htmx_flask-0.1.0-py3-none-any.whl (7.9 kB 查看哈希值)

上传时间 Python 3

由以下提供支持

AWS AWS 云计算和安全赞助商 Datadog Datadog 监控 Fastly Fastly CDN Google Google 下载分析 Microsoft Microsoft PSF 赞助商 Pingdom Pingdom 监控 Sentry Sentry 错误记录 StatusPage StatusPage 状态页面