Django Rest框架业务逻辑

问题描述 投票:16回答:3

我正在尝试使用Django Rest Framework创建一个后端,并且我正在尝试确定将业务逻辑放在何处。它会进入views.py吗?我想创建更复杂的服务,而不仅仅是获取对象列表或抓取一个特定对象。任何指导将不胜感激,谢谢。我意识到有一个关于通用Django项目中的业务逻辑的讨论,但我特别询问django rest框架。

python django django-rest-framework business-logic
3个回答
13
投票

它更多的是关于设计模式而不是Django Rest Framework。

以下是一些提示:

  • 使用REST提供接口不应涉及与数据操作或业务逻辑相关的任何特定代码。
  • 使用MVC方法并不意味着您不应该对应用程序进行分层。
  • 您应该能够在不触及UI的情况下测试业务逻辑。
  • 有些人可能会建议将业务逻辑放在模型中。但我不同意这些,因为Django模型不同于领域模型和业务相关的任务,如税收计算。
  • 在陷入MVC之前,您可以阅读有关The MVC implemented in MVC three-tier architecture的更多信息
  • 我建议有一个业务层和相关的应用程序,将您的业务逻辑放在那里。

MVC + three-tier diagram

假设您有一个在线咖啡店,并且您想提供一个REST API来订购咖啡。

以下是我建议的代码示例:

的myapp / views.py:

    def order(request, quantity=1):
        # Process the order by calling the mapped method
        order_id = CoffeeShopService.place_order(quantity)
        return HttpResponse({'order_id': order_id, mimetype='application/json')

MYAPP / services.py:

    class CoffeeShopService(object):
        @staticmethod
        def place_order(quantity):
           # do the business logic here
           return order_id

0
投票

我想这是一个设计模式Questing in Rest Framework。以下是我在Rest Framework上的API构建中如何使用分层方法的详细概述!

为了便于维护,它更加分层,最重要的是利用设计模式和GRASP Principal!

分层方法包级别视图

enter image description here

进一步分类:

enter image description here enter image description here

现在我是如何浏览图层的示例:

  1. 请求发送到example.com/Customer/profile @ project / urls.py enter image description here
  2. 请求被转发到各自的URL层(@ app / urls / Customer_Url)The Request is forwarded to the Respective URL's Layer
  3. URL将其传递到各个视图集(@ app / Viewsets / Customer_Viewsets / Customer_Signup.py)enter image description here
  4. 它是一个Post Request,(我假设这个例子)被转发到业务逻辑层(@ app / BusinessLogicLayer / BLL.py)enter image description here
  5. 业务逻辑层具有抽象实现(充当IBLL的接口),它将请求转发到相应的方法以检查我的所有业务规则! (@ app / BusinessLogicLayer / SUB_BLL / Customer / *)enter image description here
  6. 然后将请求转发到数据访问层,该数据访问层将用户数据存储在数据库中。等等! (@ app /数据访问层/ DSL.py)

0
投票

也许这是一种稍微偏心的方式,但我认为通过在其中添加方法将逻辑包装到序列化器中是非常有帮助的。

例如

串行:

class OrderSerializer(serializers.ModelSerializer):
    class Meta:
        model = Order
        fields = (
            'id',
            'total',
            'discount',
        )

    def calculate_discount(self, whatever_params):
        # calculate discount if you need... and return it

    def calculate_tax(self, whatever_params):
        # calculate tax amount if you need...and return it

    def calculate_grand_total(self, whatever_params):
        # calculate grand total if you need and return it

    def create(self, validated_data):
        # You can make an order by applying 
        # some logic in the calculation method.
        # Maybe by adding a bit of the context 
        # you sent as parameters from view.
© www.soinside.com 2019 - 2024. All rights reserved.