You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

services.py 2.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. from exceptions import Exception
  2. from imp import new_module
  3. from django.conf import settings
  4. class AppNotFoundError(Exception):
  5. pass
  6. def import_module(mod_name, classes=[]):
  7. """
  8. For dynamically importing classes from a module based on the mapping within
  9. settings.py
  10. Eg. calling import_module('product.models') will search INSTALLED_APPS for
  11. the relevant product app (default is 'oscar.product') and then import the
  12. classes from there.
  13. We search the INSTALLED_APPS list to find the appropriate app string and
  14. import that.
  15. This is very similar to django.db.models.get_model although that is only
  16. for loading models while this method will load any class.
  17. """
  18. # Classes must be specified in order for __import__ to work correctly. It's
  19. # also a good practice
  20. if not classes:
  21. raise ValueError("You must specify the classes to import")
  22. # Arguments will be things like 'product.models' and so we
  23. # we take the first component to find within the INSTALLED_APPS list.
  24. app_name = mod_name.split(".")[0]
  25. for installed_app in settings.INSTALLED_APPS:
  26. installed_app_parts = installed_app.split(".")
  27. try:
  28. # We search the second component of the installed apps
  29. if app_name == installed_app_parts[1]:
  30. real_app = "%s.%s" % (installed_app_parts[0], mod_name)
  31. # Passing classes to __import__ here does not actually filter out the
  32. # classes, we need to iterate through and assign them individually.
  33. mod = new_module(real_app)
  34. print real_app
  35. imported_mod = __import__(real_app, fromlist=classes)
  36. for classname in classes:
  37. mod.__setattr__(classname, getattr(imported_mod, classname))
  38. return mod
  39. except IndexError:
  40. pass
  41. raise AppNotFoundError("Unable to find an app matching %s in INSTALLED_APPS" % (app_name,))