Django Rest Framework业务逻辑 [英] Django Rest Framework Business Logic

查看:290
本文介绍了Django Rest Framework业务逻辑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

解决方案

更多的是设计模式,而不是Django Rest Framework。



这里有一些提示:




  • 使用REST提供的接口不应涉及任何与数据操作或业务逻辑相关的特定代码。

  • 使用MVC方法并不意味着您不应该对应用程序进行分层。

  • 您应该能够测试您的业务逻辑,而无需完全触摸UI。

  • 有些人可能建议将业务逻辑放入模型中。但是我不同意它们,因为Django模型不同于域模型和与业务相关的任务,例如税收计算。

  • 在陷入MVC之前,您可以阅读有关



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



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



    myapp / views.py:

      def订单(请求,数量= 1):
    #通过调用来处理订单映射的方法
    order_id = CoffeeShopService.place_order(quantity)
    返回HttpResponse({'order_id':order_id,mimetype ='application / json')

    myapp / services.py:

     类CoffeeShopService(对象):
    @staticmethod
    def place_order(数量):
    #在这里进行业务逻辑
    返回order_id


    I am trying to create a backend with Django Rest Framework and am trying to determine where to place the business logic. Would it go in the views.py? I would like to create more complex services than just getting a list of objects or grabbing one specific object. Any guidance would be appreciated, thanks. I realize there is a discussion about the business logic in a generic Django project but I am asking specifically about the django rest framework.

    解决方案

    It is more about design patterns rather than Django Rest Framework.

    Here are some tips:

    • Providing interfaces using REST should not involve any specific code related to data manipulation or business logic.
    • Using an MVC approach does not mean that you shouldn't layer your application.
    • You should be able to test your business logic without touching the UI at all.
    • Some people may suggest putting business logic in models. But I do not agree with them, since Django models are different from domain models and business related tasks such as tax calculation.
    • Before getting stuck in MVC, You could read more about The MVC implemented in MVC three-tier architecture
    • I suggest having a business layer and related apps putting your business logic there.

    Suppose that you have an online coffee shop & you'd like to provide a REST API for ordering coffees.

    Here are my suggested code samples:

    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
    

    这篇关于Django Rest Framework业务逻辑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆