当前位置: 首页>>代码示例>>Python>>正文


Python inflection.pluralize方法代码示例

本文整理汇总了Python中inflection.pluralize方法的典型用法代码示例。如果您正苦于以下问题:Python inflection.pluralize方法的具体用法?Python inflection.pluralize怎么用?Python inflection.pluralize使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在inflection的用法示例。


在下文中一共展示了inflection.pluralize方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: get_resource_type_from_included_serializer

# 需要导入模块: import inflection [as 别名]
# 或者: from inflection import pluralize [as 别名]
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 
开发者ID:django-json-api,项目名称:django-rest-framework-json-api,代码行数:22,代码来源:relations.py

示例2: get_context

# 需要导入模块: import inflection [as 别名]
# 或者: from inflection import pluralize [as 别名]
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
    } 
开发者ID:AltSchool,项目名称:dynamic-rest,代码行数:18,代码来源:context.py

示例3: prepare_relationship

# 需要导入模块: import inflection [as 别名]
# 或者: from inflection import pluralize [as 别名]
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) 
开发者ID:ramses-tech,项目名称:ramses,代码行数:26,代码来源:models.py

示例4: get_profane_words

# 需要导入模块: import inflection [as 别名]
# 或者: from inflection import pluralize [as 别名]
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 
开发者ID:areebbeigh,项目名称:profanityfilter,代码行数:21,代码来源:profanityfilter.py

示例5: format_resource_type

# 需要导入模块: import inflection [as 别名]
# 或者: from inflection import pluralize [as 别名]
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 
开发者ID:django-json-api,项目名称:django-rest-framework-json-api,代码行数:14,代码来源:utils.py

示例6: get_plural_name

# 需要导入模块: import inflection [as 别名]
# 或者: from inflection import pluralize [as 别名]
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 
开发者ID:AltSchool,项目名称:dynamic-rest,代码行数:16,代码来源:serializers.py

示例7: __tablename__

# 需要导入模块: import inflection [as 别名]
# 或者: from inflection import pluralize [as 别名]
def __tablename__(cls):
        return inflection.pluralize(inflection.underscore(cls.__name__)) 
开发者ID:instacart,项目名称:lore,代码行数:4,代码来源:__init__.py

示例8: _get_entity_ids

# 需要导入模块: import inflection [as 别名]
# 或者: from inflection import pluralize [as 别名]
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.
# ----------------------------------------------------------------------------- 
开发者ID:SatelliteQE,项目名称:nailgun,代码行数:38,代码来源:entity_mixins.py

示例9: _camelize

# 需要导入模块: import inflection [as 别名]
# 或者: from inflection import pluralize [as 别名]
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 
开发者ID:klavinslab,项目名称:benchling-api,代码行数:16,代码来源:base.py

示例10: get_resource_name

# 需要导入模块: import inflection [as 别名]
# 或者: from inflection import pluralize [as 别名]
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 
开发者ID:django-json-api,项目名称:django-rest-framework-json-api,代码行数:46,代码来源:utils.py

示例11: _generate_template

# 需要导入模块: import inflection [as 别名]
# 或者: from inflection import pluralize [as 别名]
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) 
开发者ID:instacart,项目名称:lore,代码行数:44,代码来源:__main__.py

示例12: index

# 需要导入模块: import inflection [as 别名]
# 或者: from inflection import pluralize [as 别名]
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) 
开发者ID:mostafa,项目名称:grest,代码行数:60,代码来源:index.py

示例13: get

# 需要导入模块: import inflection [as 别名]
# 或者: from inflection import pluralize [as 别名]
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) 
开发者ID:mostafa,项目名称:grest,代码行数:54,代码来源:get.py


注:本文中的inflection.pluralize方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。