Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

services.py 1.8KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  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. """
  16. # Classes must be specified in order for __import__ to work correctly. It's
  17. # also a good practice
  18. if not classes:
  19. raise ValueError("You must specify the classes to import")
  20. # Arguments will be things like 'product.models' and so we
  21. # we take the first component to find within the INSTALLED_APPS list.
  22. app_name = mod_name.split(".")[0]
  23. for installed_app in settings.INSTALLED_APPS:
  24. installed_app_parts = installed_app.split(".")
  25. try:
  26. # We search the second component of the installed apps
  27. if app_name == installed_app_parts[1]:
  28. real_app = "%s.%s" % (installed_app_parts[0], mod_name)
  29. # Passing classes to __import__ here does not actually filter out the
  30. # classes, we need to iterate through and assign them individually.
  31. mod = new_module(real_app)
  32. imported_mod = __import__(real_app, fromlist=classes)
  33. for classname in classes:
  34. mod.__setattr__(classname, getattr(imported_mod, classname))
  35. return mod
  36. except IndexError:
  37. pass
  38. raise AppNotFoundError("Unable to find an app matching %s in INSTALLED_APPS" % (app_name,))