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: ...

Get Django Design Patterns and Best Practices - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.