[Python] File not found by rendering a html using flask

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

  1. Stack

    Stack Membro Participativo

    I am pretty new in using flask and have a basic question: How to provide access to an HTML that is rendered using flask access to static files (such as images). Here my toy example:

    I would like to render logo.svg on a website. The Project is structured as

    Project
    |
    + -- static
    |
    + -- logo.svg
    + -- templates
    |
    + -- test.html
    + -- run_flask.py


    test.html looks as follows

    <!DOCTYPE>

    <html>

    <head>

    <title>demo</title>

    <style>
    body {
    font-family: helvetica neue, helvetica, liberation sans, arial, sans-serif;
    font-size: 14px;
    }

    </style>
    </head>

    <body>
    <img src="./static/logo.svg" id="logo">
    </body>

    </html>


    and my run_flask-py script contains:

    import flask
    from flask import render_template, send_from_directory
    from flask_cors import CORS

    app = flask.Flask(__name__, static_url_path='')
    CORS(app)
    app.config["DEBUG"] = True

    @app.route('/<string:page_name>/')
    def render_static(page_name):
    return render_template('%s.html' % page_name)

    app.run(port=5001)



    When a now run the script, the console output is:


    Running on http://127.0.0.1:5001/ (Press CTRL+C to quit)
    ​

    So far so good, but in chrome, http://127.0.0.1:5001/test/ looks like:

    [​IMG]

    I already looked at How to serve static files in Flask as the problem sounds similar. But I am actually completed confused about how the suggested send_from_directory can help me here.

    Can somebody help?

    Continue reading...

Compartilhe esta Página