How to render empty image fields created with SQLAlchemy-imageattach without "OSError: there is no original image yet" exception

How to render empty image fields created with SQLAlchemy-imageattach without "OSError: there is no original image yet" exception

我正在尝试使用 sqlalchemy-imageattach 将图像附加到 db.Model,并使用 flask/jinja2 在模板中渲染它们。 只要实际附加了图像,这一切都可以正常工作。如果该字段为空,则会抛出异常(OSError:还没有原始图像)。如何避免空字段出现异常或向 jinja2 模板添加一些异常处理?谢谢!

app.py:

from flask import Flask, render_template
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy_imageattach.stores.fs import HttpExposedFileSystemStore
from sqlalchemy_imageattach.context import (pop_store_context,
                                            push_store_context)
from sqlalchemy_imageattach.entity import Image, image_attachment


app = Flask(__name__)
db = SQLAlchemy(app)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///:memory:'

store = HttpExposedFileSystemStore(
    path='images',
    prefix='static/images/'
)
app.wsgi_app = store.wsgi_middleware(app.wsgi_app)


class Person(db.Model):

    __tablename__ = 'person'

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String, nullable=False)
    image = image_attachment('PersonImage')

    def __init__(self, name):
        self.name = name


class PersonImage(Image, db.Model):

    __tablename__ = 'person_image'

    person_id = db.Column(
        db.Integer,
        db.ForeignKey('person.id'),
        primary_key=True)
    person = db.relationship('Person')


@app.before_request
def start_implicit_store_context():
    push_store_context(store)


@app.teardown_request
def stop_implicit_store_context(exception=None):
    pop_store_context()


@app.route('/')
def index():
    person = Person(name='Hello')
    # with open('test.jpg', 'rb') as f:
    #     person.image.from_file(f)
    db.session.add(person)
    db.session.commit()
    return render_template('index.html', person=person)


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

index.html:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    {{ person.name }}
    {{ person.image }} <!-- THIS FAILS ON EMPTY FIELDS -->
  </body>
</html>

尝试更改 index.html 中的代码,如下所示:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    {{ person.name }}
    {% if person.image is not none %}
       {{ person.image }} 
    {% else %}
       <img src="default.png">
    {% endif %}
  </body>
</html>

简单的使用if条件。

<html>
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    {{ person.name }}
    {{ person.image if person.image}}
  </body>
</html>

好的,回答我自己的问题: 您必须在模板中使用 {{ person.image.original }} 或检查 if person.image.count()。 sqlalchemy-imageattach documentation 只是提到 {{ person.image }} 扩展为 <img src="{{ user.picture.locate() }}" width="{{ user.picture.width }}" height="{{ user.picture.height }}">。 这不适用于空图像字段,并且在使用明显的解决方案检查 {% if person.image %} 时也不起作用,因为 sqlalchemy-imageattach 在空图像字段上不 return None 但总是抛出一个例外。 相关代码是here:

image = self.original
if not image:
    raise IOError('there is no original image yet')
return image