首页 > 解决方案 > 实现(抽象)Nameko 服务继承

问题描述

我有一个处理大量实体的 nameko 服务,并且将入口点放在单个service.py模块中会使该模块高度不可读且难以维护。

所以我决定将模块拆分为多个服务,然后用于扩展主服务。我有点担心依赖注入,并认为像 db 这样的依赖可能由于这种方法而有多个实例。这是我到目前为止所拥有的:

具有所有与客户相关的端点的客户服务模块

# app/customer/service.py

class HTTPCustomerService:
    """HTTP endpoints for customer module"""

    name = "http_customer_service"
    db = None
    context = None
    dispatch = None

    @http("GET,POST", "/customers")
    def customer_listing(self, request):
        session = self.db.get_session()
        return CustomerListController.as_view(session, request)

    @http("GET,PUT,DELETE", "/customers/<uuid:pk>")
    def customer_detail(self, request, pk):
        session = self.db.get_session()
        return CustomerDetailController.as_view(session, request, pk)

和从客户服务继承的主要服务模块,可能还有其他抽象服务

# app/service.py

class HTTPSalesService(HTTPCustomerService):
    """Nameko http service."""

    name = "http_sales_service"
    db = Database(Base)
    context = ContextData()
    dispatch = EventDispatcher()

最后我运行它:

nameko run app.service

所以这很好用,但方法对吗?特别是关于依赖注入?

标签: nameko

解决方案


是的,这种方法效果很好。

Nameko 直到运行时才内省服务类,因此它会看到任何标准 Python 类继承产生的结果。

需要注意的一件事是,您的基类不是“抽象的”——如果您指向nameko runapp/customer/service.py,它将尝试运行它。相关,如果您将“具体”子类放在同一个模块中,nameko run将尝试运行它们。您可以通过指定服务类来缓解这种情况,即nameko run app.services:HTTPSalesService


推荐阅读