本文整理汇总了Python中pytils.translit.slugify函数的典型用法代码示例。如果您正苦于以下问题:Python slugify函数的具体用法?Python slugify怎么用?Python slugify使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了slugify函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: resize
def resize(self, width, height, dowatermark=False):
"""
Создает превьюхи для изображений
"""
dimensions_folder = '{0}x{1}'.format(width, height)
#проверяем, что существует папка с превьюхами
path_to_thumbnail_dir = os.path.join(
settings.MEDIA_ROOT, self.IMAGE_UPLOAD_TO, 'thumbnails', dimensions_folder).encode('utf-8')
if not os.path.exists(path_to_thumbnail_dir):
os.makedirs(path_to_thumbnail_dir)
original_path = os.path.join(settings.MEDIA_ROOT, self.IMAGE_UPLOAD_TO)
original_filename = '{0}/{1}.jpg'.format(original_path, slugify(self.article)).encode('utf-8')
try:
image = Image.open(original_filename)
except IOError:
# print('Image not found')
return
image = ImageOps.fit(image, (width, height), Image.ANTIALIAS)
if dowatermark:
wm = Image.open(settings.WATERMARK_PATH)
wmsize = image.size[0]/2
if wmsize < 100:
wmsize = 100
wm.thumbnail((wmsize, wmsize), Image.ANTIALIAS)
image.paste(wm, (image.size[0]/2-wm.size[0]/2, image.size[1]/2-wm.size[1]/2), wm)
path_to_thumbnail = '{0}/{1}.jpg'.format(path_to_thumbnail_dir, slugify(self.article)).encode('utf-8')
image.save(path_to_thumbnail, "JPEG", quality=100)
开发者ID:migunow,项目名称:erofeimarkov,代码行数:28,代码来源:models.py
示例2: forwards
def forwards(self, orm):
from pytils.translit import slugify
for section in orm.Section.objects.all():
section.slug = slugify(section.title_uk or section.title)
section.save()
for article in orm.Article.objects.all():
article.slug = slugify(article.title_uk or article.title)
article.save()
开发者ID:vasyabigi,项目名称:fmf,代码行数:9,代码来源:0006_add_slugs_to_sections_and_articles.py
示例3: file_upload_path
def file_upload_path(instance, filename):
"""Generates upload path
Keyword arguments:
instance -- FileField
filename - String
Returns: String
"""
parts = filename.rsplit('.', 1)
name = "%s.%s" % (slugify(translify(parts[0])), slugify(translify(parts[1])))
return "%s/%s/%s/%s" % (strftime('%Y'),
strftime('%m'), strftime('%d'), name)
开发者ID:ChristosChristofidis,项目名称:djang0byte,代码行数:14,代码来源:utils.py
示例4: save
def save(self, force_insert=False, force_update=False):
self.updated_at = datetime.now()
if (self.slug == None or self.slug == ''):
if not self.id:
super(Post, self).save(force_insert, force_update)
self.slug = '%d-%s' % (self.id, slugify(self.title))
super(Post, self).save(force_insert, force_update)
开发者ID:ryates,项目名称:django-blogs,代码行数:7,代码来源:models.py
示例5: save
def save(self, commit=True):
post = super(PostAdminForm, self).save(commit=False)
post.slug = '%i-%s' % (
Post.objects.last().pk+1, slugify(self.cleaned_data['title'])
)
post.save()
return post
开发者ID:SlavaAf,项目名称:partcom,代码行数:7,代码来源:admin.py
示例6: unique_path
def unique_path(page, page_id=None):
"""Makes unique_path for page, returns new path and slug.
Provided @page_id means do not check against self"""
slug = slugify(page.slug or page.name)[0:PAGE_SLUG_LENGTH]
parent_page = db.select("pages", page, where="id=$parent_id")[0]
test_slug, i = slug, 1
try:
while True:
if not test_slug in config.reserved:
new_path = join_path(parent_page.path, test_slug)
test = db.select(
"pages",
locals(),
where=("path=$new_path" +
web.cond(page_id, " AND NOT id=$page_id", "")),
)[0]
test_slug = "%s-%d" % (slug, i)
i += 1
except IndexError:
# Page with test_slug doesn't exist — take this slug
if parent_page.ids:
ids = parent_page.ids + "," + str(parent_page.id)
else:
ids = parent_page.id
return dict(
path=new_path,
slug=test_slug,
ids=ids,
level=parent_page.level + 1)
开发者ID:w0rm,项目名称:pre-stonegarden-dev,代码行数:29,代码来源:pages.py
示例7: set_slug
def set_slug(model, src, length=60):
slug = slugify(src)[0:length]
try:
obj = model.objects.get(slug=slug)
slug = set_slug(model, slug, length)
except model.DoesNotExist:
return slug
开发者ID:Haikson,项目名称:virtenviro-news,代码行数:7,代码来源:models.py
示例8: save
def save(self, **kwargs):
#super(Coll, self).save()
if not self.slug:
self.uid = Rubrica.objects.latest('pk').id + 1
self.slug = dict(GENDER).get(self.gender) + "-" + translit.slugify(self.title)
super(Rubrica, self).save(**kwargs)
开发者ID:avkozlov,项目名称:vitrinaburg,代码行数:7,代码来源:models.py
示例9: on_callback
def on_callback(self, request):
if request.method != 'POST':
request.respond('This hook only supports POST method.')
else:
if request.GET.get('secret', [None])[0] != self.bot.config.draftin_secret:
request.respond('Wrong secret was specified')
else:
payload = anyjson.deserialize(request.POST['payload'][0])
title = payload['name']
content = payload['content']
slug = slugify(title)
created_at = times.to_universal(payload['created_at'])
updated_at = times.to_universal(payload['updated_at'])
timezone = self.bot.config.timezone
with open(os.path.join(
self.bot.config.documents_dir,
slug + '.md'), 'w') as f:
post_content = self.template.format(title=title,
content=content,
slug=slug,
created_at=times.format(created_at, timezone, '%Y-%m-%d %H:%M'),
updated_at=times.format(updated_at, timezone, '%Y-%m-%d %H:%M'))
f.write(post_content.encode('utf-8'))
try:
subprocess.check_output(self.bot.config.update_command,
stderr=subprocess.STDOUT,
shell=True)
except subprocess.CalledProcessError, e:
request.respond(u'I tried to update a blog, but there was an error: ' + e.output.encode('utf-8'))
else:
request.respond('Done, published')
开发者ID:svetlyak40wt,项目名称:thebot-draftin,代码行数:34,代码来源:thebot_draftin.py
示例10: attach_images
def attach_images(filename):
dirname = os.path.join(settings.MEDIA_ROOT, Item.IMAGE_UPLOAD_TO).encode('utf-8')
articles = list()
with zipfile.ZipFile(filename, "r") as f:
for name in f.namelist():
try:
if type(name) is str:
unicode_name = name.decode('UTF-8')
else:
unicode_name = name
except UnicodeDecodeError:
unicode_name = name.decode('cp866')
unicode_name = unicode_name.split('.')[:-1]
unicode_name = '.'.join(unicode_name)
articles.append(unicode_name)
unicode_name = slugify(unicode_name) + '.jpg'
unicode_name = unicode_name.encode('utf-8')
file_name = os.path.join(dirname, unicode_name)
f2 = open(file_name, 'w')
f2.write(f.read(name))
f2.close()
f.close()
items = Item.objects.filter(article__in=articles)
for item in items:
item.resize_all()
开发者ID:migunow,项目名称:erofeimarkov,代码行数:27,代码来源:load_csv.py
示例11: photo_file_path
def photo_file_path(instance, filename):
"""
Path is <kind>/<media_id/digits>/file_name
"""
name, ext = os.path.splitext(filename)
kind, media_id = instance.get_path_parts()
return os.path.join(kind, os.path.join(*list(str(media_id))), translit.slugify(name)) + ext
开发者ID:KopBob,项目名称:Textum,代码行数:7,代码来源:models.py
示例12: setSlug
def setSlug(self, names, obj):
"""
Find slug field and set it
Return generated slug or None is slug not exists
"""
# get obj type
fields = self.meta.getCollType(names)
if not fields:
return None
# search slug field name
slugName = None
for name, params in fields.items():
if 'slug' in params:
slugName = name
break
if not slugName:
return None
# get slug src
slugSrc = fields[slugName]['slug']
# gen slug from src
src = obj.get(slugSrc, None)
if not src:
return None
slug = slugify(src)
# set slug
obj[slugName] = slug
return slug
开发者ID:hzx,项目名称:wender,代码行数:32,代码来源:orm.py
示例13: updateSlug
def updateSlug(self, names, field, value):
# get coll type
fields = self.meta.getCollType(names)
if not fields:
return None
# search slug field name
slugName = None
for name, params in fields.items():
if 'slug' in params:
slugName = name
break
if not slugName:
return None
# get slug src
slugSrc = fields[slugName]['slug']
# slug src must be equal to field
if slugSrc != field:
return None
# gen slug
slug = slugify(value)
return [slugName, slug]
开发者ID:hzx,项目名称:wender,代码行数:26,代码来源:orm.py
示例14: slugify
def slugify(text):
"""Make slug from (russian) text"""
try:
res = translit.slugify(smart_unicode(text, encoding))
except Exception, err:
# because filter must die silently
res = default_value % {'error': err, 'value': text}
开发者ID:AndreyBalychev,项目名称:pytils,代码行数:7,代码来源:pytils_translit.py
示例15: save
def save(self, *args, **kwargs):
self.html_compile = u'%s' % markdown(self.data,
['footnotes', 'admonition', 'headerid', 'nl2br', 'tables', 'wikilinks', 'pyshell'])
self.updated = datetime.now()
if not self.slug:
self.slug = slugify(self.title)
super(Page, self).save(*args, **kwargs)
开发者ID:vadosl,项目名称:vitalvas.com,代码行数:7,代码来源:models.py
示例16: save
def save(self, *args, **kwargs):
if not self.slug :
from pytils.translit import slugify
self.slug = slugify(self.title)
super(News, self).save(*args, **kwargs)
开发者ID:dkoldyaev,项目名称:basis.ru,代码行数:7,代码来源:models.py
示例17: fieldset_dict
def fieldset_dict(self):
# No need to call validate_fieldsets() since we
# are using iter_fieldsets.
if not hasattr(self, '__fieldset_dict'):
self.__fieldset_dict = dict((slugify(fset.title), fset) for \
fset in self.iter_fieldsets())
return self.__fieldset_dict
开发者ID:Anber,项目名称:django-formfieldset,代码行数:7,代码来源:forms.py
示例18: save
def save(self, *args, **kwargs):
if not self.slug:
from pytils.translit import slugify
self.slug = slugify(self.name)
self.text = self.text.strip()
self.html = render(self.text, self.render_method, unsafe=True)
super(Post, self).save(*args, **kwargs)
开发者ID:exezaid,项目名称:Dpress,代码行数:7,代码来源:models.py
示例19: check_for_file_and_upload
def check_for_file_and_upload(self, data):
"""
Checks to see if a file was passed back by the student. If so, it will be uploaded to S3.
@param data: AJAX post dictionary containing keys student_file and valid_files_attached.
@return: has_file_to_upload, whether or not a file was in the data dictionary,
and image_tag, the html needed to create a link to the uploaded file.
"""
has_file_to_upload = False
image_tag = ""
# Ensure that a valid file was uploaded.
if ('valid_files_attached' in data
and data['valid_files_attached'] in ['true', '1', True]
and data['student_file'] is not None
and len(data['student_file']) > 0):
has_file_to_upload = True
student_file = data['student_file'][0]
# Bad workaround about cyrillic unicode
# student_file.name = str(uuid.uuid4()) + '.' + student_file.name.split(".")[-1]
student_file.name = slugify(student_file.name)
# Upload the file to S3 and generate html to embed a link.
s3_public_url = self.upload_file_to_s3(student_file)
image_tag = self.generate_file_link_html_from_url(s3_public_url, student_file.name)
return has_file_to_upload, image_tag
开发者ID:smartdec,项目名称:edx-platform,代码行数:25,代码来源:openendedchild.py
示例20: upload
def upload(request):
"""
Uploads a file and send back its URL to CKEditor.
TODO:
Validate uploads
"""
# Get the uploaded file from request.
f_name = request.FILES['upload'].name.split('.')
request.FILES['upload'].name = slugify(f_name[0])+'.'+f_name[1]
upload = request.FILES['upload']
upload_ext = os.path.splitext(upload.name)[1]
if upload.size > 5242880:
return render(request, 'accounts/ckeditor_error.html')
# Open output file in which to store upload.
upload_filename = get_upload_filename(upload.name, request.user)
out = open(upload_filename, 'wb+')
# Iterate through chunks and write to destination.
for chunk in upload.chunks():
out.write(chunk)
out.close()
create_thumbnail(upload_filename)
# Respond with Javascript sending ckeditor upload url.
url = get_media_url(upload_filename)
return HttpResponse("""
<script type='text/javascript'>
window.parent.CKEDITOR.tools.callFunction(%s, '%s');
</script>""" % (request.GET['CKEditorFuncNum'], url))
开发者ID:SlavaAf,项目名称:partcom,代码行数:31,代码来源:views.py
注:本文中的pytils.translit.slugify函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论