mysql Compress() with sqlalchemy

前端 未结 1 1205
北荒
北荒 2021-01-12 20:21

table:
id(integer primary key)
data(blob)

I use mysql and sqlalchemy. To insert data I use:

o =          


        
相关标签:
1条回答
  • 2021-01-12 20:53

    you can assign a SQL function to the attribute:

    from sqlalchemy import func
    object.data = func.compress(mydata)
    session.add(object)
    session.commit()
    

    Here's an example using a more DB-agnostic lower() function:

    from sqlalchemy import *
    from sqlalchemy.orm import *
    from sqlalchemy.ext.declarative import declarative_base
    
    Base= declarative_base()
    
    class A(Base):
        __tablename__ = "a"
    
        id = Column(Integer, primary_key=True)
        data = Column(String)
    
    e = create_engine('sqlite://', echo=True)
    Base.metadata.create_all(e)
    s = Session(e)
    
    a1 = A()
    a1.data = func.lower("SomeData")
    s.add(a1)
    s.commit()
    
    assert a1.data == "somedata"
    

    you can make it automatic with @validates:

    from sqlalchemy.orm import validates
    class MyClass(Base):
        # ...
        data = Column(BLOB)
    
        @validates("data")
        def _set_data(self, key, value):
            return func.compress(value)
    

    if you want it readable in python before the flush, you'd need to memoize it locally and use a descriptor to access it.

    0 讨论(0)
提交回复
热议问题