如何使用Flask Alchemy从持久性存储中存储和检索python对象

时间:2019-03-05 02:25:42

标签: python serialization flask-sqlalchemy

如何使用sqlalchemy在数据库中存储和检索python对象?

我一直在查看文档,但看不到它们存储的内容超过字典。有人告诉我它具有存储python对象的功能,但尚未看到它。任何人都知道如何完成此操作的示例吗?

下面是一个我认为它如何工作的示例,但我不认为有可能将python对象添加为列。

Persistance_dreams.py

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
db = SQLAlchemy(app)

# Create our database model
class User(db.Model):
    """ User Model for python objects to a user name """
    __tablename__ = "users"

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    name = db.Column(db.String(255), unique=True, nullable=False)

    def __init__(self, name):
        self.name = name

    # create function to add python object
    def add_python_object(self, object_to_store):
        persistent_python_object = db.Column() # <-- would like to add python object here
        self.persistent_python_object = object_to_store

# Define our object we would like to store
class ExampleObject(object):

    def __init__(self, val_1, val_2):
        self.val_1 = val_1
        self.val_2  = val_2

    def does_something_from_storage(self):
        return self.val_1 + self.val_2

# Create user
adder = User('Adder')
adder.add_python_object(ExampleObject(3,4))

# Add to database
db.session.add(adder)
db.session.commit()

# Retrieve python object
user = User.query.filter_by(name='Adder').first()
result = user.persistent_python_object.does_something_from_storage()

1 个答案:

答案 0 :(得分:1)

正如@Andrew Allen所说,SQLAlchemy实际上带有pickleType列,可用于对python对象进行序列化。

Persistance_reality.py

shift