Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

services.py 1.9KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  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. imported_mod = __import__(real_app, fromlist=classes)
  35. for classname in classes:
  36. mod.__setattr__(classname, getattr(imported_mod, classname))
  37. return mod
  38. except IndexError:
  39. pass
  40. raise AppNotFoundError("Unable to find an app matching %s in INSTALLED_APPS" % (app_name,))