gpt4 book ai didi

python - 使用蓝图在 Flask 上渲染模板时图像不显示

转载 作者:太空宇宙 更新时间:2023-11-04 04:11:20 26 4
gpt4 key购买 nike

我正在尝试使用 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>

输出:

flask blueprint image load

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

关于python - 使用蓝图在 Flask 上渲染模板时图像不显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56213008/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com