- Django Design Patterns and Best Practices
- Arun Ravindran
- 274字
- 2021-06-25 21:32:09
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.
- JavaScript從入門到精通(微視頻精編版)
- 在最好的年紀(jì)學(xué)Python:小學(xué)生趣味編程
- 摩登創(chuàng)客:與智能手機和平板電腦共舞
- Android Application Development Cookbook(Second Edition)
- C#程序設(shè)計(慕課版)
- Python高級機器學(xué)習(xí)
- Building Cross-Platform Desktop Applications with Electron
- 精通Scrapy網(wǎng)絡(luò)爬蟲
- Oracle BAM 11gR1 Handbook
- Python:Master the Art of Design Patterns
- concrete5 Cookbook
- Python Web數(shù)據(jù)分析可視化:基于Django框架的開發(fā)實戰(zhàn)
- Bootstrap 4 Cookbook
- Mastering React
- JavaScript前端開發(fā)基礎(chǔ)教程