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()