【问题标题】:Render an image in html template using SQLAlchemy使用 SQLAlchemy 在 html 模板中渲染图像
【发布时间】:2019-02-17 09:12:41
【问题描述】:

我正在尝试在我的页面中呈现图像。我将图像的本地 url 存储在我的数据库中,以便我可以在我的 html 文件中获取该 url,从而显示图像。但是发生的情况是图像没有显示。

我单独打开html文件并成功渲染了图像,但是在python代码中执行并运行服务器时,图像有问题。

这是一个数据库声明的单项示例(python代码)

cable1 = SectionItem(
name='Remax',
price='$3.99',
description='AUX Metal Cable - 3.5mm - 100Cm Male To Male',
image_url='img/cables/cable1.jpg',
category=cables
)

这很好用。

这是用于渲染图像的 SQLAlechemy

from flask import Flask, render_template, request, redirect, url_for,
flash
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from database import Base
from database import Accessory, AccessorySection, SectionItem

app = Flask(__name__)

engine = create_engine('sqlite:///mobilystore.db')
Base.metadata.bind = engine
DBSession = sessionmaker(bind=engine)
session = DBSession()


@app.route('/')
@app.route('/mobily')
def mobilystore():
    all_cables = session.query(SectionItem).filter(
        SectionItem.store_id == 1).all()
    return render_template(
        'mainpage.html', all_cables=all_cables)


if __name__ == '__main__':
    app.debug = True
    app.run(host='0.0.0.0', port=5000)

服务器也可以在终端运行,没有问题。

这是我的模板文件夹中的 html 文档

<html>
    <body>
        <h1>Mobily Store</h1>
    </br>  
        {% for i in all_cables %}
        <div>
            <img src="{{i.image_url}}" alt="cable img">
            <p> {{i.description}} </p>
            <p> {{i.price}} </p>
    </br>
        </div>
        {%endfor%}

    </body>
</html>

显示价格和描述,但不显示图像。

请注意,我将图像放在模板文件夹内的 img 文件夹中(同一文件夹包含我的 html 文件)。

这是 github 上的my-project,可以让您全面了解

【问题讨论】:

    标签: python sql flask-sqlalchemy


    【解决方案1】:

    您必须将 templates/img 文件夹移动到 static/img 并在模板中使用 url_for 函数打印图像路径:

    <img src="{{ url_for('static', filename=i.image_url) }}" alt="cable img">
    

    【讨论】:

      猜你喜欢
      • 2014-01-25
      • 1970-01-01
      • 2018-06-05
      • 2021-03-04
      • 1970-01-01
      • 2016-11-13
      • 2014-05-08
      • 2021-12-19
      • 2017-04-26
      相关资源
      最近更新 更多