我正在尝试使用 flask 蓝图来显示静态图像。这是项目树:
.
├── 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
只有带有“输入图像”标签的图像图标才会显示。为什么这里没有显示实际图像?
请您参考如下方法:
在尝试运行包含的应用程序时,我遇到了导入错误。我更新了文件结构并能够从 static 文件夹中查看图像。我在 blueprints/show.py 中将 request 方法从 POST 更改为 GET。
文件结构:
.
├── 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>
输出:
您可以在 official documentation on blueprint-resources 中阅读有关构建蓝图资源的更多信息.
