search

Home  >  Q&A  >  body text

python - 怎么利用sqlalchemy读写图片进入mysql?

PHPzPHPz2809 days ago1509

reply all(3)I'll reply

  • 阿神

    阿神2017-04-18 10:04:17

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

    reply
    0
  • PHP中文网

    PHP中文网2017-04-18 10:04:17

    1

    2

    3

    4

    5

    6

    <code class="py">from sqlalchemy.dialects.sqlite import BLOB

     

    class Sample(Base):

        __tablename__ = 'sample'

        id = Column(Integer, primary_key=True)

        image = Column(BLOB)</code>

    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...

    reply
    0
  • 高洛峰

    高洛峰2017-04-18 10:04:17

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

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    26

    27

    28

    29

    30

    31

    32

    33

    34

    35

    36

    37

    <code># -*- 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()</code>

    reply
    0
  • Cancelreply