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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.128.173.32