FastApi结构 - 在哪里存储大型数据库查询

发布于 2025-02-08 14:51:27 字数 399 浏览 1 评论 0原文

我一直在Fastapi后端工作,我主要遵循在这里因为该项目是由Fastapi Creator创建的,似乎是一个很好的参考。

到目前为止,我的项目一直很好地扩展,但是我只需要处理简单的CRUD数据库操作即可。现在,我需要使用更复杂的数据库查询,并且不确定这些查询是否适合当前项目结构。我应该遵循标准的文件夹结构,还是应该做一个“查询” 文件夹?

I've been working on FastAPI backend, I've mainly been following the project structure as used here because this project was created by the FastAPI creator and seems a good reference.

So far my project has been scaling well, but I've only had to deal with simple CRUD database operations. Now I need to use more complex database queries, and I'm not sure where these would fit in the current project structure. Is there a standard folder structure I should follow, or should I just make a "queries" folder and be done with it?

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

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

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

烟花易冷人易散 2025-02-15 14:51:27

通常,将功能分为不同的服务,其中每种服务都有自己的责任。 productservice将有根据业务规则(和需求)检索产品的方法,并且与这些要求相关的查询将是(以及其他功能)。

您还将将其视为基于存储库的布局,其中存储库是“如何保存和检索给定数据”的抽象。我更喜欢将其构建为服务,因为在许多情况下拥有使用存储库的服务是过度的(您 真正更改了您在应用程序终生期间更改基本存储库的实现?)。

foo/
    schemas/
    services/
        user.py
        product.py
        posts.py

服务可能是类似的:

class ProductService:
    def __init__(self, db):
        self.db = db

    def get_products_for_user(user_id: int, pagination: Pagination):
        return self.db.query(Product).filter(Product.user_id == user_id)[pagination.offset:pagination.offset + pagination.hits]

..等

It's common to separate that functionality out into distinct services, where each service has its own responsibility. A ProductService would have methods to retrieve products according to business rules (and needs), and would be where the queries related to those requirements would be (and other functionality as well).

You'll also see this mentioned as a Repository-based layout, where the Repository is an abstraction over "how to save and retrieve given data". I prefer to structure this as services instead, since having a service that uses a repository in many cases is overkill (how often do you really change your underlying repository implementation during an application's life time?).

foo/
    schemas/
    services/
        user.py
        product.py
        posts.py

A service could be something like:

class ProductService:
    def __init__(self, db):
        self.db = db

    def get_products_for_user(user_id: int, pagination: Pagination):
        return self.db.query(Product).filter(Product.user_id == user_id)[pagination.offset:pagination.offset + pagination.hits]

.. etc.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文