init_categories.py 文件源码

python
阅读 19 收藏 0 点赞 0 评论 0

项目:OilLibrary 作者: NOAA-ORR-ERD 项目源码 文件源码
def get_category_by_name(session, name):
    '''
        Get the category matching a name.
        - Category name can be a simple name, or a full path to a category
          inside the Category hierarchy.
        - A full path consists of a sequence of category names separated by
          '->' e.g. 'Refined->Gasoline'
    '''
    full_path = name.split('->')
    if len(full_path) > 1:
        # traverse the path
        try:
            cat_obj = (session.query(Category)
                       .filter(Category.name == full_path[0])
                       .filter(Category.parent == None)
                       .one())

            for cat_name in full_path[1:]:
                matching_catlist = [c for c in cat_obj.children
                                    if c.name == cat_name]

                if len(matching_catlist) > 1:
                    raise MultipleResultsFound('One matching child Category '
                                               'required, found {} categories '
                                               'matching the name {}'
                                               .format(len(matching_catlist),
                                                       cat_name))
                elif len(matching_catlist) == 0:
                    raise NoResultFound('child Category matching the name {} '
                                        'not found'
                                        .format(cat_name))

                cat_obj = matching_catlist[0]
        except Exception:
            cat_obj = None
    else:
        # just a simple name
        try:
            cat_obj = (session.query(Category)
                       .filter(Category.name == name).one())
        except Exception:
            cat_obj = None

    return cat_obj
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号