本文整理汇总了Python中models.Post.slug方法的典型用法代码示例。如果您正苦于以下问题:Python Post.slug方法的具体用法?Python Post.slug怎么用?Python Post.slug使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类models.Post
的用法示例。
在下文中一共展示了Post.slug方法的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: upload_file_combined
# 需要导入模块: from models import Post [as 别名]
# 或者: from models.Post import slug [as 别名]
def upload_file_combined():
form = UploadForm()
if request.method == 'POST':
file = request.files['file']
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
hash = hashlib.md5()
hash.update(filename);
global counter
new_filename = str(hash.hexdigest()[14:]) + '_' + str(random.random()*100) + str(counter)
hash.update(new_filename)
counter = counter + 1
filename = hash.hexdigest()[20:] + '_' + filename
hashstring = str(hash.hexdigest()[20:])
path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
print path
file.save(path)
url = url_for('uploaded_file', filename=filename)
post = Post()
post.title = form.title.data
post.slug = hashstring
post.geoLong = form.geoLong.data
post.geoLat = form.geoLat.data
post.image_url = url
post.save()
return redirect("/all-list")
示例2: u_create
# 需要导入模块: from models import Post [as 别名]
# 或者: from models.Post import slug [as 别名]
def u_create(username):
user = current_user
post = Post(created_timestamp=datetime.utcnow(), author=user)
db.session.add(post)
db.session.commit()
# Concats random integers together (starting from 6 of them)
# till we find a valid slug
length = 6
gen = lambda: (yield str(int(random.SystemRandom(1).random()*10)))
slug = ''.join(gen().next() for _ in range(length))
while length <= 128: # Slug has a max length of 128
if not user.posts.filter_by(slug=slug).first():
break
slug = slug + gen().next()
length = length + 1
else:
db.session.delete(post)
db.session.commit()
abort(500) # Probability ~0
post.slug = slug
db.session.add(post)
db.session.commit()
return redirect(url_for('.u_slug', username=username, slug=slug))
示例3: add_initial_data
# 需要导入模块: from models import Post [as 别名]
# 或者: from models.Post import slug [as 别名]
def add_initial_data():
"""Insert initial data into the database"""
# open database session
db_session = DB(db).get_session()
# ask user for an admin username and password
username = raw_input('Please enter the admin username: ')
password = getpass.getpass(prompt='Please enter the admin password: ')
# add user to database
u = User(username, encrypt_password(app.config['SECRET_KEY'], password))
db_session.add(u)
# create statuses
s1 = Status('draft')
s2 = Status('private')
s3 = Status('public')
db_session.add(s1)
db_session.add(s2)
db_session.add(s3)
# create formats
f = Format('rest')
f2 = Format('markdown')
db_session.add(f)
db_session.add(f2)
# Tags
t1 = Tag('imposter')
t2 = Tag('weblog')
# build initial post and put it in the database
initial_post_summary = """
Installed Correctly!
"""
initial_post_content = """
Imposter was installed correctly!
This is just a sample post to show Imposter works.
**Have a lot of fun blogging!**
"""
p1 = Post('Welcome to Imposter!', initial_post_summary, initial_post_content)
p1.slug = slugify(p1.title)
p1.createdate = datetime.now()
p1.lastmoddate = datetime.now()
p1.pubdate = datetime.now()
p1.format = f
p1.status = s3
p1.user = u
p1.tags = [t1, t2]
p1.compile()
db_session.add(p1)
db_session.commit()
示例4: create
# 需要导入模块: from models import Post [as 别名]
# 或者: from models.Post import slug [as 别名]
def create():
post = Post()
post.title = request.args.get('title', '')
post.slug = request.args.get('slug', '')
post.geoLong = request.args.get('geoLong', '')
post.geoLat = request.args.get('geoLat', '')
post.image_url = request.args.get('image_url', '')
post.save()
data = {
"response" : "Success",
}
return jsonify(data)
示例5: new_post
# 需要导入模块: from models import Post [as 别名]
# 或者: from models.Post import slug [as 别名]
def new_post():
if not g.site.domain == g.user:
abort(403)
p = Post()
if request.method == "POST":
reqfile = request.files.get("file")
if reqfile:
f = File()
f.site = g.site.domain
f.name = reqfile.filename
f.content_type = reqfile.mimetype
f.slug, f.content_length = save_file(reqfile, blog.config["UPLOAD_FOLDER"])
f.save()
import datetime
p.site = g.site.domain
p.name = request.form.get("name")
p.created = datetime.datetime.utcnow()
p.year = p.created.year
p.month = p.created.month
p.day = p.created.day
slugs = [
__j.slug
for __j in Post.objects.filter(site=g.site.domain, year=p.year, month=p.month, day=p.day, slug=p.slug)
]
counter = 1
slug = slugify(p.name)
__slug = slug
while __slug in slugs:
counter += 1
__slug = "%s_%d" % (slug, counter)
p.slug = __slug
p.text = request.form.get("text")
if reqfile:
p.image_slug = f.slug
p.save()
return redirect(url_for("post", year=p.year, month=p.month, day=p.day, slug=p.slug))
return render_template("edit_post.html", post=p)
示例6: post
# 需要导入模块: from models import Post [as 别名]
# 或者: from models.Post import slug [as 别名]
def post(self):
"""
Create new post
"""
json = {}
if not self.current_user:
json = {
'error': 1,
'msg': self._('Access denied')
}
self.write(json)
return
type = self.get_argument('type', Post.TYPE_POST)
title = self.get_argument('title', None)
content = self.get_argument('content', '')
slug = self.get_argument('slug', None)
format = self.get_argument('format', 'standard')
excerpt = self.get_argument('excerpt', '')
thumbnail = self.get_argument('thumbnail', '')
category_id = self.get_argument('category', None)
tags = self.get_argument('tags', '')
date = self.get_argument('date', None)
comment_open = bool(int(self.get_argument('comment_open', '1')))
if type not in [Post.TYPE_POST, Post.TYPE_PAGE]:
type = Post.TYPE_POST
if format not in ['standard', 'aside', 'gallery', 'link', 'image', 'quote', 'status', 'video', 'audio', 'chat']:
format = 'standard'
# valid arguments
if not slug:
json = {
'error': 1,
'msg': self._('Slug field can not be empty')
}
self.write(json)
return
elif self.get_post_by_slug(slug):
json = {
'error': 1,
'msg': self._('Slug already exists')
}
self.write(json)
return
if type == Post.TYPE_POST and not category_id:
json = {
'error': 1,
'msg': self._('Category field can not be empty')
}
self.write(json)
return
if type == Post.TYPE_POST:
category = self.get_category_by_id(category_id)
if not category:
json = {
'error': 1,
'msg': self._('No such category')
}
self.write(json)
return
if date:
if validators.date(date):
date = datetime.strptime(date, '%Y-%m-%d')
elif validators.datetime(date):
date = datetime.strptime(date, '%Y-%m-%d %H:%M:%S')
else:
date = datetime.utcnow()
else:
date = datetime.utcnow()
# now create post
post = Post()
post.type = type
post.created = date
post.title = title
post.slug = slug
post.content = content
post.html = wrap_content(content)
post.format = format
post.excerpt = excerpt
post.thumbnail = thumbnail
post.comment_open = comment_open
if type == Post.TYPE_POST:
post.category_id = category.id
else:
post.category_id = 1 # default category
# update category post count
if type == Post.TYPE_POST:
category.post_count += 1
self.db.add(category)
# commit
self.db.add(post)
self.db.commit()
# create tags
if type == Post.TYPE_POST and tags:
post.tag_ids = self.create_tags(tags.split(','), post.id)
self.db.add(post)
self.db.commit()
# delete cache
keys = ['PostList:1', 'CategoryPostList:%s:1' %
category.id, 'SystemStatus', 'ArchiveHTML', 'TagCloud']
self.cache.delete_multi(keys)
#.........这里部分代码省略.........
示例7: save_post
# 需要导入模块: from models import Post [as 别名]
# 或者: from models.Post import slug [as 别名]
def save_post():
try:
# print "RECEBIDO", request.form
title = request.form['title']
content = request.form['content']
featured = 'N'
if "featured" in request.form:
featured = 'Y'
#Limpa o cache para atualizar na proxima chamada da capa.
#cache.delete("featured_posts")
print "FEATURED POST"
resume = request.form['resume']
slug = request.form['slug']
tags = request.form['tags']
add = False
if 'id' in request.form:
post = Post.query.get(request.form['id'])
cache.delete('view-post-%s' % slug) #Remove this post from cache for update in next view
else:
add = True
post = Post()
post.date_created = datetime.today()
post.short_url = util.encurtar(url_for('blog.view_post', slug=slug))
post.title = title
post.content = content
post.resume = resume
post.featured = featured
post.slug = slug
post.date_updated = datetime.today()
#post.picture = '' #don't clear this field if edit
post.tags = tags
try:
global uploaded_files
photo = request.files.get('postfile')
if photo:
print "SALVANDO A IMAGEM DO POST"
filename = uploaded_files.save(photo)
post.picture = uploaded_files.path(filename)
post.picture_url = uploaded_files.url(filename)
#print 'UPLOADED:', uploaded_files.path(filename)
#Gerar um thumbnail para mostrar dentro do post
#200x150 - Dentro do post
#220x100 - Lista de posts
else:
print "POST SEM IMAGEM"
except UploadNotAllowed:
flash("The upload was not allowed")
if add:
db.session.add(post)
else:
db.session.merge(post)
db.session.commit()
# flash('Post salvo com sucesso')
# return redirect(url_for('blog.view_post', slug=slug))
data = {}
data['message'] = "Post salvo com sucesso! <a href='%s'>Visualizar</a>" % url_for('blog.view_post', slug=slug)
data['id'] = post.id
return jsonify(data)
except IntegrityError as e:
db.session.rollback()
data = {}
data['message'] = "O Slug informado ja existe. Altere e tente novamente."
return jsonify(data)
except:
db.session.rollback()
print "Unexpected error:", sys.exc_info()[0]
raise
示例8: save_post
# 需要导入模块: from models import Post [as 别名]
# 或者: from models.Post import slug [as 别名]
def save_post(post_id=None):
"""Save Post to database
If post_id is None a new Post will be inserted in the database. Otherwise
the existing Post will be updated.
"""
message = 'Post updated'
orig_tags = []
post_form = PostForm(request.form)
if not post_form.validate():
flash('ERROR: errors detected. Post NOT saved!', category='error')
return edit_post(post_id=post_id, post_form=post_form)
# test if we're creating a new post, or updating an existing one
if post_id is None:
post = Post()
post.status_id = 1
post.user_id = session['user_id']
post.createdate = datetime.now()
else:
post = get_post(post_id)
orig_tags = [tag for tag in post.tags]
post_form.populate_obj(post)
post.lastmoddate = datetime.now()
# compile input to html
post.compile(app.config['REPL_TAGS'])
# update pubdate if post's pubdate is None and its status is set
# to public
if request.form['status'] == 'public' and \
unicode(post.status) != 'public' and \
post.pubdate is None:
post.pubdate = datetime.now()
post.status = get_status(request.form['status'])
if post.slug is None:
post.slug = slugify(post.title)
if post_id is None:
db_session.add(post)
message = 'New post was successfully added'
db_session.commit()
for tag in orig_tags:
recalculate_tagcount(tag)
for tag in post.tags:
if tag not in orig_tags:
recalculate_tagcount(tag)
db_session.commit()
flash(message, category='info')
return redirect(url_for('edit_post', post_id=post.id))