Пример #1
0
 def create_list_objs(self, entity_factory, list_scopes):
     """Create and return list of objects used entity factory and UI data
 (list of scopes UI text elements {"header": "item", ...} remapped to
 list of dicts {"attr": "value", ...}).
 Return list of created objects.
 """
     list_factory_objs = [
         entity_factory.create_empty() for _ in xrange(len(list_scopes))
     ]
     list_scopes_with_upper_keys = [
         string_utils.dict_keys_to_upper_case(scope)
         for scope in list_scopes
     ]
     list_scopes_to_convert = string_utils.exchange_dicts_items(
         transform_dict=Entity.items_of_remap_keys(),
         dicts=list_scopes_with_upper_keys,
         is_keys_not_values=True)
     # convert and represent values in scopes
     for scope in list_scopes_to_convert:
         # convert u'None', u'No person' to None type
         string_utils.update_dicts_values(scope, ["None", "No person"],
                                          None)
         for key, val in scope.iteritems():
             if val:
                 if key in ["mandatory", "verified"]:
                     # convert u'false', u'true' like to Boolean
                     scope[key] = string_utils.get_bool_value_from_arg(val)
                 # convert datetime attributes' directly
                 if key in ["updated_at", "created_at"]:
                     scope[key] = string_utils.convert_str_to_datetime(val)
                 # convert datetime attributes' in 'comments'
                 if (key == "comments" and isinstance(val, list) and all(
                         isinstance(comment, dict) for comment in val)):
                     # u'(Creator) 07/06/2017 05:47:14 AM UTC'
                     # to u'07/06/2017 05:47:14 AM UTC'
                     scope[key] = [{
                         k: (string_utils.convert_str_to_datetime(
                             re.sub(regex.TEXT_WITHIN_PARENTHESES, "", v))
                             if k == "created_at" else v)
                         for k, v in comment.iteritems()
                     } for comment in val]
                 # convert multiple values to list of strings and split if need it
                 if key in ["owners", "assessor", "creator", "verifier"]:
                     # convert CSV like u'*****@*****.**' to u'Example User'
                     val = val if val != url.DEFAULT_USER_EMAIL else roles.DEFAULT_USER
                     # split multiple values if need 'Ex1, Ex2 F' to ['Ex1', 'Ex2 F']
                     scope[key] = val.split(", ")
                 # convert 'slug' from CSV for snapshoted objects u'*23eb72ac-4d9d'
                 if (key == "slug" and
                     (self.obj_name in objects.ALL_SNAPSHOTABLE_OBJS)
                         and "*" in val):
                     scope[key] = val.replace("*", "")
     return [
         Entity.update_objs_attrs_values_by_entered_data(
             obj_or_objs=factory_obj, is_allow_none_values=False, **scope)
         for scope, factory_obj in zip(list_scopes_to_convert,
                                       list_factory_objs)
     ]
Пример #2
0
   def convert_attr_value_from_dict_to_unicode(attr_name, attr_value):
       """Convert attribute value from dictionary to unicode representation
 (get value by key from dictionary 'attr_value' where key determine
 according to 'attr_name').
 """
       if isinstance(attr_value, dict):
           converted_attr_value = attr_value
           if attr_name in [
                   "contact", "manager", "owners", "assessor", "creator",
                   "verifier", "created_by", "modified_by", "Assessor",
                   "Creator", "Verifier"
           ]:
               converted_attr_value = unicode(attr_value.get("name"))
           if attr_name in [
                   "custom_attribute_definitions", "program", "audit",
                   "objects_under_assessment"
           ]:
               converted_attr_value = (
                   unicode(attr_value.get("title"))
                   if attr_name != "custom_attribute_definitions" else {
                       attr_value.get("id"):
                       attr_value.get("title").upper()
                   })
           if attr_name in ["custom_attribute_values"]:
               converted_attr_value = {
                   attr_value.get("custom_attribute_id"):
                   attr_value.get("attribute_value")
               }
           if obj_attr_name == "comments":
               converted_attr_value = {
                   k:
                   (string_utils.convert_str_to_datetime(v) if
                    k == "created_at" and isinstance(v, unicode) else v)
                   for k, v in attr_value.iteritems()
                   if k in ["modified_by", "created_at", "description"]
               }
           return converted_attr_value
Пример #3
0
    def convert_obj_repr_from_rest_to_ui(cls, obj):
        """Convert object's attributes values from REST like
    (dict or list of dict) representation to UI like with unicode.
    Examples:
    None to None, u'Ex' to u'Ex', [u'Ex1', u'Ex2', ...] to u'Ex1, Ex2',
    {'name': u'Ex', ...} to u'Ex',
    [{'name': u'Ex1', ...}, {'name': u'Ex2', ...}] to u'Ex1, Ex2'
    """

        # pylint: disable=too-many-locals
        # pylint: disable=undefined-loop-variable
        def convert_attr_value_from_dict_to_unicode(attr_name, attr_value):
            """Convert attribute value from dictionary to unicode representation
      (get value by key from dictionary 'attr_value' where key determine
      according to 'attr_name').
      """
            if isinstance(attr_value, dict):
                converted_attr_value = attr_value
                if attr_name in [
                        "contact", "manager", "owners", "assessor", "creator",
                        "verifier", "created_by", "modified_by", "Assessor",
                        "Creator", "Verifier"
                ]:
                    converted_attr_value = unicode(attr_value.get("name"))
                if attr_name in [
                        "custom_attribute_definitions", "program", "audit",
                        "objects_under_assessment"
                ]:
                    converted_attr_value = (
                        unicode(attr_value.get("title"))
                        if attr_name != "custom_attribute_definitions" else {
                            attr_value.get("id"):
                            attr_value.get("title").upper()
                        })
                if attr_name in ["custom_attribute_values"]:
                    converted_attr_value = {
                        attr_value.get("custom_attribute_id"):
                        attr_value.get("attribute_value")
                    }
                if obj_attr_name == "comments":
                    converted_attr_value = {
                        k:
                        (string_utils.convert_str_to_datetime(v) if
                         k == "created_at" and isinstance(v, unicode) else v)
                        for k, v in attr_value.iteritems()
                        if k in ["modified_by", "created_at", "description"]
                    }
                return converted_attr_value

        origin_obj = copy.deepcopy(obj)
        for obj_attr_name in obj.__dict__.keys():
            # 'Ex', u'Ex', 1, None to 'Ex', u'Ex', 1, None
            obj_attr_value = (obj.assignees.get(obj_attr_name.title()) if (
                obj_attr_name in ["assessor", "creator", "verifier"]
                and "assignees" in obj.__dict__.keys()) else getattr(
                    obj, obj_attr_name))
            # u'2017-06-07T16:50:16' and u'2017-06-07 16:50:16' to datetime
            if (obj_attr_name in ["updated_at", "created_at"]
                    and isinstance(obj_attr_value, unicode)):
                obj_attr_value = string_utils.convert_str_to_datetime(
                    obj_attr_value)
            if isinstance(obj_attr_value, dict) and obj_attr_value:
                # to "assignees" = {"Assessor": [], "Creator": [], "Verifier": []}
                if obj_attr_name == "assignees":
                    obj_attr_value = {
                        k: ([
                            convert_attr_value_from_dict_to_unicode(k, _v)
                            for _v in v
                        ] if isinstance(v, list) else
                            convert_attr_value_from_dict_to_unicode(k, v))
                        for k, v in obj_attr_value.iteritems()
                        if k in ["Assessor", "Creator", "Verifier"]
                    }
                # {'name': u'Ex1', 'type': u'Ex2', ...} to u'Ex1'
                else:
                    obj_attr_value = convert_attr_value_from_dict_to_unicode(
                        obj_attr_name, obj_attr_value)
            # [el1, el2, ...] or [{item1}, {item2}, ...] to [u'Ex1, u'Ex2', ...]
            if (isinstance(obj_attr_value, list)
                    and all(isinstance(item, dict)
                            for item in obj_attr_value)):
                obj_attr_value = [
                    convert_attr_value_from_dict_to_unicode(
                        obj_attr_name, item) for item in obj_attr_value
                ]
            setattr(obj, obj_attr_name, obj_attr_value)
        # merge "custom_attribute_definitions" and "custom_attribute_values"
        obj_cas_attrs_names = [
            "custom_attributes", "custom_attribute_definitions",
            "custom_attribute_values"
        ]
        if set(obj_cas_attrs_names).issubset(obj.__dict__.keys()):
            cas_def = obj.custom_attribute_definitions
            cas_val = obj.custom_attribute_values
            # form CAs values of CAs definitions exist but CAs values not, or if CAs
            # definitions have different then CAs values lengths
            if cas_def and (not cas_val or
                            (isinstance(cas_def and cas_val, list)
                             and len(cas_def) != len(cas_val))):
                cas_val_dicts_keys = ([_.keys()[0] for _ in cas_val]
                                      if isinstance(cas_val, list) else [None])
                _cas_val = [{
                    k: v
                } for k, v in CustomAttributeDefinitionsFactory(
                ).generate_ca_values(
                    list_ca_def_objs=origin_obj.custom_attribute_definitions,
                    is_none_values=True).iteritems()
                            if k not in cas_val_dicts_keys]
                cas_val = _cas_val if not cas_val else cas_val + _cas_val
            cas_def_dict = (dict([_def.iteritems().next()
                                  for _def in cas_def]) if
                            (isinstance(cas_def, list) and all(
                                isinstance(_def, dict)
                                for _def in cas_def)) else {
                                    None: None
                                })
            cas_val_dict = (dict([_val.iteritems().next()
                                  for _val in cas_val]) if
                            (isinstance(cas_def, list) and all(
                                isinstance(_def, dict)
                                for _def in cas_def)) else {
                                    None: None
                                })
            cas = string_utils.merge_dicts_by_same_key(cas_def_dict,
                                                       cas_val_dict)
            setattr(obj, "custom_attributes", cas)
        return obj