util.py 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. from collections import defaultdict
  2. from django.conf import settings
  3. from mongodbforms.documentoptions import DocumentMetaWrapper, LazyDocumentMetaWrapper
  4. from mongodbforms.fieldgenerator import MongoDefaultFormFieldGenerator
  5. try:
  6. from django.utils.module_loading import import_by_path
  7. except ImportError:
  8. # this is only in Django's devel version for now
  9. # and the following code comes from there. Yet it's too nice to
  10. # pass on this. So we do define it here for now.
  11. import sys
  12. from django.core.exceptions import ImproperlyConfigured
  13. from django.utils.importlib import import_module
  14. from django.utils import six
  15. def import_by_path(dotted_path, error_prefix=''):
  16. """
  17. Import a dotted module path and return the attribute/class designated
  18. by the last name in the path. Raise ImproperlyConfigured if something
  19. goes wrong.
  20. """
  21. try:
  22. module_path, class_name = dotted_path.rsplit('.', 1)
  23. except ValueError:
  24. raise ImproperlyConfigured("%s%s doesn't look like a module path" %
  25. (error_prefix, dotted_path))
  26. try:
  27. module = import_module(module_path)
  28. except ImportError as e:
  29. msg = '%sError importing module %s: "%s"' % (
  30. error_prefix, module_path, e)
  31. six.reraise(ImproperlyConfigured, ImproperlyConfigured(msg),
  32. sys.exc_info()[2])
  33. try:
  34. attr = getattr(module, class_name)
  35. except AttributeError:
  36. raise ImproperlyConfigured(
  37. '%sModule "%s" does not define a "%s" attribute/class' %
  38. (error_prefix, module_path, class_name))
  39. return attr
  40. def load_field_generator():
  41. if hasattr(settings, 'MONGODBFORMS_FIELDGENERATOR'):
  42. return import_by_path(settings.MONGODBFORMS_FIELDGENERATOR)
  43. return MongoDefaultFormFieldGenerator
  44. def init_document_options(document):
  45. if not isinstance(document._meta, (DocumentMetaWrapper, LazyDocumentMetaWrapper)):
  46. document._meta = DocumentMetaWrapper(document)
  47. return document
  48. def get_document_options(document):
  49. return DocumentMetaWrapper(document)
  50. def format_mongo_validation_errors(validation_exception):
  51. """Returns a string listing all errors within a document"""
  52. def generate_key(value, prefix=''):
  53. if isinstance(value, list):
  54. value = ' '.join([generate_key(k) for k in value])
  55. if isinstance(value, dict):
  56. value = ' '.join([
  57. generate_key(v, k) for k, v in value.iteritems()
  58. ])
  59. results = "%s.%s" % (prefix, value) if prefix else value
  60. return results
  61. error_dict = defaultdict(list)
  62. for k, v in validation_exception.to_dict().iteritems():
  63. error_dict[generate_key(v)].append(k)
  64. return ["%s: %s" % (k, v) for k, v in error_dict.iteritems()]
  65. # Taken from six (https://pypi.python.org/pypi/six)
  66. # by "Benjamin Peterson <benjamin@python.org>"
  67. #
  68. # Copyright (c) 2010-2013 Benjamin Peterson
  69. #
  70. # Permission is hereby granted, free of charge, to any person obtaining a copy
  71. # of this software and associated documentation files (the "Software"), to deal
  72. # in the Software without restriction, including without limitation the rights
  73. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  74. # copies of the Software, and to permit persons to whom the Software is
  75. # furnished to do so, subject to the following conditions:
  76. #
  77. # The above copyright notice and this permission notice shall be included in
  78. # all copies or substantial portions of the Software.
  79. #
  80. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  81. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  82. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  83. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  84. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  85. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  86. # SOFTWARE.
  87. def with_metaclass(meta, *bases):
  88. """Create a base class with a metaclass."""
  89. return meta("NewBase", bases, {})