从JSON序列化到SQL Alchemy对象(flaskadmin/python)

2024-04-20 12:52:08 发布

您现在位置:Python中文网/ 问答频道 /正文

在flask/python中,我需要将JSON(从Firestore)序列化为SQL Alchemy对象。你知道吗

我不想将Alchemy SQL对象序列化为JSON。不是这个。我需要逆向转换。你知道吗

其想法是覆盖flask admin视图的get_query方法,以便从Firestore恢复数据,但仍然使用flask admin的所有功能,如按视图中选定的列排序等。此外,此应用程序中的数据在postgresql中保持不变(我们使用SQL Alchemy作为ORM),以及来自Firestore的数据。他们必须住在一起。你知道吗

一些代码及其错误:

# flask is imported as f
# flask_sqlalchemy is imported as sa
# also firebase_admin and other related classes with Firebase have been imported

class FakeView(OurExampleModelView):
    column_default_sort = "title"

    def get_query(self):
        # initialize firebase app
        cred = credentials.Certificate(f.current_app.config['GOOGLE_APPLICATION_CREDENTIALS'])
        firebase_admin.initialize_app(cred)

        db = firestore.client()
        users_ref = db.collection(u'users')
        docs = users_ref.stream()

        return sa.BaseQuery(docs)

得到这个错误:

sqlalchemy.exc.InvalidRequestError
sqlalchemy.exc.InvalidRequestError: SQL expression, column, or mapped entity expected - got '<google.cloud.firestore_v1.document.DocumentSnapshot object at 0x7fe02609d5c0>'

也尝试过:

class FakeView(OurExampleModelView):
    column_default_sort = "title"

    def get_query(self):
        # initialize firebase app
        cred = credentials.Certificate(f.current_app.config['GOOGLE_APPLICATION_CREDENTIALS'])
        firebase_admin.initialize_app(cred)

        db = firestore.client()
        users_ref = db.collection(u'users')
        docs = users_ref.stream()

        res = [doc.to_dict() for doc in docs]

        return sa.BaseQuery(docs)

然后得到这个:

sqlalchemy.exc.InvalidRequestError
sqlalchemy.exc.InvalidRequestError: SQL expression, column, or mapped entity expected - got '{'title': 'Title example', 'image': 'fake_image_url'}'

知道如何从JSON转换到SQLAlchemy对象吗?你知道吗

非常感谢!你知道吗


Tags: refappflaskdocsdbsqladminsqlalchemy