Python inflection.dasherize() Examples

The following are 11 code examples of inflection.dasherize(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module inflection , or try the search function .
Example #1
Source File: utils.py    From django-rest-framework-json-api with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def format_field_names(obj, format_type=None):
    """
    Takes a dict and returns it with formatted keys as set in `format_type`
    or `JSON_API_FORMAT_FIELD_NAMES`

    :format_type: Either 'dasherize', 'camelize', 'capitalize' or 'underscore'
    """
    if format_type is None:
        format_type = json_api_settings.FORMAT_FIELD_NAMES

    if isinstance(obj, dict):
        formatted = OrderedDict()
        for key, value in obj.items():
            key = format_value(key, format_type)
            formatted[key] = value
        return formatted

    return obj 
Example #2
Source File: templates.py    From argo-python-dsl with Apache License 2.0 6 votes vote down vote up
def __call__(self, f: Callable[..., None]) -> template:
        super().__call__(f)

        self.name = dasherize(f.__code__.co_name)

        source: List[str]
        source, _ = inspect.getsourcelines(f.__code__)

        co_start: int = 0
        for i, line in enumerate(source):
            if re.search(r"\)( -> (.+))?:[\s\n\r]+$", line):
                co_start = i + 1
                break

        self.source = textwrap.dedent("".join(source[co_start:]))

        tmpl = template(f)
        tmpl.callable = False

        tmpl.__closure__ = self.scope

        return tmpl 
Example #3
Source File: utils.py    From django-rest-framework-json-api with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def format_value(value, format_type=None):
    if format_type is None:
        format_type = json_api_settings.FORMAT_FIELD_NAMES
    if format_type == 'dasherize':
        # inflection can't dasherize camelCase
        value = inflection.underscore(value)
        value = inflection.dasherize(value)
    elif format_type == 'camelize':
        value = inflection.camelize(value, False)
    elif format_type == 'capitalize':
        value = inflection.camelize(value)
    elif format_type == 'underscore':
        value = inflection.underscore(value)
    return value 
Example #4
Source File: style_configuration.py    From urbanfootprint with GNU General Public License v3.0 5 votes vote down vote up
def build_style_string(style, separator=' '):
    """
        Creates key value pairs as a string for the given Style with the given separator
        between the paris
    :param style:
    :param separator: Default ' '
    :return:
    """

    style_string = separator.join(
        map_dict(
            lambda key, value: '{key}: {value};'.format(key=dasherize(key), value=map_value(value)),
            compact_dict(style)))

    return style_string 
Example #5
Source File: _workflow.py    From argo-python-dsl with Apache License 2.0 5 votes vote down vote up
def __new__(
        cls,
        name: Union[str, Type["Workflow"]],
        bases: Tuple[Type["Workflow"], ...],
        props: Dict[str, Any],
        **kwargs,
    ):
        workflow_name = dasherize(underscore(name))

        props["kind"] = "Workflow"
        props["api_version"] = "argoproj.io/v1alpha1"

        metadata_dict = dict(name=workflow_name, generate_name=f"{workflow_name}-")
        metadata_dict.update(props.get("__metadata__", {}))

        # Required fields
        props["metadata"]: V1ObjectMeta = V1ObjectMeta(**metadata_dict)
        props["spec"] = {
            k: props.pop(k) for k in V1alpha1WorkflowSpec.attribute_map if props.get(k)
        }
        props["status"] = {}

        bases = (*bases, cls.__model__)
        klass = super().__new__(cls, name, bases, props)

        if name == "Workflow":
            # No need to initialize any further
            return klass

        cls.__compile(klass, name, bases, props)

        return klass 
Example #6
Source File: tasks.py    From argo-python-dsl with Apache License 2.0 5 votes vote down vote up
def __new__(cls, f: Callable[..., T]):
        """Workflow spec for V1alpha1Template."""
        self = super().__new__(cls, f)
        self.name = dasherize(f.__code__.co_name)

        self.template: str = None
        self.template_ref: V1alpha1TemplateRef = None

        return self 
Example #7
Source File: templates.py    From argo-python-dsl with Apache License 2.0 5 votes vote down vote up
def __new__(cls, f: Callable[..., T]):
        """Workflow spec for V1alpha1Template."""
        self = super().__new__(cls, f)
        self.name = dasherize(f.__code__.co_name)

        return self 
Example #8
Source File: serializer.py    From sqlalchemy-jsonapi with MIT License 5 votes vote down vote up
def _render_attributes(self, resource):
        """Render the resources's attributes."""
        attributes = {}
        attrs_to_ignore = set()

        for key, relationship in resource.__mapper__.relationships.items():
            attrs_to_ignore.update(set(
                [column.name for column in relationship.local_columns]).union(
                    {key}))

        if self.dasherize:
            mapped_fields = {x: dasherize(underscore(x)) for x in self.fields}
        else:
            mapped_fields = {x: x for x in self.fields}

        for attribute in self.fields:
            if attribute == self.primary_key:
                continue
            # Per json-api spec, we cannot render foreign keys
            # or relationsips in attributes.
            if attribute in attrs_to_ignore:
                raise AttributeError
            try:
                value = getattr(resource, attribute)
                if isinstance(value, datetime.datetime):
                    attributes[mapped_fields[attribute]] = value.isoformat()
                else:
                    attributes[mapped_fields[attribute]] = value
            except AttributeError:
                raise

        return attributes 
Example #9
Source File: serializer.py    From sqlalchemy-jsonapi with MIT License 5 votes vote down vote up
def _render_relationships(self, resource):
        """Render the resource's relationships."""
        relationships = {}
        related_models = resource.__mapper__.relationships.keys()
        primary_key_val = getattr(resource, self.primary_key)
        if self.dasherize:
            mapped_relationships = {
                x: dasherize(underscore(x)) for x in related_models}
        else:
            mapped_relationships = {x: x for x in related_models}

        for model in related_models:
            relationships[mapped_relationships[model]] = {
                'links': {
                    'self': '/{}/{}/relationships/{}'.format(
                        resource.__tablename__,
                        primary_key_val,
                        mapped_relationships[model]),
                    'related': '/{}/{}/{}'.format(
                        resource.__tablename__,
                        primary_key_val,
                        mapped_relationships[model])
                }
            }

        return relationships 
Example #10
Source File: serializer.py    From sqlalchemy-jsonapi with MIT License 5 votes vote down vote up
def _api_type_for_model(self, model):
        return dasherize(tableize(model.__name__)) 
Example #11
Source File: base.py    From benchling-api with MIT License 5 votes vote down vote up
def _tableize(cls):
        """Tableize the model name.

        :return:
        """
        name = inflection.tableize(cls.__name__)
        name = inflection.dasherize(name)
        return name