官术网_书友最值得收藏!

Solution details

Service objects are plain old Python objects (POPOs) that encapsulate a service or interactions with a system. They are usually kept in a separate file named services.py or utils.py.

For example, checking a web service is sometimes dumped into a model method as follows:

class Profile(models.Model): 
    ... 
 
    def is_superhero(self): 
        url = "http://api.herocheck.com/?q={0}".format( 
              self.user.username) 
        return webclient.get(url) 

This method can be refactored to use a service object as follows:

from .services import SuperHeroWebAPI 
 
    def is_superhero(self): 
        return SuperHeroWebAPI.is_hero(self.user.username) 

The service object can now be defined in services.py as follows:

API_URL = "http://api.herocheck.com/?q={0}" 
 
class SuperHeroWebAPI: 
    ... 
    @staticmethod 
    def is_hero(username): 
        url =API_URL.format(username) 
        return webclient.get(url) 

In most cases, methods of a service object are stateless, that is, they perform the action solely based on the function arguments without using any class properties. Hence, it is better to explicitly mark them as static methods (as we have done for is_hero).

Consider refactoring your business logic or domain logic out of models into service objects. This way, you can use them outside your Django application as well.

Imagine there is a business reason to blacklist certain users from becoming superhero types based on their username. Our service object can be easily modified to support this:

class SuperHeroWebAPI: 
    ... 
    @staticmethod 
    def is_hero(username): 
        blacklist = set(["syndrome", "kcka$$", "superfake"]) 
        url =API_URL.format(username) 
        return username not in blacklist and webclient.get(url) 

Ideally, service objects are self-contained. This makes them easy to test without mocking, say, the database. They can also be easily reused.

In Django, time-consuming services are executed asynchronously using task queues such as Celery. Typically, the service object actions are run as Celery tasks. Such tasks can be run periodically or after a delay.

主站蜘蛛池模板: 且末县| 光山县| 张掖市| 敦煌市| 肃北| 东乌| 原阳县| 武鸣县| 上蔡县| 荆州市| 大冶市| 牡丹江市| 定兴县| 泽州县| 吉隆县| 双柏县| 罗江县| 大同市| 个旧市| 申扎县| 安龙县| 改则县| 穆棱市| 甘孜县| 晋宁县| 古蔺县| 珠海市| 泾川县| 宝清县| 盐山县| 清河县| 夏河县| 中西区| 襄汾县| 郯城县| 金堂县| 光山县| 广安市| 前郭尔| 怀化市| 策勒县|