【问题标题】:Correct way to declare an image field, sqlalchemy声明图像字段的正确方法,sqlalchemy
【发布时间】:2023-03-17 14:56:01
【问题描述】:

我正在尝试使用烧瓶构建和应用程序,我看过一些教程和书籍以及一些代码[1],它们解释了如何为数据库设置声明整数和字符串。但是,他们没有解释如何存储图像。我现在很困惑,虽然存储图像的自然方式是在数据库上,但是阅读烧瓶站点[2]上的一些文档,文件系统是存储图像的地方。我只是在阅读烧瓶开发书籍时做出第一个假设,即使用 largeBinary 的声明是正确的,但这只是我的猜测,您可以在下面的代码中看到。有人可以帮我解决这个问题吗?如果我问的不清楚,请告诉我。

Class User(Base):
    __table__ = 'user'

    id = Column(Integer, primary_key = True)
    name  Column(String(80), nullable=False)
    email =  Column(String(250), nullable=False)
    image = Column(LargeBinary, nullable = True)

[1]https://github.com/lobrown/Full-Stack-Foundations/blob/master/Lesson_1/database_setup.py [2]http://flask.pocoo.org/docs/0.10/patterns/fileuploads/

【问题讨论】:

标签: python sqlite flask-sqlalchemy


【解决方案1】:

有一个名为SQLAlchemy-ImageAttach 的库,它提供了一种创建具有图像对象的实体的方法。这些可以通过一些 url 公开。

否则,您可以通过 SingleImageSet 类直接获取文件对象。

使用该库,您可以从两种存储中进行选择,例如文件系统或亚马逊的 S3。在文档中,有一个 described example(灰色框)如何定义先前的存储,然后定义一个用户实体并拥有一个 UserPicture 实体。

from sqlalchemy import Column, ForeignKey, Integer, Unicode
from sqlalchemy.orm import relationship
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy_imageattach.entity import Image, image_attachment

Base = declarative_base()

class User(Base):
"""User model."""

    id = Column(Integer, primary_key=True)
    name = Column(Unicode, nullable=False)
    picture = image_attachment('UserPicture')
    __tablename__ = 'user'

class UserPicture(Base, Image):
    """User picture model."""

    user_id = Column(Integer, ForeignKey('user.id'), primary_key=True)
    user = relationship('User')
    __tablename__ = 'user_picture'

我不知道 Flask,但也许您可以通过一些 wsgi 声明与此处的 Lib 一起使用文件存储。我希望它对您有所帮助并给您一些**。

【讨论】:

    【解决方案2】:

    我在这篇文章[1] 中读到,最好的方法是将图像字段声明为一个字符串来保存图像的 url 或链接,然后图像可以存储在与服务器不同的外部服务器中你的申请。因此,如果有人有同样的疑问,只需将其声明为字符串并继续您的应用程序开发。对数据库管理系统有点失望,它们只能用于存储数字和字母数据(:p)。

    [1]https://www.reddit.com/r/flask/comments/31tywp/afbest_way_to_store_avatars_images_etc/

    【讨论】:

      【解决方案3】:

      如果您要对图像文件进行哈希处理,您可能希望将 LargeBinary 替换为设置为特定字符数量的字符串。然后您可以设置图像值,例如

      class User(Base):
              image = Column(string(int), nullable=True, 
      temp='thepicture.jpg')
      

      假设图片保存为thepicture.jpg

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-01-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多