我有一个处理许多实体的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所以这个方法很好,但是这个方法正确吗?尤其是在依赖注入方面?
发布于 2019-05-20 10:07:44
是的,这种方法效果很好。
Nameko直到运行时才会内省服务类,因此它看到了标准Python类继承产生的任何内容。
需要注意的一点是,您的基类不是“抽象的”--如果您将nameko run指向app/customer/service.py,它将尝试运行它。相关的,如果您将“具体”子类放在同一个模块中,nameko run将尝试同时运行这两个子类。您可以通过指定服务类(即nameko run app.services:HTTPSalesService )来缓解这一问题。
https://stackoverflow.com/questions/56218311
复制相似问题