python - 怎么利用sqlalchemy读写图片进入mysql?
PHPz
PHPz 2017-04-18 10:02:17
0
3
1493
PHPz
PHPz

学习是最好的投资!

reply all(3)
阿神

In fact, you can store the image directly in the file system, and then just store the file path in mysql

洪涛
from sqlalchemy.dialects.sqlite import BLOB

class Sample(Base):
    __tablename__ = 'sample'
    id = Column(Integer, primary_key=True)
    image = Column(BLOB)

This should define a binary column, and then you just need to convert the image to binary and save it.

For details, please refer to the following:
http://stackoverflow.com/ques...

小葫芦

You can convert image files to base64 encoding and then store them in the database. See the example for details

# -*- 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()
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template