我有本地 django 模型,它反射(reflect)了一些外部服务的实体。因此,基本上,当我创建本地对象时,我首先向服务发出发布请求,然后使用响应中的数据填充本地对象的字段并保存它。
将外部 api 调用放入模型管理器以抽象 View 和测试的逻辑是一个好主意吗?或者有更好的方法吗?
我想要实现的是避免代码库中各处重复的逻辑。
最佳答案
模型管理器似乎是个好主意。但也许最好将外部 api 调用的逻辑放在单独的类中。例如:
class ExternalApiService(object):
model = ModelName
def create_object(self, **kwargs):
# create model object
self.model.objects.create(**kwargs)
def call_external_api(self):
# returns json response from API
def process_api_response(self, json_response):
# process response
def get_latest_object(self):
# get latest object
def get_object(self, pk):
# get object
并在 View 中使用它们。
service = ExternalApiService()
class SomeView(ListView):
queryset = service.get_queryset()
def get_context_data(self, *args, **kwargs):
context = super(SomeView, self).get_context_data(*args, **kwargs)
context['something_specific'] = service.get_latest_object()
return context
这种分层的优点是将模型和 View 与业务逻辑和外部服务分开。还提供了更大的灵活性,因为您可以从服务类对象访问外部 api,而无需访问模型或依赖于模型。
关于django - 我应该在 django 模型管理器中进行外部 API 调用吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53376186/