Heim > Fragen und Antworten > Hauptteil
PHP中文网2017-04-18 10:04:17
from sqlalchemy.dialects.sqlite import BLOB
class Sample(Base):
__tablename__ = 'sample'
id = Column(Integer, primary_key=True)
image = Column(BLOB)
这个应该是定义了一个二进制列,然后你只要把图片转为二进制保存应该就可以了。
具体可以参考下面:
http://stackoverflow.com/ques...
高洛峰2017-04-18 10:04:17
可以把图片文件转换为base64编码然后存入到数据库。具体看示例
# -*- coding: utf-8 -*
from sqlalchemy import Column, String, create_engine, LargeBinary
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
import base64
Base = declarative_base()
class User(Base):
__tablename__ = 'user'
id = Column(String(20), primary_key=True)
name = Column(String(20))
image = Column(LargeBinary)
img = open("1111.png", "rb")
img = base64.b64encode(img.read())
engine = create_engine('mysql://root:123456@localhost:3306/test')
DBSession = sessionmaker(bind=engine)
session = DBSession()
new_user = User(id='1', name='test', image=img)
session.add(new_user)
session.commit()
# 查询刚刚存入放入图片
user = session.query(User).filter(User.id == '1').one()
image = base64.b64decode(user.image)
with open("test.png", "wb") as f:
f.write(image)
session.close()