def get(self, user): page = helper.sanitizeHtml(self.request.get('pagina')) target_user_str= helper.sanitizeHtml(helper.parse_post_id(user)) perPage = 20 page = int(page) if page else 1 realPage = page - 1 if realPage > 0: prevPage = realPage session = get_current_session() if session.has_key('user'): user = session['user'] target_user = User.all().filter('lowercase_nickname =', target_user_str).fetch(1) if len(target_user) > 0: posts = Post.all().filter('user ='******'-created').fetch(perPage,perPage * realPage) if (page * perPage) < Post.all().filter('user ='******'-created').count(): nextPage = page + 1 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())) else: self.redirect('/')
def post(self): session = get_current_session() url = self.request.get("url") title = helper.sanitizeHtml(self.request.get("title")) message = helper.sanitizeHtml(self.request.get("message")) nice_url = helper.sluglify(title) if session.has_key("user"): if len(nice_url) > 0: user = session["user"] if len(message) == 0: # is it a post or a message? # Check that we don't have the same URL within the last 'check_days' since_date = date.today() - timedelta(days=7) q = Post.all().filter("created >", since_date).filter("url =", url).count() url_exists = q > 0 q = Post.all().filter("nice_url", nice_url).count() nice_url_exist = q > 0 try: if not url_exists: if not nice_url_exist: post = Post(url=url, title=title, message=message, user=user, nice_url=nice_url) post.put() vote = Vote(user=user, post=post, target_user=post.user) vote.put() Post.remove_cached_count_from_memcache() self.redirect("/noticia/" + str(post.nice_url)) else: session["post_error"] = "Este titulo ha sido usado en una noticia anterior" self.redirect("/agregar") else: session["post_error"] = "Este link ha sido entregado en los ultimo 7 dias" self.redirect("/agregar") except db.BadValueError: session["post_error"] = "El formato del link no es valido" self.redirect("/agregar") else: q = Post.all().filter("nice_url", nice_url).count() nice_url_exist = q > 0 if not nice_url_exist: post = Post(title=title, message=message, user=user, nice_url=nice_url) post.put() post.url = helper.base_url(self) + "/noticia/" + post.nice_url post.put() Post.remove_cached_count_from_memcache() vote = Vote(user=user, post=post, target_user=post.user) vote.put() self.redirect("/noticia/" + post.nice_url) else: session["post_error"] = "Este titulo ha sido usado en una noticia anterior" self.redirect("/agregar") else: session["post_error"] = "Necesitas agregar un titulo" self.redirect("/agregar") else: self.redirect("/login")
def list_post(request): posts = None if not is_admin(): posts = Post.all().filter("is_published", True).order("-create_time") else: posts = Post.all().order("-create_time") return object_list( request, queryset=posts, allow_empty=True, template_name="list_post.html", extra_context={"is_author": is_author()}, paginate_by=settings.POST_LIST_PAGE_SIZE, )
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()))
def get(self,post_id): session = get_current_session() if session.has_key('user'): user = session['user'] try: post = Post.all().filter('nice_url =', helper.parse_post_id( post_id ) ).get() if post == None: #If for some reason the post doesn't have a nice url, we try the id. This is also the case of all old stories post = db.get( helper.parse_post_id( post_id ) ) comments = Comment.all().filter("post =", post.key()).order("-karma").fetch(1000) comments = helper.order_comment_list_in_memory(comments) prefetch.prefetch_comment_list(comments) display_post_title = True prefetch.prefetch_posts_list([post]) if helper.is_json(post_id): comments_json = [c.to_json() for c in comments if not c.father_ref()] if(self.request.get('callback')): self.response.headers['Content-Type'] = "application/javascript" self.response.out.write(self.request.get('callback')+'('+simplejson.dumps({'post':post.to_json(),'comments':comments_json})+')') else: self.response.headers['Content-Type'] = "application/json" self.response.out.write(simplejson.dumps({'post':post.to_json(),'comments':comments_json})) else: self.response.out.write(template.render('templates/post.html', locals())) except db.BadKeyError: self.redirect('/')
def get(self, year=None, month=None, day=None, slug=None, tag=None): datestart = datetime.date.min dateend = datetime.date.min if year: datestart = datestart.replace(year=year) dateend = dateend.replace(year=year+1) if month: datestart = datestart.replace(month=month) if month == 12: dateend = dateend.replace(year=year+1) dateend = dateend.replace(month=1) else: dateend = dateend.replace(month=month+1) if day: datestart = datestart.replace(day=day) one_day = datetime.timedelta(days=1) dateend = datestart + one_day print datetime.datetime.now() print datetime.datetime.utcnow() print datetime.datetime.utcnow().replace(tzinfo=pytz.utc).astimezone(pytz.timezone('Asia/Singapore')) posts = Post.all()\ .filter('datecreated >=', datestart)\ .filter('datecreated <', dateend) return render_template('blog/list.html', posts=posts)
def get(self): posts = Post.all().order("-created").fetch(20) prefetch_posts_list(posts) items = [] for post in posts: items.append( PyRSS2Gen.RSSItem( title=post.title, link="http://noticiashacker.com/noticia/" + str(post.key()), description="", guid=PyRSS2Gen.Guid("guid1"), pubDate=post.created, ) ) rss = PyRSS2Gen.RSS2( title="Noticias Hacker", link="http://noticiashacker.com/", description="", lastBuildDate=datetime.now(), items=items, ) print "Content-Type: text/xml" self.response.out.write(rss.to_xml("utf-8"))
def list_post(request): posts = Post.all().order('-create_time') if (not is_admin()): posts = posts.filter("is_published", True) return object_list(request, queryset=posts, allow_empty=True, template_name='list_post.html', extra_context={'is_author': is_author()}, paginate_by=settings.POST_LIST_PAGE_SIZE)
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
def show_entries(): user = users.get_current_user() if user: session["logged_in"] = True posts = Post.all() return render_template("show_entries.html", entries=posts)
def get(self): posts = Post.all().order('-created').fetch(20) prefetch.prefetch_posts_list(posts) items = [] for post in posts: if len(post.message) == 0: rss_poster = '<a href="'+post.url+'">'+post.url+'</a>' else: rss_poster = post.message rss_poster += ' por <a href="'+helper.base_url(self)+'/perfil/'+post.user.nickname+'">'+post.user.nickname+'</a>' link = helper.base_url(self)+'/noticia/' + str(post.key()) if post.nice_url: link = helper.base_url(self)+'/noticia/' + str(post.nice_url) items.append(PyRSS2Gen.RSSItem( title = post.title, link = link, description = rss_poster, guid = PyRSS2Gen.Guid("guid1"), pubDate = post.created )) rss = PyRSS2Gen.RSS2( title = "Noticias Hacker", link = "http://noticiashacker.com/", description = "Noticias Hacker", lastBuildDate = datetime.now(), items = items ) print 'Content-Type: text/xml' self.response.out.write(rss.to_xml('utf-8'))
def index(page = 1): user = g.user posts = [ { 'author': { 'nickname': 'John' }, 'body': 'Beautiful day in Portland!' }, { 'author': { 'nickname': 'Susan' }, 'body': 'The Avengers movie was so cool!' } ] posts = Post.query.order_by(desc(Post.created)).paginate(page, POSTS_PER_PAGE, False).items pagination = Pagination(page=page, total=len(Post.all()), per_page=POSTS_PER_PAGE, search=False, css_framework='bootstrap3', record_name='posts') return render_template('index.html', posts = posts, user = user, pagination=pagination, )
def history(): show_count = 50 startPage = int(request.args.get('page', 1)) prevpage = startPage - 1 if prevpage <= 0: prevpage = None nextpage = startPage + 1 startOffset = startPage * show_count - show_count nextOffset = nextpage * show_count - show_count heekPost = PostRoot(key_name='heek', version=2) query = Post.all() query.ancestor(heekPost) query.order('-datetime') rows = [dict(text=post.text) for post in query.run(offset=startOffset, limit=show_count)] next_cnt = query.count(offset=nextOffset, limit=show_count) if next_cnt == 0: nextpage = None return render_template('history.html', contents=rows, prevpage=prevpage, nextpage=nextpage)
def delete_post(cls, post_id, user_id): error_msg = None posts = Post.all().order('-created').fetch(limit=10) updated_post_list = posts post = Post.get_by_id(post_id) if user_id == post.created_by: # delete comments of the post comments = Comment.all().filter('post_id =', post_id).fetch(limit=10) for c in comments: Comment.delete(c) # delete likes of the post likes = Like.all().filter('post_id =', post_id).fetch(limit=10) for l in likes: Like.delete(l) # delete the post updated_post_list = cls.update_list_on_delete( object_list=posts, object_id=post_id ) Post.delete(post) else: error_msg = 'You can delete only your own posts' return updated_post_list, error_msg
def post(self, post_id): session = get_current_session() if session.has_key('user'): message = helper.sanitizeHtml(self.request.get('message')) user = session['user'] key = self.request.get('comment_key') if len(message) > 0 and key == keys.comment_key: try: post = Post.all().filter('nice_url =', helper.parse_post_id( post_id ) ).get() if post == None: #If for some reason the post doesn't have a nice url, we try the id. This is also the case of all old stories post = db.get( helper.parse_post_id( post_id ) ) post.remove_from_memcache() comment = Comment(message=message,user=user,post=post) comment.put() helper.killmetrics("Comment","Root", "posted", session, "",self) vote = Vote(user=user, comment=comment, target_user=user) vote.put() Notification.create_notification_for_comment_and_user(comment,post.user) self.redirect('/noticia/' + post_id) except db.BadKeyError: self.redirect('/') else: self.redirect('/noticia/' + post_id) else: self.redirect('/login')
def get_post(slug): q = Post.all() q.filter("slug =", slug) post = q.get() if post is not None: return render_template('post.html', post=post) else: return render_template('404.html'), 404
def get(self, year=None, month=None, day=None, slug=None): ##print year, month, day, slug start_date = datetime.date(year, month, day) ##post = Post.all().filter('slug =', slug).get() post = Post.all().filter('datecreated >', start_date).get() print post post.content = apply_markdown(post.content) return render_template('blog/detail.html', post=post)
def render_blog(self, posts=''): if self.user: username = self.user.username else: username = "" posts = Post.all().order('-created').fetch(limit=10) self.render("blog.html", posts=posts, username=username)
def getMessage(): heekPost = PostRoot(key_name='heek', version=2) query = Post.all() query.ancestor(heekPost) query.order('-datetime') for post in query.run(limit=1): return post.text
def get_posts(update = False): q = Post.all().order('-created').fetch(limit = 10) key = 'all' posts, age = age_get(key) if posts is None or update: posts = list(q) age_set(key, posts) return posts, age
def cache_computation(self): #start_time=time.time() cache={} key=self.length() if key in cache: r=cache[key] else: r= Post.all().order('-created') return r
def list_category_post(request, category_id): category = Category.get_by_id(int(category_id)) if not category: raise Http404 posts = Post.all().filter('category', category).order('-create_time') return object_list(request, queryset=posts, allow_empty=True, template_name='list_category_post.html', extra_context={'is_author': is_author(), 'category': category}, paginate_by=settings.POST_LIST_PAGE_SIZE)
def get(self): posts = Post.all().filter('created <', datetime.datetime.now() - datetime.timedelta(days=90)) assert posts.count() try: while True: db.delete(posts.fetch(100)) time.sleep(0.1) except DeadlineExceededError: self.response.clear() self.response.set_status(200)
def list_all_post(request): posts = Post.all().order("-create_time") return object_list( request, queryset=posts, allow_empty=True, template_name="list_post.html", extra_context={"is_admin": is_admin()}, paginate_by=settings.POST_LIST_PAGE_SIZE, )
def search(request): if request.REQUEST.has_key('q'): keywords = request.GET['q'] logging.getLogger().info(keywords) posts = Post.all().search(keywords).order('-create_time') return object_list(request, queryset=posts, allow_empty=True, template_name='search_post.html', extra_context={'keywords': keywords}, paginate_by=settings.POST_LIST_PAGE_SIZE) else: return HttpResponseRedirect('/')
def get_posts_by_user(self, user, limit, offset): """ Get all posts by a specific user, ordered by creation date (descending). The user parameter will be a User object. """ # TODO - filter the query so that only posts by the given user query = Post.all().filter("author", user).order("-created") return query.fetch(limit=limit, offset=offset)
def validate(self): rv = Form.validate(self) if not rv: return False slug = Post.all().filter('slug =', self.slug.data).get() if slug: self.slug.errors.append('The slug needs to be unique') return False return True
def get(self): # get all posts. posts = Post.all().order('-created') # if logged in show user navigation, if not show guest navigation. username = self.check_login(self.request.cookies.get('user_id')) if username: self.render('/blog.html', username=username, posts=posts) else: self.render('/blog.html', posts=posts)
def get_posts_by_user(self, user, limit, offset): """ Get all posts by a specific user, ordered by creation date (descending). The user parameter will be a User object. """ #query = Post.all().order('-created') #query = Post.all().filter("author",db.get("aglkZXZ-YmxvZ3pyEQsSBFVzZXIYgICAgICAoAsM")).order('-created') query = Post.all().filter("author",user).order('-created') #import pdb; pdb.set_trace() #print("bye") return query.fetch(limit=limit,offset=offset)
def get(self): posts = Post.all().filter( 'created <', datetime.datetime.now() - datetime.timedelta(days=90)) assert posts.count() try: while True: db.delete(posts.fetch(100)) time.sleep(0.1) except DeadlineExceededError: self.response.clear() self.response.set_status(200)
def test_uploading_file_with_unsupported_content_type(self): """ Uploading file with an unsupported content type should return a 200 page with a message explaining file type is not supported. """ response = self.upload_file(self.test_file1_path, self.test_file1_sha1, "image/tiff", 1, self.sid, self.xsrf) self.assertEqual(200, response.code) self.assertTrue( response.body.find("We don't support that file type.") > 0) posts = Post.all() self.assertEqual(len(posts), 0)
def get_posts(update = False): mc_key='BLOGS' posts, age=age_get(mc_key) if update or posts is None: q=Post.all().order('-created').fetch(limit=10) #q = db.GqlQuery("select * from Post order by created desc limit 10") posts=list(q) age_set(mc_key,posts) age = 0 return posts, age
def get_posts_by_user(self, user, limit, offset): """ Get all posts by a specific user, ordered by creation date (descending). The user parameter will be a User object. """ # TODO - filter the query so that only posts by the given user #post = db.GqlQuery("SELECT * FROM Post WHERE author = '%s'" % user) #return post #query = Post.all().order('-created') #return query.fetch(limit=limit, offset=offset) query = Post.all().filter("author", user) return query.fetch(limit=limit, offset=offset)
def get(self): posts = Post.all().order('-size').fetch(20) try: current_post = None for post in posts: current_post = post bin = post.bin self.response.out.write(template.render('templates/stats.html', locals())) except datastore_errors.Error, e: if e.args[0] == "ReferenceProperty failed to be resolved": current_post.delete() self.redirect('/stats')
def news_feed(): feed = AtomFeed('EURYPAA 2016 News Posts', feed_url=request.url, url=request.url_root) posts = Post.all() for post in posts: feed.add(post.title, unicode(post.content), content_type='html', author="EURYPAA2016 Admin", published=post.when, updated=post.when, id=post.when) return feed.get_response()
def get_object(self): slug = self.kwargs.get('slug', '') if self.request.user.is_authenticated(): qs = Post.all() else: qs = Post.published() try: self.object = qs.filter('slug =', slug).fetch(1)[0] except IndexError: self.object = None
def news_feed(): feed = AtomFeed('%(EVENT_NAME)s News Posts' % session, feed_url=request.url, url=request.url_root) posts = Post.all() for post in posts: feed.add(post.title, unicode(post.content), content_type='html', author=post.author, published=post.when, updated=post.when, id=post.when) return feed.get_response()
def post(self): session = get_current_session() url = self.request.get('url') title = helper.sanitizeHtml(self.request.get('title')) message = helper.sanitizeHtml(self.request.get('message')) if session.has_key('user'): if len(title) > 0: user = session['user'] if len(message) == 0: #is it a post or a message? #Check that we don't have the same URL within the last 'check_days' since_date = date.today() - timedelta(days=7) q = Post.all().filter("created >", since_date).filter("url =", url).count() url_exists = q > 0 try: if not url_exists: post = Post(url=url, title=title, message=message, user=user) post.put() vote = Vote(user=user, post=post, target_user=post.user) vote.put() Post.remove_cached_count_from_memcache() self.redirect('/noticia/' + str(post.key())) else: session[ 'post_error'] = "Este link ha sido entregado en los ultimo 7 dias" self.redirect('/agregar') except db.BadValueError: session[ 'post_error'] = "El formato del link no es valido" self.redirect('/agregar') else: post = Post(title=title, message=message, user=user) post.put() post.url = helper.base_url(self) + "/noticia/" + str( post.key()) post.put() Post.remove_cached_count_from_memcache() vote = Vote(user=user, post=post, target_user=post.user) vote.put() self.redirect('/noticia/' + str(post.key())) else: session['post_error'] = "Necesitas agregar un titulo" self.redirect('/agregar') else: self.redirect('/login')
def get(self): if hasattr(keys,'consumer_key') and hasattr(keys,'consumer_secret') and hasattr(keys,'access_token') and hasattr(keys,'access_token_secret') and hasattr(keys,'bitly_login') and hasattr(keys,'bitly_apikey') and hasattr(keys,'base_url') and helper.base_url(self) == keys.base_url: posts = Post.all().order('-karma').fetch(20) for post in posts: if not post.twittered: post.twittered = True post.put() out = sendMessageToTwitter(self,post) self.response.out.write("Printed:" + out) return self.response.out.write("No more message") else: self.response.out.write("No keys")
def test_task_timeline_delete_posts(self): """ this test calls delete_posts directly to ensure deleted files get marked as deleted """ add_posts(shake_id=self.shake_a.id, sharedfile_id=self.shared_1.id, sourcefile_id=self.source.id) add_posts(shake_id=self.shake_a.id, sharedfile_id=self.shared_2.id, sourcefile_id=self.source.id) delete_posts(sharedfile_id=self.shared_1.id) delete_posts(sharedfile_id=self.shared_2.id) posts = Post.all() for post in posts: self.assertTrue(post.deleted)
def get(self): ''' Retrieves all blog posts from db, orders them then renders blog.html with those posts. ''' posts = Post.all() posts.order('-post_date') if self.is_logged_in()[0]: self.render("blog.html", posts=posts, login="******") self.render("logout.html", banner="logout") else: self.render("blog.html", posts=posts, login="******") self.render("signin.html", banner="signin")
def get_posts_by_user(self, user, limit, offset): """ Get all posts by a specific user, ordered by creation date (descending). The user parameter will be a User object. """ ####### TODO - filter the query so that there are only posts by the given user # only use ORM syntax # query = Post.all().order('-created').filter(author) # return query.fetch(user=user, limit=limit, offset=offset) user_posts = Post.all().order('-created').filter("author", user) # return user_posts return user_posts.fetch(limit=limit, offset=offset)
def list_category_post(request, category_id): category = Category.get_by_id(int(category_id)) if not category: raise Http404 posts = Post.all().filter('category', category).order('-create_time') return object_list(request, queryset=posts, allow_empty=True, template_name='list_category_post.html', extra_context={ 'is_author': is_author(), 'category': category }, paginate_by=settings.POST_LIST_PAGE_SIZE)
def get(self, username=""): """ handles get request """ cookie = self.request.cookies.get("username") is_logged_in = self.is_logged_in() if cookie: username = check_secure_val(cookie) if username: posts = Post.all().filter("name = ", username) self.render("welcome.html", username=username, is_logged_in=is_logged_in, posts=posts) else: self.redirect("/signup")
def get(self, username=""): """ """ # If request is for a specific page, set page number and offset # accordingly page = self.request.get("page") offset = 0 page = page and int(page) if page: offset = (int(page) - 1) * self.page_size else: page = 1 # Fetch posts for all users, or a specific user, depending on request # parameters if username: user = self.get_user_by_name(username) posts = self.get_posts_by_user(user, self.page_size, offset) else: posts = self.get_posts(self.page_size, offset) # determine next/prev page numbers for navigation links if page > 1: prev_page = page - 1 else: prev_page = None if not posts: # fixes error when no posts exist, sets posts to empty rather than # None, maintaining compatiblilty with subsequent code. posts = "" if len(posts) == self.page_size and Post.all().count( ) > offset + self.page_size: next_page = page + 1 else: next_page = None # render the page t = jinja_env.get_template("blog.html") response = t.render(posts=posts, page=page, page_size=self.page_size, prev_page=prev_page, next_page=next_page, username=username) self.response.out.write(response)
def get(self, post_id): p = Post.get_by_id(int(post_id)) if not p: self.error(404) return if self.user and (self.user.key() == p.user_obj.key()): self.render("deletePost.html", subject= p.subject) elif self.user and (self.user.key() != p.user_obj.key()): error = "You can only delete posts you created!" posts = greetings = Post.all().order('-created') comments = Comment.all().order('-created') self.render("front.html", posts=posts, comments=comments, error=error) else: self.redirect('/login')
def get_posts_by_user(self, user, limit, offset): """ Get all posts by a specific user, ordered by creation date (descending). The user parameter will be a User object. """ #user = user.key().id() #userkey = User.Key() #author = Post.key().author() #query = User.key() posts = Post.all().order('-created') author = user.key() #post = db.GqlQuery("SELECT * FROM Post WHERE author = '%s'" % author) post = posts.filter('author =', author) #if post: # return post.get() # TODO - filter the query so that only posts by the given user #return None return post.fetch(limit=limit, offset=offset)
def sitemap(request): str = '''<?xml version="1.0" encoding="UTF-8"?> <?xml-stylesheet type="text/xsl" href="/static/xsl/sitemap.xsl"?> <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> <url> <loc>http://www.niubi.de/</loc> <changefreq>weekly</changefreq> <priority>0.9</priority> </url> ''' posts = Post.all().filter('is_published', True) for post in posts: str += '''<url> <loc>http://www.niubi.de/post/%s/</loc> <changefreq>weekly</changefreq> <priority>0.8</priority> </url> ''' % post.key().id() categories = Category.all().order('-post_count') for category in categories: str += '''<url> <loc>http://www.niubi.de/category/%s/</loc> <changefreq>monthly</changefreq> <priority>0.8</priority> </url> ''' % category.key().id() tags = Tag.all().order('-post_count') for tag in tags: str += '''<url> <loc>http://www.niubi.de/tag/%s/</loc> <changefreq>weekly</changefreq> <priority>0.8</priority> </url> ''' % tag.name str += '''<url> <loc>http://www.niubi.de/about/</loc> <changefreq>yearly</changefreq> <priority>0.8</priority> </url>''' str += '</urlset>' return HttpResponse(str, content_type='text/xml')
def get(self, post_id): session = get_current_session() if session.has_key('user'): user = session['user'] try: post = Post.all().filter('nice_url =', helper.parse_post_id(post_id)).get() if post == None: #If for some reason the post doesn't have a nice url, we try the id. This is also the case of all old stories post = db.get(helper.parse_post_id(post_id)) comments = Comment.all().filter( "post =", post.key()).order("-karma").fetch(1000) comments = helper.order_comment_list_in_memory(comments) prefetch.prefetch_comment_list(comments) display_post_title = True prefetch.prefetch_posts_list([post]) if helper.is_json(post_id): comments_json = [ c.to_json() for c in comments if not c.father_ref() ] if (self.request.get('callback')): self.response.headers[ 'Content-Type'] = "application/javascript" self.response.out.write( self.request.get('callback') + '(' + simplejson.dumps({ 'post': post.to_json(), 'comments': comments_json }) + ')') else: self.response.headers['Content-Type'] = "application/json" self.response.out.write( simplejson.dumps({ 'post': post.to_json(), 'comments': comments_json })) else: self.response.out.write( template.render('templates/post.html', locals())) except db.BadKeyError: self.redirect('/')
def get(self, username=""): """ """ # If request is for a specific page, set page number and offset accordingly page = self.request.get("page") offset = 0 page = page and int(page) if page: offset = (int(page) - 1) * self.page_size else: page = 1 # Fetch posts for all users, or a specific user, depending on request parameters if username: user = self.get_user_by_name(username) posts = self.get_posts_by_user(user, self.page_size, offset) else: posts = self.get_posts(self.page_size, offset) # determine next/prev page numbers for navigation links if page > 1: prev_page = page - 1 else: prev_page = None if posts == None: next_page = None elif len(posts) == self.page_size and Post.all().count() > offset+self.page_size: next_page = page + 1 else: next_page = None # render the page t = jinja_env.get_template("blog.html") response = t.render( posts=posts, page=page, page_size=self.page_size, prev_page=prev_page, next_page=next_page, username=username) self.response.out.write(response)
def get(self, username=""): """Fetch posts for all users,or a specific user,depending on request parameters""" if username: user = self.get_user_by_name(username) posts = self.get_posts_by_user(user, self.page_size, offset) counter = Post.all().filter('author', user).count() else: self.redirect('/login') # t = jinja_env.get_template("userview.html") response = self.render_template("userview.html", posts=posts, page_size=self.page_size, username=username, counter=counter) # response = t.render( # posts=posts, # page_size=self.page_size, # username=username, # counter=counter) self.response.out.write(response)
def render_front(self, creator): posts = Post.all().order('-created') # posts = db.GqlQuery("select * from Post order by created desc # limit 10") # look for likes in Like entity for the current user (creator) likes = Like.all().filter("user = ", creator) dict = [] if likes: # iterate through and make dictionary from response for l in likes: dict.append(int(l.post_id)) # turn dict into a set userlikes = set(dict) if posts: self.render('index.html', posts=posts, creator=creator, userlikes=userlikes) else: self.render('noposts.html')
def get(self): u = self.current_user() user_logged = None user_id_logged = None posts = Post.all().order('-date_added') if u: user_logged = u.username user_id_logged = u.key().id() results = posts.fetch(limit=10) # Get updated cursor and store it for the first time for pagination post_cursor = posts.cursor() memcache.set('post_cursor', post_cursor) self.render('front.html', user_logged=user_logged, user_id_logged=user_id_logged, posts=results, page_number=1)
def get(self, post_id): #k = db.Key.from_path("Post", int(post_id), parent=blog_key()) p = Post.get_by_id(int(post_id)) if not p: self.redirect('/') return if self.user and (self.user.key() == p.user_obj.key()): self.render("newpost.html", subject=p.subject, content=p.content) elif not self.user: self.redirect('/') else: posts = greetings = Post.all().order('-created') comments = Comment.all().order('-created') error = "You can only edit posts you created." self.render('front.html', posts=posts, comments=comments, error=error)
def get(self): posts = Post.all().order('-created').fetch(20) prefetch_posts_list(posts) items = [] for post in posts: items.append( PyRSS2Gen.RSSItem(title=post.title, link="http://noticiashacker.com/noticia/" + str(post.key()), description="", guid=PyRSS2Gen.Guid("guid1"), pubDate=post.created)) rss = PyRSS2Gen.RSS2(title="Noticias Hacker", link="http://noticiashacker.com/", description="", lastBuildDate=datetime.now(), items=items) print 'Content-Type: text/xml' self.response.out.write(rss.to_xml('utf-8'))
def get(self): page = 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_posts_list(posts) i = perPage * realPage + 1 for post in posts: post.number = i i = i + 1 self.response.out.write( template.render('templates/main.html', locals()))
def get(self, post_id): k = db.Key.from_path('Comment', int(post_id), parent=blog_key()) c = db.get(k) if not c: self.error(404) return if self.user and (self.user.key() == c.comment_user.key()): self.render("usercomment.html", content=c.content) elif self.user and (self.user.key() != c.comment_user.key()): posts = greetings = Post.all().order('-created') comments = Comment.all().order('-created') error = "You can only edit comments you created." self.render('front.html', posts=posts, comments=comments, error=error) else: self.redirect('/login')