Flask - 如何查询 BLOB 图像数据并将其显示在 HTML / Jinja2 上?

所以,我有一个表单,用户可以在其中发布标题、正文和上传图片。我从表单中获取了该图像并将其作为“Blob”保存到我的 Postgres 数据库中。


但是我有一个问题,我对如何查询该图像 blob 数据并解码并将其显示给用户感到困惑。


这些是我的表:


class User(db.Model, UserMixin):

    id = db.Column(db.Integer, primary_key=True)

    email = db.Column(db.String(120), unique=True, nullable=False)

    username = db.Column(db.String(30), unique=True, nullable=False)

    password = db.Column(db.String(120), nullable=False)

    date_joined = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)

    posts = db.relationship('Post', backref='author', lazy=True, passive_deletes=True)



class Post(db.Model):

    id = db.Column(db.Integer, primary_key=True)

    titl = db.Column(db.String(100), nullable=False)

    body = db.Column(db.Text, nullable=False)

    link = db.Column(db.LargeBinary)

    date_posted = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)

    user_id = db.Column(db.Integer, db.ForeignKey( 'user.id', ondelete='CASCADE'), nullable=False)

这是将 POST 和图像保存到我的数据库和静态文件夹目录的路径:


@app.route('/create/post', methods=['GET', 'POST'])

def create_post():

    # Image upload and validation

    if request.method == 'POST':

        if request.files:


            if allowed_image_size(request.cookies.get('filesize')):

                flash('Image exceeds the maximum size limit of 5 MB!', 'danger')

                return redirect(request.url)


            image = request.files['uploadImg']


            if image.filename == '':

                flash('No image detected or file name is empty!', 'danger')

                return redirect(request.url)


            if not allowed_images(image.filename):

                flash('Invalid image extension!', 'danger')

                return redirect(request.url)

            else:

                filename = secure_filename(image.filename)

                image.save(os.path.join(app.config['IMAGE_UPLOADS'], image.filename))



此外,当我查询帖子以查看是否可以检索数据时,使用类似的东西posts = Post.query.all()并使用print(posts.link.read()). 我收到一条错误消息AttributeError: 'list' object has no attribute 'link'



侃侃尔雅
浏览 118回答 1
1回答

慕雪6442864

我相信您应该将图像作为路径名存储到您的帖子表中,而不是 blob。在您的数据库中将其更改为:&nbsp;link = db.Column(db.String(30))然后在将帖子添加到数据库时将图像文件名路径的字符串传递到帖子中使用随机字符串重命名文件也是一个好习惯,因为许多用户可能会上传,myCatPicture.jpg这会导致它覆盖文件。这样的事情会做def get_random_string(length):&nbsp; &nbsp; # Random string with the combination of lower and upper case&nbsp; &nbsp; letters = string.ascii_letters&nbsp; &nbsp; return ''.join(random.choice(letters) for i in range(length))然后在保存图像时保存新文件名&nbsp; &nbsp; if not allowed_images(image.filename):&nbsp; &nbsp; &nbsp; &nbsp; flash('Invalid image extension!', 'danger')&nbsp; &nbsp; &nbsp; &nbsp; return redirect(request.url)&nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; ext = os.path.splitext(file_name)[1]&nbsp; # get the file extension&nbsp; &nbsp; &nbsp; &nbsp; new_filename = get_random_string(20)&nbsp; # create a random string&nbsp; &nbsp; &nbsp; &nbsp; image.save(os.path.join(app.config['IMAGE_UPLOADS'], new_filename+ext))&nbsp; # save with the new path并在创建后使用新字符串。post = Post(title=form.title.data,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; body=form.body.data, link=os.path.join(app.config['IMAGE_UPLOADS'], new_filename+ext) , user_id=current_user.id)&nbsp; &nbsp;#here we are substituting the old blod with the new stored image path string笔记:只要您将路径存储在数据库中,文件名并不重要。您可以随时查找它以获取图像/路径。...然后在你的模板中(因为你已经有了所有的帖子)你可以开始一个 for 循环{% for post in range(len(posts)) %}&nbsp; &nbsp; <h1> {{ post.title }} </h1>&nbsp; &nbsp; <img src= {{post.link }} >&nbsp; &nbsp; <p> {{ post.body }} </p>{% endfor %}这应该遍历每个帖子标题、图像和内容等。同样,我对此有点模糊。但认为这几乎涵盖了它。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python