def name(cls): name = camel_case_to_spaces(cls.__name__) if name.endswith('plan'): name = name[:-5] if name.endswith('importation'): name = name[:-12] return '_'.join(name.split())
def contribute_to_class(self, cls, name): setattr(cls, name, self) self.object_name = cls.__name__ self.verbose_name = camel_case_to_spaces(self.object_name) if self.meta: meta_attrs = self.meta.__dict__.copy() for name in self.meta.__dict__: if name.startswith('_'): del meta_attrs[name] for attr_name in DEFAULT_NAMES: if attr_name in meta_attrs: setattr(self, attr_name, meta_attrs.pop(attr_name)) elif hasattr(self.meta, attr_name): setattr(self, attr_name, getattr(self.meta, attr_name)) # Any leftover attributes must be invalid. if meta_attrs != {}: raise TypeError( f"'class Meta' got invalid attribute(s): {','.join(meta_attrs)}" ) del self.meta
def __new__(cls, name, bases, namespace): base_variables = {} base_bindings = {} for base in bases: base_variables.update(getattr(base, "variables", {})) base_bindings.update(getattr(base, "bindings", {})) variables = [] bindings = [] for key in list(namespace.keys()): value = namespace[key] if isinstance(value, Binding): dest_list = bindings elif isinstance(value, Variable): dest_list = variables else: dest_list = None if dest_list is not None: dest_list.append((key, value)) del namespace[key] namespace.setdefault("variables", {}).update(base_variables) namespace.setdefault("variables", {}).update(variables) namespace.setdefault("bindings", {}).update(base_bindings) namespace.setdefault("bindings", {}).update(bindings) # Figure out some sane defaults if "identifier" not in namespace: namespace["identifier"] = snake_case(camel_case_to_spaces(name)) if namespace.get("identifier") and not namespace.get("name"): namespace["name"] = space_case(namespace["identifier"]).title() return type.__new__(cls, name, bases, namespace)
def contribute_to_class(self, cls, name): from django.db import connection from django.db.backends.utils import truncate_name cls._meta = self self.model = cls # First, construct the default values for these options. self.object_name = cls.__name__ self.model_name = self.object_name.lower() self.verbose_name = camel_case_to_spaces(self.object_name) # Store the original user-defined values for each option, # for use when serializing the model definition self.original_attrs = {} # Next, apply any overridden values from 'class Meta'. if self.meta: meta_attrs = self.meta.__dict__.copy() for name in self.meta.__dict__: # Ignore any private attributes that Django doesn't care about. # NOTE: We can't modify a dictionary's contents while looping # over it, so we loop over the *original* dictionary instead. if name.startswith('_'): del meta_attrs[name] for attr_name in DEFAULT_NAMES: if attr_name in meta_attrs: setattr(self, attr_name, meta_attrs.pop(attr_name)) self.original_attrs[attr_name] = getattr(self, attr_name) elif hasattr(self.meta, attr_name): setattr(self, attr_name, getattr(self.meta, attr_name)) self.original_attrs[attr_name] = getattr(self, attr_name) self.unique_together = normalize_together(self.unique_together) self.index_together = normalize_together(self.index_together) # App label/class name interpolation for names of constraints and # indexes. if not getattr(cls._meta, 'abstract', False): for attr_name in {'constraints', 'indexes'}: objs = getattr(self, attr_name, []) setattr(self, attr_name, self._format_names_with_class(cls, objs)) # verbose_name_plural is a special case because it uses a 's' # by default. if self.verbose_name_plural is None: self.verbose_name_plural = format_lazy('{}s', self.verbose_name) # order_with_respect_and ordering are mutually exclusive. self._ordering_clash = bool(self.ordering and self.order_with_respect_to) # Any leftover attributes must be invalid. if meta_attrs != {}: raise TypeError("'class Meta' got invalid attribute(s): %s" % ','.join(meta_attrs)) else: self.verbose_name_plural = format_lazy('{}s', self.verbose_name) del self.meta # If the db_table wasn't provided, use the app_label + model_name. if not self.db_table: self.db_table = "%s_%s" % (self.app_label, self.model_name) self.db_table = truncate_name(self.db_table, connection.ops.max_name_length())
def get_prefix(self): # autogenerate a prefix from the model name if one is not supplied manually if not self.prefix: self.prefix = slugify(camel_case_to_spaces( self.model.__name__)) + '-chooser' return self.prefix
def _guess_parent_ref_field_name(self): """Hacky way to "guess" parent class-referencing field name """ parent_field_name = ( camel_case_to_spaces(self.Meta.model.__name__).replace(' ', '_') + '_id') return parent_field_name
def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['list_name'] = self.model_name.lower() + 's' context['list_display_name'] = camel_case_to_spaces( self.model_name) + 's' context['model_name'] = self.model_name.lower() return context
def __new__(cls, name, bases, namespace): variables = [] bindings = [] for key in list(namespace.keys()): value = namespace[key] if isinstance(value, Binding): dest_list = bindings elif isinstance(value, Variable): dest_list = variables else: dest_list = None if dest_list is not None: dest_list.append((key, value)) del namespace[key] namespace.setdefault("variables", {}).update(variables) namespace.setdefault("bindings", {}).update(bindings) # Figure out some sane defaults if "identifier" not in namespace: namespace["identifier"] = snake_case(camel_case_to_spaces(name)) if namespace.get("identifier") and not namespace.get("name"): namespace["name"] = space_case(namespace["identifier"]).title() return type.__new__(cls, name, bases, namespace)
def test_critical_model_meta(model_and_factory): model, _ = model_and_factory # noqa assert hasattr(model._meta, 'verbose_name') # noqa assert model._meta.verbose_name != camel_case_to_spaces( # noqa model._meta.object_name) # noqa assert hasattr(model._meta, 'verbose_name_plural') # noqa assert model._meta.verbose_name_plural != f'{model._meta.verbose_name}s' # noqa
def contribute_to_class(self, cls, name): cls._meta = self self.model = cls # First, construct the default values for these options. self.object_name = cls.__name__ self.model_name = self.object_name.lower() self.verbose_name = camel_case_to_spaces(self.object_name) # Next, apply any overridden values from 'class Meta'. if self.meta: meta_attrs = self.meta.__dict__.copy() for name in self.meta.__dict__: # NOTE: We can't modify a dictionary's contents while looping # over it, so we loop over the *original* dictionary instead. if name.startswith('_'): del meta_attrs[name] for attr_name in DEFAULT_NAMES: if attr_name in meta_attrs: setattr(self, attr_name, meta_attrs.pop(attr_name)) elif hasattr(self.meta, attr_name): setattr(self, attr_name, getattr(self.meta, attr_name)) # verbose_name_plural is a special case because it uses a 's' # by default. if self.verbose_name_plural is None: self.verbose_name_plural = format_lazy('{}s', self.verbose_name) # Any leftover attributes must be invalid. if meta_attrs != {}: raise TypeError("'class Meta' got invalid attribute(s): %s" % ','.join(meta_attrs)) else: self.verbose_name_plural = format_lazy('{}s', self.verbose_name) del self.meta
def _profile_part(instance): class_name = instance.__class__.__name__ if class_name == "Profile": return "base profile" return camel_case_to_spaces(class_name)
def get_context(self, request: HttpRequest, exception: Exception) -> ContextDict: """ Get a context dictionary with various context data. This is used both for template name determination as well as template rendering. :param request: Django request that caused the exception :param exception: The exception that occurred :returns: Variables """ resolver_match = getattr(request, 'resolver_match', None) exc_type = camel_case_to_spaces(exception.__class__.__name__).replace( ' ', '_') env = { 'exception': exception, 'message': force_str(exception), 'code': getattr(exception, 'code', None), 'title': (getattr(exception, 'title', None) or _('Error')), 'exc_type': exc_type, 'view_name': getattr(resolver_match, 'view_name', None), 'url_name': getattr(resolver_match, 'url_name', None), 'app_name': getattr(resolver_match, 'app_name', None), 'namespace': getattr(resolver_match, 'namespace', None), } return env
def get_field_params(field): params = OrderedDict() if field['label'] and field['label'] != camel_case_to_spaces( re.sub('__c$', '', field['name'])).title(): params['verbose_name'] = field['label'] if not field['updateable'] or not field['createable']: # Fields that are result of a formula or system fields modified # by triggers or by other apex code # use symbolic names NOT_UPDATEABLE, NOT_CREATABLE, READ_ONLY instead of 1, 2, 3 sf_read_only = (0 if field['updateable'] else 1) | (0 if field['createable'] else 2) params['sf_read_only'] = reverse_models_names[sf_read_only] if field['defaultedOnCreate'] and field['createable']: if field['defaultValue'] is None: params['default'] = SymbolicModelsName('DEFAULTED_ON_CREATE') else: params['default'] = SymbolicModelsName('DefaultedOnCreate', field['defaultValue']) elif field['defaultValue'] is not None: params['default'] = field['defaultValue'] if field['inlineHelpText']: params['help_text'] = field['inlineHelpText'] if field['picklistValues']: params['choices'] = [(x['value'], x['label']) for x in field['picklistValues'] if x['active']] if field['type'] == 'reference' and not field['referenceTo']: params['ref_comment'] = 'No Reference table' return params
def text(cls): if hasattr(cls, 'action_text'): return cls.action_text from django.utils.text import camel_case_to_spaces txt = cls.__name__ txt = txt.replace('Form', '') txt = camel_case_to_spaces(txt) return txt
def dispatch(self): data = json.loads(self.request.body.decode("UTF-8")) command = data.pop("command") func_name = "handle_%s" % snake_case(camel_case_to_spaces(command)) func = getattr(self, func_name, None) if not callable(func): return JsonResponse({"error": "No handler: %s" % func_name}) return func(data)
def camel_space_to_spaces(value): """ Split CamelCase and convert to lower case. Strip surrounding whitespace and multiple consecutive internal spaces. """ de_cameled = camel_case_to_spaces(value) return re_multiple_spaces.sub(r' ', de_cameled)
def mutation_parameters() -> dict: dict_params = { 'login': LoginMutation.Field(), 'logout': LogoutMutation.Field(), } dict_params.update((camel_case_to_spaces(n).replace(' ', '_'), mut.Field()) for n, mut in registry.forms.items()) return dict_params
def url(self): if not self.id: raise ValueError( f"Can't get url for unsaved {self.__class__.__name__}") app_name = self._meta.app_label.replace("_", "-") model_name = camel_case_to_spaces(self.__class__.__name__).replace( " ", "-") view_name = f"v{DATAGROWTH_API_VERSION}:{app_name}:{model_name}-content" return reverse(view_name, args=[self.id])
def id_html_elements(self): # преобразование имени объекта с помощью джанго-утилиты model_name = camel_case_to_spaces( self.model._meta.object_name).replace(' ', '_') slider_name = f"id_{model_name}" # TODO: получать значение pk min_input = f"{model_name}-0-min" max_input = f"{model_name}-0-max" return slider_name, min_input, max_input
def snake_case_name(self): """ returns model name in snake case :return: model field name :rtype: str """ return camel_case_to_spaces(self.name).replace(' ', '_')
def render(self, name, value, *args, **kwargs): widget = self.widget widget.choices = self.choices output = [self.widget.render(name, value, *args, **kwargs)] output.append(u'<a href="javascript:void(0);" class="add-another" id="add_id_{0}" data-url="{1}">'\ .format(name, self.new_url)) output.append(u'<small>%s</small></a>' % ugettext('New {0}').\ format(camel_case_to_spaces(name).title())) return mark_safe(u''.join(output))
def get_view_name(cls): view_name_parts = camel_case_to_spaces(cls.__name__).split() try: if view_name_parts[-1] == 'view': view_name_parts.pop() if view_name_parts[-1] == cls.base_name: view_name_parts.pop() except IndexError: pass return '_'.join(view_name_parts)
def get_handler(self, operation_id): if operation_id in self.handlers: return self.handlers[operation_id] snake_operation_id = camel_case_to_spaces(operation_id).replace( ' ', '_') if snake_operation_id in self.handlers: return self.handlers[snake_operation_id] raise MissingHandler( 'Missing handler for operation %s (tried %s too)' % (operation_id, snake_operation_id))
class Options(object): model = owner object_name = owner.__name__ model_name = owner.__name__.lower() verbose_name = camel_case_to_spaces(owner.__name__) class pk(object): @classmethod def value_to_string(cls, obj): return str(obj.pk)
def mutation_parameters() -> dict: dict_params = { "token_auth": ObtainJSONWebToken.Field(), "verify_token": graphql_jwt.Verify.Field(), "refresh_token": graphql_jwt.Refresh.Field(), "revoke_token": graphql_jwt.Revoke.Field(), } dict_params.update( (camel_case_to_spaces(n).replace(" ", "_"), mut.Field()) for n, mut in registry.forms.items()) return dict_params
def contribute_to_class(self, cls, name): from django.db import connection from django.db.backends.utils import truncate_name cls._meta = self self.model = cls # First, construct the default values for these options. self.object_name = cls.__name__ self.model_name = self.object_name.lower() self.verbose_name = camel_case_to_spaces(self.object_name) # Store the original user-defined values for each option, # for use when serializing the model definition self.original_attrs = {} # Next, apply any overridden values from 'class Meta'. if self.meta: meta_attrs = self.meta.__dict__.copy() for name in self.meta.__dict__: # Ignore any private attributes that Django doesn't care about. # NOTE: We can't modify a dictionary's contents while looping # over it, so we loop over the *original* dictionary instead. if name.startswith('_'): del meta_attrs[name] for attr_name in DEFAULT_NAMES: if attr_name in meta_attrs: setattr(self, attr_name, meta_attrs.pop(attr_name)) self.original_attrs[attr_name] = getattr(self, attr_name) elif hasattr(self.meta, attr_name): setattr(self, attr_name, getattr(self.meta, attr_name)) self.original_attrs[attr_name] = getattr(self, attr_name) self.unique_together = normalize_together(self.unique_together) self.index_together = normalize_together(self.index_together) # verbose_name_plural is a special case because it uses a 's' # by default. if self.verbose_name_plural is None: self.verbose_name_plural = format_lazy('{}s', self.verbose_name) # order_with_respect_and ordering are mutually exclusive. self._ordering_clash = bool(self.ordering and self.order_with_respect_to) # Any leftover attributes must be invalid. if meta_attrs != {}: raise TypeError("'class Meta' got invalid attribute(s): %s" % ','.join(meta_attrs)) else: self.verbose_name_plural = format_lazy('{}s', self.verbose_name) del self.meta # If the db_table wasn't provided, use the app_label + model_name. if not self.db_table: self.db_table = "%s_%s" % (self.app_label, self.model_name) self.db_table = truncate_name(self.db_table, connection.ops.max_name_length())
def contribute_to_class(self, cls, name): from django.db import connection from django.db.backends.utils import truncate_name cls._meta = self self.model = cls # First, construct the default values for these options. self.object_name = cls.__name__ self.model_name = self.object_name.lower() self.verbose_name = camel_case_to_spaces(self.object_name) # Store the original user-defined values for each option, # for use when serializing the model definition self.original_attrs = {} # Next, apply any overridden values from 'class Meta'. if self.meta: meta_attrs = self.meta.__dict__.copy() for name in self.meta.__dict__: # Ignore any private attributes that Django doesn't care about. # NOTE: We can't modify a dictionary's contents while looping # over it, so we loop over the *original* dictionary instead. if name.startswith('_'): del meta_attrs[name] for attr_name in DEFAULT_NAMES: if attr_name in meta_attrs: setattr(self, attr_name, meta_attrs.pop(attr_name)) self.original_attrs[attr_name] = getattr(self, attr_name) elif hasattr(self.meta, attr_name): setattr(self, attr_name, getattr(self.meta, attr_name)) self.original_attrs[attr_name] = getattr(self, attr_name) ut = meta_attrs.pop('unique_together', self.unique_together) self.unique_together = normalize_unique_together(ut) # verbose_name_plural is a special case because it uses a 's' # by default. if self.verbose_name_plural is None: self.verbose_name_plural = string_concat( self.verbose_name, 's') # Any leftover attributes must be invalid. if meta_attrs != {}: raise TypeError("'class Meta' got invalid attribute(s): %s" % ','.join(meta_attrs.keys())) else: self.verbose_name_plural = string_concat(self.verbose_name, 's') del self.meta # If the db_table wasn't provided, use the app_label + model_name. if not self.db_table: self.db_table = "%s_%s" % (self.app_label, self.model_name) self.db_table = truncate_name(self.db_table, connection.ops.max_name_length())
def mutation_parameters() -> dict: dict_params = { #'login': LoginMutation.Field(), #'logout': LogoutMutation.Field(), 'token_auth': graphql_jwt.ObtainJSONWebToken.Field(), 'verify_token': graphql_jwt.Verify.Field(), 'refresh_token': graphql_jwt.Refresh.Field(), } dict_params.update((camel_case_to_spaces(n).replace(' ', '_'), mut.Field()) for n, mut in registry.forms.items()) return dict_params
def get_table_description(self, cursor, table_name): "Returns a description of the table, with the DB-API cursor.description interface." # pylint:disable=too-many-locals,unused-argument result = [] for field in self.table_description_cache(table_name)['fields']: params = OrderedDict() if field['label'] and field['label'] != camel_case_to_spaces( re.sub('__c$', '', field['name'])).title(): params['verbose_name'] = field['label'] if not field['updateable'] or not field['createable']: # Fields that are result of a formula or system fields modified # by triggers or by other apex code sf_read_only = (0 if field['updateable'] else 1) | (0 if field['createable'] else 2) # use symbolic names NOT_UPDATEABLE, NON_CREATABLE, READ_ONLY instead of 1, 2, 3 params['sf_read_only'] = reverse_models_names[sf_read_only] if field['defaultedOnCreate']: if field['defaultValue'] is None: params['default'] = SymbolicModelsName( 'DEFAULTED_ON_CREATE') else: params['default'] = SymbolicModelsName( 'DefaultedOnCreate', field['defaultValue']) elif field['defaultValue'] is not None: params['default'] = field['defaultValue'] if field['inlineHelpText']: params['help_text'] = field['inlineHelpText'] if field['picklistValues']: params['choices'] = [(x['value'], x['label']) for x in field['picklistValues'] if x['active']] if field['type'] == 'reference' and not field['referenceTo']: params['ref_comment'] = 'No Reference table' field['type'] = 'string' if field['calculatedFormula']: # calculated formula field are without length in Salesforce 45 Spring '19, # but Django requires a length, though the field is read only and never written field['length'] = 1300 # We prefer "length" over "byteLength" for "internal_size". # (because strings have usually: byteLength == 3 * length) result.append( FieldInfo( field['name'], # name, field['type'], # type_code, field['length'], # display_size, field['length'], # internal_size, field['precision'], # precision, field['scale'], # scale, field['nillable'], # null_ok, params.get('default'), # default params, )) return result
def mutate(_self, info, token, url, values): url_prefix = url_prefix_for_site(info) query = wagtailPage.objects.filter(url_path=url_prefix + url.rstrip('/') + '/') instance = with_page_permissions(info.context, query.specific()).live().first() user = info.context.user # convert camelcase to dashes values = { camel_case_to_spaces(k).replace(' ', '-'): v for k, v in values.items() } form = instance.get_form(values, None, page=instance, user=user) ''' This try/except can parse a submitted anamnese or questionnaire to a valid form. A form can either be submitted as 'key': 'value', which is always valid. In this case, the following section will not be able to convert the form data and the program will continue as usual. Or the form is submitted as 'key': '{'helpText': helpText, 'fieldType': fieldType, 'value': value}'. In this case, if the form can entirely be translated (each key has a value field in its dict), it is also a valid submission. ''' try: tmp_values = values form.full_values = {} for v in values: # print("V: ", v) # print("VC", json.loads(values[v].replace('\'', '\"'))['value']) form.full_values[v] = json.loads(values[v].replace('\'', '\"')) values[v] = form.full_values[v]['value'] parsed = True except: values = tmp_values form.full_values = values parsed = False if form.is_valid(): # form_submission instance.process_form_submission(form) if parsed: msg = "OK, parsed special input" else: msg = "OK" return registry.forms[_node](result=msg) else: return registry.forms[_node]( result="FAIL", errors=[FormError(*err) for err in form.errors.items()])
def contribute_to_class(self, cls, name): setattr(cls, name, self) self.model = cls self.object_name = cls.__name__ self.model_name = self.object_name.lower() self.verbose_name = camel_case_to_spaces(self.object_name) self.storage_name = cls.__name__.lower() + 's' self.original_attrs = {} if self.meta: if hasattr(self.meta, 'storage_name'): self.storage_name = self.meta.storage_name if hasattr(self.meta, 'json_db_name'): self.json_db_name = self.meta.json_db_name if hasattr(self.meta, 'ordering'): self.ordering = list(self.meta.ordering)
def mutate(_self, info, token, url, values): url_prefix = url_prefix_for_site(info) query = wagtailPage.objects.filter(url_path=url_prefix + url.rstrip('/') + '/') instance = with_page_permissions( info.context, query.specific() ).live().first() user = info.context.user # convert camelcase to dashes values = {camel_case_to_spaces(k).replace(' ', '-'): v for k, v in values.items()} form = instance.get_form(values, None, page=instance, user=user) if form.is_valid(): # form_submission instance.process_form_submission(form) return registry.forms[_node](result="OK") else: return registry.forms[_node](result="FAIL", errors=[FormError(*err) for err in form.errors.items()])
def get_table_description(self, cursor, table_name): "Returns a description of the table, with the DB-API cursor.description interface." # pylint:disable=too-many-locals,unused-argument result = [] for field in self.table_description_cache(table_name)['fields']: params = OrderedDict() if field['label'] and field['label'] != camel_case_to_spaces(re.sub('__c$', '', field['name'])).title(): params['verbose_name'] = field['label'] if not field['updateable'] or not field['createable']: # Fields that are result of a formula or system fields modified # by triggers or by other apex code sf_read_only = (0 if field['updateable'] else 1) | (0 if field['createable'] else 2) # use symbolic names NOT_UPDATEABLE, NON_CREATABLE, READ_ONLY instead of 1, 2, 3 params['sf_read_only'] = reverse_models_names[sf_read_only] if field['defaultValue'] is not None: params['default'] = field['defaultValue'] if field['inlineHelpText']: params['help_text'] = field['inlineHelpText'] if field['picklistValues']: params['choices'] = [(x['value'], x['label']) for x in field['picklistValues'] if x['active']] if field['defaultedOnCreate'] and field['createable']: params['default'] = SymbolicModelsName('DEFAULTED_ON_CREATE') if field['type'] == 'reference' and not field['referenceTo']: params['ref_comment'] = 'No Reference table' field['type'] = 'string' if field['calculatedFormula']: # calculated formula field are without length in Salesforce 45 Spring '19, # but Django requires a length, though the field is read only and never written field['length'] = 1300 # We prefer "length" over "byteLength" for "internal_size". # (because strings have usually: byteLength == 3 * length) result.append(FieldInfo( field['name'], # name, field['type'], # type_code, field['length'], # display_size, field['length'], # internal_size, field['precision'], # precision, field['scale'], # scale, field['nillable'], # null_ok, params.get('default'), # default params, )) return result
def snake_case(cls): return camel_case_to_spaces(cls.__name__).lower().replace(" ", "_")
def camel_case_to_dashes(value): return '-'.join(camel_case_to_spaces(value).split(' '))
def captitle(title): return capfirst(camel_case_to_spaces(title))
def _update_from_name(self, name): self.name = name self.verbose_name = self.verbose_name or camel_case_to_spaces(name) self.verbose_name_plural = self.verbose_name_plural or self.verbose_name + 's'
def __getValidationKeyFromClass(app, cls): validationKey = getattr(cls, 'key', None) if not validationKey: validationKey = camel_case_to_spaces(cls.__name__).replace(' ', '_') return "{}_{}".format(app.name, validationKey)
def __init__(cls, name, bases, attrs): super(GingerMetaView, cls).__init__(name, bases, attrs) GingerMetaView.__position += 1 cls.position = GingerMetaView.__position cls.__abstract__ = attrs.get("__abstract__", False) cls.base_name = "_".join(camel_case_to_spaces(re.sub(r'(?i)view.*', '', cls.__name__)).split())
def create_verbose_name(name): name = camel_case_to_spaces(name) name = name.replace('_', ' ') return name
def name(self): if self.enum_class: return camel_case_to_spaces(self.enum_class.__class__.__name__) return u"<Invalid Enum>"