Python inflection.pluralize() Examples

The following are 13 code examples of inflection.pluralize(). 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: relations.py    From django-rest-framework-json-api with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def get_resource_type_from_included_serializer(self):
        """
        Check to see it this resource has a different resource_name when
        included and return that name, or None
        """
        field_name = self.field_name or self.parent.field_name
        parent = self.get_parent_serializer()

        if parent is not None:
            # accept both singular and plural versions of field_name
            field_names = [
                inflection.singularize(field_name),
                inflection.pluralize(field_name)
            ]
            includes = get_included_serializers(parent)
            for field in field_names:
                if field in includes.keys():
                    return get_resource_type_from_serializer(includes[field])

        return None 
Example #2
Source File: context.py    From dynamic-rest with MIT License 6 votes vote down vote up
def get_context(version, name, model, plural_name):
    name = inflection.underscore(inflection.singularize(name))
    model = model or name
    model_class_name = inflection.camelize(model)
    class_name = inflection.camelize(name)
    serializer_class_name = class_name + 'Serializer'
    viewset_class_name = class_name + 'ViewSet'
    plural_name = plural_name or inflection.pluralize(name)
    return {
        'version': version,
        'serializer_class_name': serializer_class_name,
        'viewset_class_name': viewset_class_name,
        'model_class_name': model_class_name,
        'name': name,
        'plural_name': plural_name
    } 
Example #3
Source File: models.py    From ramses with Apache License 2.0 6 votes vote down vote up
def prepare_relationship(config, model_name, raml_resource):
    """ Create referenced model if it doesn't exist.

    When preparing a relationship, we check to see if the model that will be
    referenced already exists. If not, it is created so that it will be possible
    to use it in a relationship. Thus the first usage of this model in RAML file
    must provide its schema in POST method resource body schema.

    :param model_name: Name of model which should be generated.
    :param raml_resource: Instance of ramlfications.raml.ResourceNode for
        which :model_name: will be defined.
    """
    if get_existing_model(model_name) is None:
        plural_route = '/' + pluralize(model_name.lower())
        route = '/' + model_name.lower()
        for res in raml_resource.root.resources:
            if res.method.upper() != 'POST':
                continue
            if res.path.endswith(plural_route) or res.path.endswith(route):
                break
        else:
            raise ValueError('Model `{}` used in relationship is not '
                             'defined'.format(model_name))
        setup_data_model(config, res, model_name) 
Example #4
Source File: profanityfilter.py    From profanityfilter with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_profane_words(self):
        """Returns all profane words currently in use."""
        profane_words = []

        if self._custom_censor_list:
            profane_words = [w for w in self._custom_censor_list]  # Previous versions of Python don't have list.copy()
        else:
            profane_words = [w for w in self._censor_list]

        profane_words.extend(self._extra_censor_list)
        profane_words.extend([inflection.pluralize(word) for word in profane_words])
        profane_words = list(set(profane_words))
        
        # We sort the list based on decreasing word length so that words like
        # 'fu' aren't substituted before 'fuck' if no_word_boundaries = true
        profane_words.sort(key=len)
        profane_words.reverse()

        return profane_words 
Example #5
Source File: utils.py    From django-rest-framework-json-api with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def format_resource_type(value, format_type=None, pluralize=None):
    if format_type is None:
        format_type = json_api_settings.FORMAT_TYPES

    if pluralize is None:
        pluralize = json_api_settings.PLURALIZE_TYPES

    if format_type:
        # format_type will never be None here so we can use format_value
        value = format_value(value, format_type)

    return inflection.pluralize(value) if pluralize else value 
Example #6
Source File: serializers.py    From dynamic-rest with MIT License 5 votes vote down vote up
def get_plural_name(cls):
        """Get the serializer's plural name.

        The plural name may be defined on the Meta class.
        If the plural name is not defined,
        the pluralized form of the name will be returned.
        """
        if not hasattr(cls.Meta, 'plural_name'):
            setattr(
                cls.Meta,
                'plural_name',
                inflection.pluralize(cls.get_name())
            )
        return cls.Meta.plural_name 
Example #7
Source File: __init__.py    From lore with MIT License 5 votes vote down vote up
def __tablename__(cls):
        return inflection.pluralize(inflection.underscore(cls.__name__)) 
Example #8
Source File: entity_mixins.py    From nailgun with GNU General Public License v3.0 5 votes vote down vote up
def _get_entity_ids(field_name, attrs):
    """Find the IDs for a one to many relationship.

    The server may return JSON data in the following forms for a
    :class:`nailgun.entity_fields.OneToManyField`::

        'user': [{'id': 1, …}, {'id': 42, …}]
        'users': [{'id': 1, …}, {'id': 42, …}]
        'user_ids': [1, 42]

    Search ``attrs`` for a one to many ``field_name`` and return its ID.

    :param field_name: A string. The name of a field.
    :param attrs: A dict. A JSON payload as returned from a server.
    :returns: An iterable of entity IDs.

    """
    field_name_ids = field_name + '_ids'
    plural_field_name = pluralize(field_name)
    if field_name_ids in attrs:
        return attrs[field_name_ids]
    elif field_name in attrs:
        return [entity['id'] for entity in attrs[field_name]]
    elif plural_field_name in attrs:
        return [entity['id'] for entity in attrs[plural_field_name]]
    else:
        raise MissingValueError(
            f'Cannot find a value for the "{field_name}" field. '
            f'Searched for keys named {field_name_ids}, {field_name}, {plural_field_name} '
            f'but available keys are {attrs.keys()}.'
        )


# -----------------------------------------------------------------------------
# Definition of parent Entity class and its dependencies.
# ----------------------------------------------------------------------------- 
Example #9
Source File: base.py    From benchling-api with MIT License 5 votes vote down vote up
def _camelize(cls, property=None):
        """Camelize the model name.

        :param property:
        :return:
        """
        name = inflection.underscore(cls.model_name)
        if property is not None:
            name += "_" + inflection.pluralize(property)
        else:
            name = inflection.pluralize(name)
        name = inflection.camelize(name)
        name = name[0].lower() + name[1:]
        return name 
Example #10
Source File: utils.py    From django-rest-framework-json-api with BSD 2-Clause "Simplified" License 4 votes vote down vote up
def get_resource_name(context, expand_polymorphic_types=False):
    """
    Return the name of a resource.
    """
    from rest_framework_json_api.serializers import PolymorphicModelSerializer
    view = context.get('view')

    # Sanity check to make sure we have a view.
    if not view:
        return None

    # Check to see if there is a status code and return early
    # with the resource_name value of `errors`.
    try:
        code = str(view.response.status_code)
    except (AttributeError, ValueError):
        pass
    else:
        if code.startswith('4') or code.startswith('5'):
            return 'errors'

    try:
        resource_name = getattr(view, 'resource_name')
    except AttributeError:
        try:
            serializer = view.get_serializer_class()
            if expand_polymorphic_types and issubclass(serializer, PolymorphicModelSerializer):
                return serializer.get_polymorphic_types()
            else:
                return get_resource_type_from_serializer(serializer)
        except AttributeError:
            try:
                resource_name = get_resource_type_from_model(view.model)
            except AttributeError:
                resource_name = view.__class__.__name__

            if not isinstance(resource_name, str):
                # The resource name is not a string - return as is
                return resource_name

            # the name was calculated automatically from the view > pluralize and format
            resource_name = format_resource_type(resource_name)

    return resource_name 
Example #11
Source File: __main__.py    From lore with MIT License 4 votes vote down vote up
def _generate_template(type, parsed, **kwargs):
    env.require(lore.dependencies.INFLECTION)
    import inflection
    name = parsed.name
    kwargs = kwargs or {}
    for attr in ['keras', 'xgboost', 'sklearn']:
        if hasattr(parsed, attr):
            kwargs[attr] = getattr(parsed, attr)
    kwargs['major_version'] = sys.version_info[0]
    kwargs['full_version'] = env.PYTHON_VERSION
    notebooks = ['features', 'architecture']
    name = inflection.underscore(name)
    if type == 'notebooks':
        for notebook in notebooks:
            _generate_template(notebook, parsed, **kwargs)
        return

    if type == 'test':
        destination = os.path.join(inflection.pluralize(type), 'unit', 'test_' + name + '.py')
    elif type in notebooks:
        destination = os.path.join('notebooks', name, type + '.ipynb')
    else:
        destination = os.path.join(env.APP, inflection.pluralize(type), name + '.py')

    if os.path.exists(destination):
        sys.exit(ansi.error() + ' %s already exists' % destination)

    dir = os.path.dirname(destination)
    if not os.path.exists(dir):
        os.makedirs(dir)
        if type not in notebooks:
            open(os.path.join(dir, '__init__.py'), 'w')

    kwargs['app_name'] = env.APP
    kwargs['module_name'] = name
    kwargs['class_name'] = inflection.camelize(name)
    code = _render_template(type + '.py.j2', **kwargs)

    with open(destination, 'w+') as file:
        file.write(code)

    print(ansi.success('CREATED ') + destination) 
Example #12
Source File: index.py    From grest with GNU General Public License v3.0 4 votes vote down vote up
def index(self, request):
    try:
        # patch __log
        self.__log = self._GRest__log

        __validation_rules__ = {
            "skip": fields.Int(required=False,
                               validate=lambda skip: skip >= 0,
                               missing=0),

            "limit": fields.Int(required=False,
                                validate=lambda lim: lim >= 1 and lim <= 100,
                                missing=QUERY_LIMIT),

            "order_by": fields.Str(required=False,
                                   missing="?")
        }

        (primary, secondary) = validate_models(self)

        query_data = validate_input(__validation_rules__, request)
        skip = query_data.get("skip")
        limit = query_data.get("skip") + query_data.get("limit")
        order_by = escape(query_data.get("order_by"))

        if order_by:
            if order_by.startswith("-"):
                # select property for descending ordering
                order_by_prop = order_by[1:]
            else:
                # select property for ascending ordering
                order_by_prop = order_by

            primary_model_props = primary.model.defined_properties().keys()
            if all([order_by_prop not in primary_model_props,
                    order_by_prop != "?"]):
                raise HTTPException(msg.INVALID_ORDER_PROPERTY, 404)

        total_items = len(primary.model.nodes)

        if total_items <= 0:
            raise HTTPException(msg.NO_ITEM_EXISTS.format(
                model=primary.model_name), 404)

        if skip > total_items:
            raise HTTPException(msg.VALIDATION_FAILED, 422)

        items = primary.model.nodes.order_by(order_by)[skip:limit]

        if items:
            return serialize({pluralize(primary.model_name):
                              [item.to_dict() for item in items]})
        else:
            raise HTTPException(msg.NO_ITEM_EXISTS.format(
                model=primary.model_name), 404)
    except DoesNotExist as e:
        self.__log.exception(e)
        raise HTTPException(msg.ITEM_DOES_NOT_EXIST, 404) 
Example #13
Source File: get.py    From grest with GNU General Public License v3.0 4 votes vote down vote up
def get(self, primary_id, secondary_model_name=None, secondary_id=None):
    try:
        # patch __log
        self.__log = self._GRest__log

        (primary, secondary) = validate_models(self,
                                               primary_id,
                                               secondary_model_name,
                                               secondary_id)

        primary_selected_item = primary.model.nodes.get_or_none(
            **{primary.selection_field: primary.id})

        if all([primary_selected_item,
                secondary.model,
                secondary.id]):
            # user selected a nested model with 2 keys
            # (from the primary and secondary models)
            # /users/user_id/roles/role_id -> selected role of this user
            # /categories/cat_id/tags/tag_id -> selected tag of this category

            # In this example, the p variable of type Post
            # is the secondary_item
            # (u:User)-[:POSTED]-(p:Post)
            secondary_item = primary_selected_item.get_all(
                secondary.model_name,
                secondary.selection_field,
                secondary.id,
                retrieve_relations=True)

            return serialize({singularize(secondary.model_name):
                              secondary_item})
        elif all([primary_selected_item, secondary.model]):
            # user selected a nested model with primary key
            # (from the primary and the secondary models)
            # /users/user_1/roles -> all roles for this user
            relationships = primary_selected_item.get_all(
                secondary.model_name,
                retrieve_relations=True)
            return serialize({pluralize(secondary.model_name):
                              relationships})
        else:
            # user selected a single item (from the primary model)
            if primary_selected_item:
                return serialize({primary.model_name:
                                  primary_selected_item.to_dict()})
            else:
                raise HTTPException(msg.MODEL_DOES_NOT_EXIST.format(
                    model=primary.model_name), 404)
    except (DoesNotExist, AttributeError) as e:
        self.__log.exception(e)
        raise HTTPException(msg.ITEM_DOES_NOT_EXIST, 404)