[Python] Flask: Match folder hierarchy of `static` to `templates`

Discussão em 'Python' iniciado por Stack, Fevereiro 13, 2025.

  1. Stack

    Stack Membro Participativo

    In a blueprint folder hierarchy, the contents of templates shadows the hierarchy.

    Ultimately, I'd like to

    • Mirror the hierarchy of blueprint templates in blueprint static?
    • Add a url_prefix to the blueprint which applies to templates and static,

    From the folder hierachy displayed below, ./subfiles/auth contains:

    • ./subfiles/auth/templates/auth/register.html
    • ./subfiles/auth/static/auth/register.js

    (Note the addition of auth after static.)

    Issue:


    Even without the url_prefix:

    # auth.py
    @auth_bp.route("/auth/register", methods=["GET", "POST"])
    def register():
    # [...]
    return render_template(f"{request.path[1:]}.html")


    <!-- register.html -->
    <!-- [...] -->
    <script src="{{ url_for( request.blueprint + ".static", filename=request.path[1:] + ".js") }}"></script>


    results in:

    GET http://127.0.0.1:5000/static/auth/register.js net::ERR_ABORTED 404 (NOT FOUND)

    whereas:

    <!-- register.html -->
    <!-- [...] -->
    <p>{{ url_for( request.blueprint + ".static", filename=request.path[1:] + ".js") }}</p>


    results in:

    /static/auth/register.js

    That should be correct, although I have a feeling that it is looking at the root level ./static rather than in ./subfiles/auth/static/.

    Folder Hierarchy:


    % tree -I '__pycache__'
    .
    ├── app.py
    ├── app.sh
    ├── blueprints_init.py
    ├── config.py
    ├── global_fun.py
    ├── pielection.db
    ├── pielection.sql
    ├── readme.txt
    ├── requirements.txt
    ├── static
    │ ├── brand.png
    │ └── styles.css
    ├── subfiles
    │ ├── __init__.py
    │ ├── auth
    │ │ ├── __init__.py
    │ │ ├── auth_fun.py
    │ │ ├── auth_rt.py
    │ │ ├── static
    │ │ │ └── auth
    │ │ │ └── register.js
    │ │ └── templates
    │ │ └── auth
    │ │ ├── account.html
    │ │ ├── login.html
    │ │ └── register.html
    └── templates
    ├── apology.html
    ├── layout.html
    └── layoutmwe.html

    Continue reading...

Compartilhe esta Página