我正在尝试使用sqlalchemy-imageattach将图像附加到db.Model,并使用flask / jinja2在模板中呈现它们。 只要实际附加了图像,这一切都可以正常工作。如果该字段为空,则抛出异常(OSError:还没有原始图像)。如何避免空字段上的异常或为jinja2模板添加一些异常处理?谢谢!
foreach($groups as $group) {
echo $group->user_count
}
:
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
答案 0 :(得分:0)
尝试在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>
答案 1 :(得分:0)
简单使用if条件。
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
{{ person.name }}
{{ person.image if person.image}}
</body>
</html>
答案 2 :(得分:0)
好的,回答我自己的问题:
您必须在模板中使用{{ 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在空图像字段上不返回None
但总是抛出异常。
相关代码为here:
image = self.original
if not image:
raise IOError('there is no original image yet')
return image