sqlalchemy,封装还是撒在任何地方?

发布于 2025-02-09 06:34:58 字数 616 浏览 0 评论 0原文

我正在使用SQLalchemy + SQLite 3编写一个小应用程序。我正在尝试将Sqlalchemy包裹在下面的剪辑中。我发现我最终得到了Sqlalch周围非常乏味的包装纸。尝试包裹Sqlalchemy是典型的吗?还是可以完全使用它的约定,并在整个代码库中撒上会话和SA查询对象? Sqlalchemy的语法在某种程度上很尴尬,以至于我最终想包裹很多衬里。意见?任何好的代码示例都将不胜感激。

class MyDB:
...
    def query(self, table_class, query):
        if isinstance(query, str):
            query = text(query)

        with self.make_session() as sesh:
            res = sesh.execute(select(table_class).where(query)).all()
        return res
...
db = MyDB(db_path="path_to_db.sqlite")

results = db.query(table_class = MyOrmTableClass, query = "where device_id="FOOBAR")

I'm writing a small application using SQLAlchemy + SQLite3. I'm trying to wrap SQLAlchemy in classes like the snip below. I find I'm ending up with a tedious amount of very thin wrappers around SQLAlch. Is it typical to try and wrap SQLAlchemy? or is the convention just to use embrace it fully and sprinkle sessions and SA query objects throughout a codebase? The syntax of sqlalchemy is somehow just awkward enough that I end up wanting to wrap a lot of one liners. Opinions? Any good code examples would be appreciated.

class MyDB:
...
    def query(self, table_class, query):
        if isinstance(query, str):
            query = text(query)

        with self.make_session() as sesh:
            res = sesh.execute(select(table_class).where(query)).all()
        return res
...
db = MyDB(db_path="path_to_db.sqlite")

results = db.query(table_class = MyOrmTableClass, query = "where device_id="FOOBAR")

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文