本文整理汇总了Python中models.Post类的典型用法代码示例。如果您正苦于以下问题:Python Post类的具体用法?Python Post怎么用?Python Post使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Post类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: single_post
def single_post(post_id):
"""Returns everything in a post as json"""
post_d = mongo.db.posts.find_one(post_id)
if post_d is None:
abort(404)
post = Post(bson=post_d)
return jsonify(**post.to_dict())
示例2: add_post
def add_post(request):
if request.method == "POST":
post_form = PostForm(request.POST, request.FILES)
if post_form.is_valid():
title = post_form.cleaned_data['title']
keywords = post_form.cleaned_data['keywords']
description = post_form.cleaned_data['description']
image = post_form.cleaned_data['image']
text = post_form.cleaned_data['text']
slug = title
new_post = Post(title=title,
userid=request.user,
slug=slug,
keywords=keywords,
image=image,
text=text,
description=description,
date=datetime.now())
new_post.save()
post_form = PostForm()
return render(request,
'blog/add_post.html',
{'post_form': post_form})
else:
post_form = PostForm()
ctx = {'post_form': post_form}
return render(request,
'blog/add_post.html',
ctx, )
示例3: sub_post
def sub_post(request, id_num): #for nested posts
pform = PostForm(request.POST or None)
parent = get_object_or_404(Post, pk=id_num)
if (request.method == 'POST'
and request.user.is_authenticated()):
if pform.is_valid():
title = pform.cleaned_data["title"]
check = Post.objects.filter(title=title).order_by("-identifier")
check_int = 0
if len(check) > 0:
check_int = check[0].identifier + 1
post = Post(title=title,
body=pform.cleaned_data["body"],
parent=parent,
user=request.user,
identifier=check_int)
post.save()
messages.success(request, "Post submitted correctly")
else:
### meaningful errors here would be helpful
### messages.error(request, pform.errors)
return render_to_response("post_form.html",
{'pform' : pform, 'post':parent},
RequestContext(request))
return HttpResponseRedirect("/posts/"+id_num)
示例4: test_get_nozomi_dialgs
def test_get_nozomi_dialgs(self):
d = feedparser.parse('tests/data/feed.xml')
entry_elem = d.entries[0]
post = Post(entry_elem)
self.assertMultiLineEqual(post.get_nozomi_dialogs()[0],
u'「原種・亜種と同じく飛び回ったり走り回ったりして追うのが大変なのに、希少種ときたら頭も硬いのが厄介ですよね」')
示例5: test_parse_post
def test_parse_post(self):
response = '''{"comments": {"can_post": 0, "count": 4},
"date": 1298365200,
"from_id": 55555,
"geo": {"coordinates": "55.6745689498 37.8724562529",
"place": {"city": "Moskovskaya oblast",
"country": "Russian Federation",
"title": "Shosseynaya ulitsa, Moskovskaya oblast"},
"type": "point"},
"id": 465,
"likes": {"can_like": 1, "can_publish": 1, "count": 10, "user_likes": 0},
"online": 1,
"post_source": {"type": "api"},
"reply_count": 0,
"reposts": {"count": 3, "user_reposted": 0},
"text": "qwerty",
"to_id": 201164356}
'''
instance = Post()
owner = UserFactory(remote_id=201164356) # Travis Djangov
author = UserFactory(remote_id=55555)
instance.parse(json.loads(response))
instance.save()
self.assertTrue(instance.remote_id.startswith('201164356_'))
self.assertEqual(instance.wall_owner, owner)
self.assertEqual(instance.author, author)
self.assertEqual(instance.reply_count, 0)
self.assertEqual(instance.likes, 10)
self.assertEqual(instance.reposts, 3)
self.assertEqual(instance.comments, 4)
self.assertEqual(instance.text, 'qwerty')
self.assertTrue(isinstance(instance.date, datetime))
示例6: get
def get(self):
page = helper.sanitizeHtml(self.request.get('pagina'))
perPage = 20
page = int(page) if page else 1
realPage = page - 1
if realPage > 0:
prevPage = realPage
if (page * perPage) < Post.get_cached_count():
nextPage = page + 1
session = get_current_session()
if session.has_key('user'):
user = session['user']
posts = Post.all().order('-created').fetch(perPage,perPage * realPage)
prefetch.prefetch_posts_list(posts)
i = perPage * realPage + 1
for post in posts:
post.number = i
i = i + 1
if helper.is_json(self.request.url):
posts_json = [p.to_json() for p in posts]
if(self.request.get('callback')):
self.response.headers['Content-Type'] = "application/javascript"
self.response.out.write(self.request.get('callback')+'('+simplejson.dumps({'posts':posts_json})+');')
else:
self.response.headers['Content-Type'] = "application/json"
self.response.out.write(simplejson.dumps({'posts':posts_json}))
else:
self.response.out.write(template.render('templates/main.html', locals()))
示例7: profile
def profile():
form = CreatePostForm()
# session gets the encrypted ID and hashes it to get the value i.e. the username
user = User.query.filter_by(username = session['username']).first()
if user is None:
return redirect(url_for('signin'))
else:
if request.method == 'POST':
if form.validate() == False:
return render_template('profile.html', form=form,communityform=CreateCommunityForm())
else:
newpost = Post(form.text.data, session['userID'], form.categoryID)
db.session.add(newpost)
file = request.files[form.image.name]
if file:
filename = secure_filename(file.filename)
# flush to ge the postID to be used as filename
db.session.flush()
filename = str(newpost.postID) + os.path.splitext(filename)[1]
newpost.imageURI = filename
file.save(os.path.join(APP_UPLOADS, filename))
flash(filename+" uploaded!")
db.session.commit()
flash("posted!")
return redirect(url_for('profile'))
elif request.method == 'GET':
# posts = Post.query.filter_by(username = session['username']).first()
return render_template('profile.html', form=form, communityform=CreateCommunityForm())
示例8: show_page
def show_page(num):
p = Page(num, per_page, Post.find().count())
p.urlfunc = lambda num: url_for("blog.show_page", num=num)
if not p.exists:
abort(404)
posts = Post.find({"is_published": True}).order_by("-timestamp")[p.slice()]
return render_template("blog/index.html", posts=posts, page=p)
示例9: edit_or_create_post
def edit_or_create_post(request):
try:
user = TestProfile.objects.get(email=request.user.email)
post = Post.objects.get(user=user)
provided, type = json.loads(post.provided), json.loads(post.house_type)
except Post.DoesNotExist:
post = None
type = None
provided = None
except TestProfile.DoesNotExist:
user = None
if request.POST.get('add'):
if user is not None and post is None:
user.num_posts += 1
post = Post(user=user, region=user.region, sub_region='Berkeley', distance='',
title=request.POST.get('title'),
house_type=json.dumps(request.POST.getlist('housing_type[]')),
provided=json.dumps(request.POST.getlist('provided[]')),
proximity='10 minute walk',
num_people=1,
notes=request.POST.get('notes'))
post.save()
provided, type = json.loads(post.provided), json.loads(post.house_type)
print(provided)
elif request.POST.get('delete'):
if user.num_posts > 0:
user.num_posts -= 1
if post is not None:
post.delete()
user.save()
context = {'user': user, 'post': post, 'type': type, 'provided': provided}
return render(request, 'temporary_housing/edit_or_create_post.html', context)
示例10: get_context_data
def get_context_data(self, *args, **kwargs):
ctx = super(PostList, self).get_context_data(*args, **kwargs)
page = self.request.GET.get('p', 1)
if self.request.user.is_authenticated():
objects = Post.all().order("-post_date")
else:
objects = Post.published().order("-post_date")
pager = Paginator(objects, PAGE_SIZE)
try:
page_obj = pager.page(page)
except InvalidPageException:
raise Http404
ctx.update({
'paginator': pager,
'page_obj': page_obj,
})
return ctx
示例11: fetch
def fetch(request):
if request.method != 'GET':
raise Http404
params = {}
for k in ('since_id', 'until_id', 'count'):
if k in request.GET:
params[k] = request.GET[k]
since_post = None
until_post = None
if 'since_id' in params:
since_post = Post.get_by_id(int(params['since_id']))
elif 'until_id' in params:
until_post = Post.get_by_id(int(params['until_id']))
count = 8
if 'count' in params and re.match('\d+', params['count']):
count = int(params['count'])
if not (count >= 1 and count <= 8):
count = 8
posts = Post.fetch(**{
'since_post' : since_post,
'until_post' : until_post,
'count' : count
})
return util.respond(True, [post.to_dict() for post in posts])
示例12: publications
def publications(request):
if request.method == 'POST':
# save new post
title = request.POST['title']
authors = request.POST['authors']
publisher = request.POST['publisher']
papertype = request.POST['papertype']
page_num = request.POST['page_num']
additional_info = request.POST['additional_info']
# selectedpublication = request.POST['selectedpublication']
str_date_published = request.POST['date_published']
post = Post(title=title)
# post.date_published = datetime.datetime.now()
post.date_published = datetime.fromtimestamp(mktime(time.strptime(str_date_published, "%b %d %Y")))
post.authors = authors
post.papertype = papertype
post.page_num = page_num
post.additional_info = additional_info
post.publisher = publisher
if request.POST.get('selectedpublication', True):
post.selectedpublication = True;
post.save()
# Get all posts from DB
posts = Post.objects
return render_to_response('admin/publications.html', {'Posts': posts},
context_instance=RequestContext(request))
示例13: test_comment_approved
def test_comment_approved(self):
post = Post(author=self.me, title="Hi", created_date=timezone.now())
post.save()
comment = Comment(author=self.me.username, post=post)
comment.approve()
comment.save()
assert comment in post.approved_comments()
示例14: post
def post(self, request):
"""
Crea un post a partir de la información POST
"""
success_message = ''
post_with_owner = Post()
post_with_owner.owner = request.user # aquí asignamos al usuario como propietario del post
form = PostForm(request.POST, instance=post_with_owner)
if form.is_valid():
new_post = form.save()
form = PostForm() # reiniciamos el form
success_message = 'Post almacenado con éxito! '
success_message += '<a href="{0}">'.format(
reverse('post_detail', args=[request.user.username, new_post.pk])
)
success_message += 'Ver post'
success_message += '</a>'
context = {
'form': form,
'success_message': success_message
}
return render(request, 'blogs/new_post.html', context)
示例15: feed_update
def feed_update(id=None):
# Manual update of one or all feeds now
if request.json['action'] == 'refresh':
# Call refresh routine
# TODO: RSS worker functions in separate package
# TODO: Need to capture return status
if id is None:
rss_spawn() # Update all feeds
else:
try:
feed = Feed.get(Feed.id == id)
except Feed.DoesNotExist:
return jsonify(**FEED_NOT_FOUND)
rss_worker(feed) # Update single feed
# return JSON status OK
return jsonify(**STATUS_OK)
# Mark one or all feeds read
elif request.json['action'] == 'markread':
if id is None:
# Mark all posts read
query = Post.update(is_read=True)
else:
# Mark posts in current feed read
query = Post.update(is_read=True).where(Feed.id == id)
query.execute()
# return JSON status OK
return jsonify(**STATUS_OK)