nameko - 实现(抽象)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 直到运行时才内省服务类,因此它会看到任何标准 Python 类继承产生的结果。
需要注意的一件事是,您的基类不是“抽象的”——如果您指向nameko run
它app/customer/service.py
,它将尝试运行它。相关,如果您将“具体”子类放在同一个模块中,nameko run
将尝试运行它们。您可以通过指定服务类来缓解这种情况,即nameko run app.services:HTTPSalesService
推荐阅读
- git - git woes:使用 cygwin 创建具有文件访问权限的 repo
- javascript - JavaScript (node.js) 如何从 subreddit 中获取随机图像的 URL?
- ruby-on-rails - 按模型的第一个 hasMany 孩子的日期排序
- case - CASE in BETWEEN in WHERE
- java - 从 ZipOutputStream 创建文件
- android - 加载 Mapview 时应用程序在启动时崩溃 (java.lang.OutOfMemoryError: EnsureLocalCapacity)
- python - 为坐标打印 Python 程序
- java - 为什么在没有同步的情况下在 Catalina 过滤器中使用非线程安全的“会话”?
- reactjs - 如何在 react.js 中为 react-credit-card-input 添加 id
- wpf - 如何找到哪些控件导致 UI 线程花费大部分时间进行布局?