使用蓝图在烧瓶上渲染模板时,图像不显示

时间:2019-05-20 00:12:38

标签: python flask

我正在尝试使用flask bluprint显示静态图像。这是项目树:

.   
├── api.py  
├── __init__.py  
├── show.py  
├── static  
│   └── test.jpg  
└── templates  
    └── show.html  

api.py的内容:

import os
from flask import Flask
from api import show

def create_app(test_config=None):
    app = Flask(__name__, instance_relative_config=True)

    UPLOAD_FOLDER = os.path.join('static')
    app.config.from_mapping(
        SECRET_KEY='dev',
        UPLOAD_FOLDER = UPLOAD_FOLDER,
    )

    app.register_blueprint(show.bp)

    return app

if __name__ == '__main__':
    app = create_app()
    app.run(debug=True)

show.py是:

from flask import (Blueprint, render_template, current_app)
import os


bp = Blueprint('show', __name__, static_folder='static', template_folder='templates')

@bp.route('/show', methods=['POST'])
def show():
    image = os.path.join(current_app.config['UPLOAD_FOLDER'], 'test.jpg')

    return render_template("show.html", in_image = image)

show.html;

<!DOCTYPE html>
<html>
<head>
    <title>Show</title>
</head>
<body>
    <img src="{{ in_image }}" alt="Input Image">
</body>
</html>

在静态文件夹中有一个test.jpg。在运行应用程序时

export FLASK_APP=api
export FLASK_ENV=development
flask run

仅显示带有标签“输入图像”的图像之类的图标。为什么实际的图像没有显示在这里?

1 个答案:

答案 0 :(得分:1)

在尝试运行包含的应用程序时,我遇到导入错误。我更新了文件结构,并能够查看static文件夹中的图像。我将request中的POST方法从GET更改为blueprints/show.py

文件结构:

.
├── api.py
├── blueprints
│   ├── __init__.py
│   └── show.py
├── static
│   └── penguins.png
└── templates
    └── show.html

api.py

import os
from flask import Flask
from blueprints.show import bp

def create_app(test_config=None):
    app = Flask(__name__, instance_relative_config=True)
    UPLOAD_FOLDER = os.path.join('static')
    app.config.from_mapping(
        SECRET_KEY='dev',
        UPLOAD_FOLDER = UPLOAD_FOLDER,
    )
    app.register_blueprint(bp)
    return app

app = create_app()

blueprints/__init__.py是空白文件。

blueprints/show.py

from flask import Blueprint, render_template, current_app
import os    

bp = Blueprint('show', __name__, static_folder='static',
               template_folder='templates')

@bp.route('/show')
def show():
    image = os.path.join(current_app.config['UPLOAD_FOLDER'], 'penguins.png')
    return render_template("show.html", in_image = image)

templates/show.html

<!DOCTYPE html>
<html>
<head>
    <title>Show</title>
</head>
<body>
    <img src="{{ in_image }}" alt="Input Image">
</body>
</html>

输出:

flask blueprint image load

您可以在official documentation on blueprint-resources中阅读有关构建蓝图资源的更多信息。