正确的声明图像字段的方法,sqlalchemy

时间:2015-12-08 11:25:06

标签: python sqlite flask-sqlalchemy

我正在尝试用烧瓶构建和应用程序,我已经看到了一些教程和书籍以及一些代码[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/

2 个答案:

答案 0 :(得分:2)

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

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

使用lib,您可以从两个存储中进行选择,例如文件系统或Amazon的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一起使用文件存储。我希望它可以帮助你一些,并给你一些**。

答案 1 :(得分:1)

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

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