1
|
|
|
# coding: utf-8 |
2
|
|
|
from django.conf import settings |
3
|
|
|
from collections import OrderedDict |
4
|
|
|
|
5
|
|
|
|
6
|
|
|
class ServiceProvider(OrderedDict): |
7
|
|
|
|
8
|
|
|
def load_services(self, services=settings.TH_SERVICES): |
9
|
|
|
""" |
10
|
|
|
get the service from the settings |
11
|
|
|
""" |
12
|
|
|
kwargs = {} |
13
|
|
|
for class_path in services: |
14
|
|
|
module_name, class_name = class_path.rsplit('.', 1) |
15
|
|
|
klass = import_from_path(class_path) |
16
|
|
|
service = klass(None, **kwargs) |
17
|
|
|
self.register(class_name, service) |
18
|
|
|
|
19
|
|
|
def register(self, class_name, service): |
20
|
|
|
self[class_name] = service |
21
|
|
|
|
22
|
|
|
def get_service(self, class_name): |
23
|
|
|
""" |
24
|
|
|
get the service (class instance) from its name |
25
|
|
|
""" |
26
|
|
|
return self[class_name] |
27
|
|
|
|
28
|
|
|
|
29
|
|
|
def import_from_path(path): |
30
|
|
|
""" |
31
|
|
|
Import a class dynamically, given it's dotted path. |
32
|
|
|
:param path: the path of the module |
33
|
|
|
:type path: string |
34
|
|
|
:return: Return the value of the named attribute of object. |
35
|
|
|
:rtype: object |
36
|
|
|
""" |
37
|
|
|
module_name, class_name = path.rsplit('.', 1) |
38
|
|
|
try: |
39
|
|
|
return getattr(__import__(module_name, |
40
|
|
|
fromlist=[class_name]), class_name) |
41
|
|
|
except AttributeError: |
42
|
|
|
raise ImportError('Unable to import %s' % path) |
43
|
|
|
|
44
|
|
|
|
45
|
|
|
service_provider = ServiceProvider() |
46
|
|
|
|