• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python util.slugify函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中util.slugify函数的典型用法代码示例。如果您正苦于以下问题:Python slugify函数的具体用法?Python slugify怎么用?Python slugify使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



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

示例1: generate_usable_slug

def generate_usable_slug(recipe):
    """
    Generate a usable slug for a given recipe. This method will try to slugify
    the recipe name and then append an integer if needed, increasing this
    integer until no existing recipe would be overwritten.
    """
    slug = slugify(recipe.name)

    # Reuse existing slug if we can
    if recipe.slug and recipe.slug == slug:
        return recipe.slug

    append = 0
    while True:
        count = Recipe.all()\
                      .filter('owner =', recipe.owner)\
                      .filter('slug =', slug)\
                      .count()

        if not count:
            break

        append += 1
        slug = slugify(recipe.name) + str(append)

    return slug
开发者ID:danielgtaylor,项目名称:malt.io,代码行数:26,代码来源:recipes.py


示例2: generate_usable_slug

def generate_usable_slug(brew):
    """
    Generate a usable slug for a given brew. This method will try to slugify
    the brew date + owner and then append an integer if needed, increasing this
    integer until no existing brew would be overwritten.
    """
    base = brew.started.strftime('%d-%b-%Y') + '-' + brew.owner.name
    slug = slugify(base)

    # Reuse existing slug if we can
    if brew.slug and brew.slug == slug:
        return brew.slug

    append = 0
    while True:
        count = Brew.all()\
                    .filter('owner =', brew.owner)\
                    .filter('recipe =', brew.recipe)\
                    .filter('slug =', slug)\
                    .count()

        if not count:
            break

        append += 1
        slug = slugify(base) + str(append)

    return slug
开发者ID:adamrumbold,项目名称:malt.io,代码行数:28,代码来源:brew.py


示例3: _smart

def _smart(url, tries):
    # let's get the content of the page
    soup = BeautifulSoup(urllib2.urlopen(url))

    # we want to build a short with the page title
    if soup.title is None:
        return _random(url)

    title = soup.title.string
    if title is None:
        return _random(url)

    words = [word.lower() for word in
                [word.strip() for word in title.split()]
                if len(word) > 4 and word[0] != '&']

    # that works for Sphinx :)
    if len(words) > 1:
        short = words[0] + '-' + words[1]
    elif len(words) == 1:
        short = words[0]
    else:
        return _random(url)

    if tries > 0:
        short += '-' + str(tries)

    return slugify(short)
开发者ID:faitmain,项目名称:short.faitmain.org,代码行数:28,代码来源:db.py


示例4: __init__

    def __init__(self, module_path):
        self.module_path = module_path
        self.filename    = filename = os.path.basename(module_path)

        module_name = filename.split('.')[0].lstrip('_01234567890')

        imp_desc  = ('', 'r', imp.PY_SOURCE)
        with open(module_path) as module_file:
            self.module     = imp.load_module(module_name, module_file, module_path, imp_desc)
            module_file.seek(0)
            self.module_src = module_file.read()

        self.title    = self.module.title
        self.author   = self.module.author # TODO: settings.AUTHORS lookup
        self.tags     = getattr(self.module,'tags',())
        self.is_draft = getattr(self.module,'draft',False)
        self.pub_date = datetime.datetime(*self.module.pub_date)

        updated = getattr(self.module, 'updated', self.pub_date)
        self.updated  = updated or datetime.datetime(*updated)

        try:
            self.id = int(getattr(self.module, int_id_name, None))
        except ValueError:
            raise ValueError('Internal IDs should be integers.'+str(file_path))
        
        self.slug     = slugify(unicode(self.title))

        self.parts    = get_parts(self.module_src)

        self.run_examples()
开发者ID:mahmoud,项目名称:PythonDoesBlog,代码行数:31,代码来源:post.py


示例5: handle_error

def handle_error(e):
    if not e:
        e = {}
    else:
        logging.exception(e)

    try:
        e.code
    except AttributeError:
        e.code = 500
        e.name = e.description = 'Internal Server Error'
    result = {
        'status': 'error',
        'error_code': e.code,
        'error_name': util.slugify(e.name),
        'error_message': e.name,
        'error_class': e.__class__.__name__,
        'description': e.description,
        'data': None,
        'validations': None
    }
    if hasattr(e, 'data'):
        result['data'] = e.data
    if hasattr(e, 'validations'):
        result['validations'] = e.validations
    return util.jsonpify(result), e.code
开发者ID:tiberiucorbu,项目名称:av-website,代码行数:26,代码来源:helpers.py


示例6: clone_infra

def clone_infra(plan, environment, name, team, project, description, task=None, clone=None):
    if not plan.provider == plan.CLOUDSTACK:
        dbinfra = DatabaseInfra.best_for(
            plan=plan, environment=environment, name=name)

        if dbinfra:
            database = Database.provision(databaseinfra=dbinfra, name=name)
            database.team = team
            database.description = description
            database.project = project
            database.save()

            return build_dict(databaseinfra=dbinfra, database=database, created=True)

        return build_dict(databaseinfra=None, created=False)

    workflow_dict = build_dict(name=slugify(name),
                               plan=plan,
                               environment=environment,
                               steps=get_clone_settings(plan.engine_type.name),
                               qt=get_vm_qt(plan=plan, ),
                               dbtype=str(plan.engine_type),
                               team=team,
                               project=project,
                               description=description,
                               clone=clone
                               )

    start_workflow(workflow_dict=workflow_dict, task=task)
    return workflow_dict
开发者ID:flaviohenriqu,项目名称:database-as-a-service,代码行数:30,代码来源:providers.py


示例7: error_handler

def error_handler(e):
    logging.exception(e)
    try:
        e.code
    except AttributeError:
        e.code = 500
        e.name = "Internal Server Error"

    if flask.request.path.startswith("/_s/"):
        return (
            util.jsonpify(
                {
                    "status": "error",
                    "error_code": e.code,
                    "error_name": util.slugify(e.name),
                    "error_message": e.name,
                    "error_class": e.__class__.__name__,
                }
            ),
            e.code,
        )

    return (
        flask.render_template(
            "error.html", title="Error %d (%s)!!1" % (e.code, e.name), html_class="error-page", error=e
        ),
        e.code,
    )
开发者ID:JackNova,项目名称:gae-init,代码行数:28,代码来源:main.py


示例8: clean

    def clean(self):
        #slugify name
        if not self.pk:
            # new database
            self.name = slugify(self.name)

        if self.name in self.__get_database_reserved_names():
            raise ValidationError(_("%s is a reserved database name" % self.name))
开发者ID:tuxmonteiro,项目名称:database-as-a-service,代码行数:8,代码来源:models.py


示例9: render_author_pages

 def render_author_pages(self):
     author_dict = self.author_dict
     for author, posts in author_dict.items():
         author_slug = slugify(unicode(author))
         with open(os.path.join(OUTPUT_DIR, 'author', author_slug+'.html'), 'w') as a_file:
             a_file.write(render_to('post_list.html', 
                                    posts=posts, 
                                    list_desc="Posts by "+author+""))
开发者ID:mahmoud,项目名称:PythonDoesBlog,代码行数:8,代码来源:blog.py


示例10: _build_globo

 def _build_globo(self, channel=None):
     categories, shows = scraper.get_globo_shows()
     data = { 'globo': {} }
     for cat, show_list in zip(categories, shows):
         slug = util.slugify(cat)
         data['globo'].update({slug: (cat, None)})
         data[slug] = show_list
     return data
开发者ID:TonyPh12345,项目名称:kodibrasilforum,代码行数:8,代码来源:globo.py


示例11: __init__

 def __init__(self, index, display, interface, change=2, data_rate=64):
     self.index = index
     self.display = display
     self.id = util.slugify(display)
     self.change = change
     self.data_rate = data_rate
     self.interface = interface
     self.logger = util.get_logger("%s.%s" % (self.__module__, self.__class__.__name__))
开发者ID:entone,项目名称:Automaton,代码行数:8,代码来源:__init__.py


示例12: add_post

 def add_post(self, title, post, tags):
     url = slugify(title)
     self.collection.save(dict(title=title,
                               post=post,
                               tags=tags,
                               comments=[],
                               time=datetime.now(),
                               url=url)
     )
开发者ID:kkris,项目名称:refer,代码行数:9,代码来源:database.py


示例13: get_globo_shows

def get_globo_shows():
    soup = bs(get_page(GLOBOTV_MAIS_URL))
    content = soup.findAll('div', attrs={'class': re.compile('trilho-tag')})
    categories = [c.find('h2').text for c in content]
    shows = [dict([(util.slugify(img['alt']),
                    (img['alt'],
                     img['data-src'].replace(img['data-src'][7:img['data-src'].index('=/')+2], '')))
                    for img in c.findAll('img') if '=/' in img['data-src']])
             for c in content]
    return (categories, shows)
开发者ID:TonyPh12345,项目名称:kodibrasilforum,代码行数:10,代码来源:scraper.py


示例14: create_new_credential

 def create_new_credential(cls, user, database):
     credential = Credential()
     credential.database = database
     credential.user = user[:cls.USER_MAXIMUM_LENGTH_NAME]
     credential.user = slugify(credential.user)
     credential.password = make_db_random_password()
     credential.full_clean()
     credential.driver.create_user(credential)
     credential.save()
     return credential
开发者ID:flaviohenriqu,项目名称:database-as-a-service,代码行数:10,代码来源:models.py


示例15: clean

    def clean(self):
        if not self.pk:
            self.name = slugify(self.name)

        if self.name in self.__get_database_reserved_names():
            raise ValidationError(
                _("{} is a reserved database name".format(
                    self.name
                ))
            )
开发者ID:globocom,项目名称:database-as-a-service,代码行数:10,代码来源:models.py


示例16: database_pre_save

def database_pre_save(sender, **kwargs):
    database = kwargs.get('instance')

    #slugify name
    database.name = slugify(database.name)

    if database.id:
        saved_object = Database.objects.get(id=database.id)
        if database.name != saved_object.name:
            raise AttributeError(_("Attribute name cannot be edited"))
开发者ID:pombredanne,项目名称:database-as-a-service,代码行数:10,代码来源:models.py


示例17: render_tag_pages

    def render_tag_pages(self):
        tag_dict = self.tag_dict
        for tag, posts in tag_dict.items():
            tag_slug = slugify(unicode(tag))
            with open(os.path.join(OUTPUT_DIR, 'tag', tag_slug+'.html'), 'w') as t_file:
                t_file.write(render_to('post_list.html', 
                                       posts=posts, 
                                       list_desc="Posts tagged <em>"+tag+"</em>"))

        with open(os.path.join(OUTPUT_DIR, 'tag', 'tag_cloud.html'), 'w') as t_file:
            t_file.write(render_to('tag_cloud.html', tag_dict=tag_dict))
开发者ID:mahmoud,项目名称:PythonDoesBlog,代码行数:11,代码来源:blog.py


示例18: __remove_user

 def __remove_user(database):
     from logical.models import Credential
     from util import slugify
     credential = Credential()
     credential.database = database
     credential.user = 'u_{}'.format(database.name[:Credential.USER_MAXIMUM_LENGTH_NAME])
     credential.user = slugify(credential.user)
     try:
         credential.driver.remove_user(credential)
     except InvalidCredential:
         pass
开发者ID:globocom,项目名称:database-as-a-service,代码行数:11,代码来源:test_templatetag_capacity.py


示例19: get_premiere_live

def get_premiere_live(logo):
    #provider_id is hardcoded right now. 
    provider_id = '520142353f8adb4c90000008'
    live = dict([(util.slugify(json['time_mandante']['sigla'] + 'x' + json['time_visitante']['sigla']), {
                'name': json['time_mandante']['sigla'] + ' x ' + json['time_visitante']['sigla'],
                'logo': logo,
                'playable': True,
                'plot': json['campeonato'] + ': ' + json['time_mandante']['nome'] + ' x ' + json['time_visitante']['nome'] + ' (' + json['estadio'] + '). ' + json['data'],
                'id': json['id_midia'],
            }) for json in get_page(PREMIERE_LIVE_JSON % provider_id)['jogos']])
    return live
开发者ID:ffsi,项目名称:equanimous-octo-kumquat,代码行数:11,代码来源:scraper.py


示例20: __init__

 def __init__(self, *arg, **kwargs):
   self.name = util.slugify(kwargs.pop('name', 'my-camera'))
   self.directory = kwargs.pop('directory', path.dirname(path.realpath(__file__)))
   self.width = kwargs.pop('width', 640)
   self.height = kwargs.pop('height', 480)
   self.rotation = kwargs.pop('rotation', 0)
   self.init_camera()
   if self.is_working():
     util.print_out('CAMERA LOADED', self.full_name())
   else:
     util.print_out('CAMERA FAILD', self.full_name())
开发者ID:jmacko,项目名称:timelapse,代码行数:11,代码来源:pss-capture.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python util.start_MAVProxy_SIL函数代码示例发布时间:2022-05-26
下一篇:
Python util.slice_sample函数代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap