def create_sample_blog_entries(klass, count=50): """ Create N number of sample blog entries where N = the count parameter. Text in posts till be random lorem ipsum text. Author will be a randomly selected author from the system, and date will be a random date from the last 2 years. All test entries will be marked "published". """ klass._setup(BlogEntry, count) while count > 0: headline = words(randrange(3,12), common=False).capitalize() slug = klass._check_slug(slugify(headline)[:klass.field_len]) b = BlogEntry( headline = headline, slug = slug, intro = klass._join_paras( paragraphs(randrange(1,3), common=False) ), body = klass._join_paras( paragraphs(randrange(2,5), common=False) ), pub_date = klass._get_rand_date(), status = BloggingSettings.PUBLISHED_ENTRY_STATES[0], author = Author.objects.order_by('?')[0] ) b.save() count += -1
def testWithTwoBlogEntries(self): BlogEntry(title='entry1', text='entry1').save() BlogEntry(title='entry2', text='entry2').save() result = IndexHandler().render() self.assertIn('entry2', result) self.assertIn('entry1', result) self.assertLess(result.index('entry2'), result.index('entry1'))
def post(self): user_id = None commentId = None # AUTHENTICATE check for valid cookie user_id = auth(self.request.cookies.get('user_id')) commentId = self.request.get("commentId") comment = self.request.get("comment") postId = self.request.get("postId") q = BlogEntry.get_by_id(int(postId)) k = q.key() if user_id: commentId = int(commentId) comEntity = Comments.get_by_id(commentId, parent=k) if user_id == comEntity.author_id: q = BlogEntry.get_by_id(int(postId)) if q: k = q.key() c = Comments.get_by_id(int(commentId), parent=k) if c: c.comment = comment c.put() error = "" self.redirect("/focus?postId=%s&error=%s" % (postId, error)) else: error = "You must be the author to edit the comment." self.redirect("/focus?postId=%s&error=%s" % (postId, error)) else: error = "You must be loggen in to edit the comment." self.redirect("/focus?postId=%s&error=%s" % (postId, error))
def post(self): # AUTHENTICATE user_id = None # AUTHENTICATE check for valid cookie user_id = auth(self.request.cookies.get('user_id')) title = self.request.get("title") body = self.request.get("body") like = 0 if user_id: if title and body: u = Users.get_by_id(int(user_id)) b = BlogEntry(title=title, body=body, author_name=u.userName, likes=like, author_id=user_id) b.put() self.redirect("/welcome") else: error = "Please provide BOTH a title and body." # must include all the parameters below to preserve user # entered data self.render_newpost(title=title, body=body, error=error) else: self.redirect("/login")
def post(self): user_id = None # AUTHENTICATE check for valid cookie user_id = auth(self.request.cookies.get('user_id')) postId = self.request.get("postId") # must be logged in if user_id: q = BlogEntry.get_by_id(int(postId)) title = q.title body = q.body created = q.created last_mod = q.last_mod author = q.author_id # ONLY AUTHOR CAN EDIT: check that user_id matches the AUTHOR if author == user_id: q = BlogEntry.get_by_id(int(postId)) q.delete() error = "Post deleted" self.redirect("/welcome?error=%s" % error) else: error = "Only the author can delete." self.redirect("/focus?postId=%s&error=%s" % (postId, error)) else: error = "Please signup and login to edit posts." self.redirect("/focus?postId=%s&error=%s" % (postId, error))
def index(): BEERS_PER_PAGE = app.config['POSTS_PER_PAGE'] page = int(request.args.get('page', '1')) beers = BlogEntry.select().order_by(('date', 'desc'), ).paginate(page, BEERS_PER_PAGE) pagination = Pagination(page, BEERS_PER_PAGE, BlogEntry.count()) return render_template('index.html',sorted_entries=beers, pagination=pagination)
def testNoEditLinkForGuest(self): # Given there is a blog entry in the database BlogEntry(title='entry1', text='entry1').save() self.assertEqual(1, BlogEntry.all().count()) # When I visit the home page result = IndexHandler().render() # Then I should not see the "Edit" link self.assertNotRegexpMatches(result, r"<a href=[^>]+>Edit</a>")
def testPostNewBlogEntry(self, textLength=200): self.signInAsAdmin() self.assertEqual(0, BlogEntry.all().count()) handler = self.createNewBlogEntryHandler(textLength=textLength) handler.post() self.assertEqual(1, BlogEntry.all().count()) e = BlogEntry.all().get() self.assertEqual('asdsad', e.title) self.assertEqual(handler.request.text, e.text)
def testEditBlogEntry(self): # Given there is a blog entry in the database entry = BlogEntry(title='entry1', text='entry1') entry.save() self.assertEqual(1, BlogEntry.all().count()) # And I am signed in as admin self.signInAsAdmin() # When I edit the blog entry handler = self.createEditBlogEntryHandler() handler.request.GET['id'] = entry.key().id() handler.get() result = str(handler.response.out) # And I should see an input for "title" self.assertRegexpMatches(result, r'<[^>]+ name="title"[^>]*>') self.assertRegexpMatches(result, r'<[^>]+ value="entry1"[^>]*>') # And I should see an input for "text" self.assertRegexpMatches(result, r'<[^>]+ name="text"[^>]*>') self.assertRegexpMatches(result, r'<textarea[^>]*>entry1<') # And I should see a "Save" button self.assertRegexpMatches(result, r'<button[^>]*>Save</') # And I fill out the "title" field with "new title" handler = self.createEditBlogEntryHandler() handler.request.POST['id'] = entry.key().id() handler.request.POST['title'] = 'new title' # And I fill out the "text" field with "new text" handler.request.POST['text'] = 'new text' # And I click on the "Save" button handler.post() # And I should see the blog entry with "title": "new title" self.assertEqual(1, BlogEntry.all().count()) entry = BlogEntry.all().get() self.assertEqual('new title', entry.title) # And I should see the blog entry with "text": "new text" self.assertEqual('new text', entry.text)
def updateblog(request): # Get feed url = 'http://blog.instanssi.org/feeds/posts/default' feed = feedparser.parse(url) # Delete old entries BlogEntry.objects.filter(locked=False).delete() # Get items that have changed for item in feed['items']: locked = False try: oldentry = BlogEntry.objects.get(title=item['title']) locked = oldentry.locked except BlogEntry.DoesNotExist: pass if not locked: timestamp = datetime.fromtimestamp( time.mktime(item['published_parsed'])) + timedelta(hours=2) entry = BlogEntry() entry.title = item['title'] entry.summary = item['summary'] entry.date = timestamp entry.link = item['link'] entry.name = item['authors'][0]['name'] entry.save() # Just return "ok" return HttpResponse("ok")
def testRenderingBlogEntries(self): self.assertEqual(0, BlogEntry.all().count()) BlogEntry(title='asdsad', text='my text').save() self.assertEqual(1, BlogEntry.all().count()) result = IndexHandler().render() today = datetime.datetime.now().strftime('%Y-%m-%d') self.assertRegexpMatches(result, r'<[^>]+ class="title"[^>]*>asdsad</') self.assertRegexpMatches(result, r'<[^>]+ class="text"[^>]*><p>my text</p></') self.assertRegexpMatches(result, r'<[^>]+ class="date"[^>]*>%s</' % today)
def testEditLinkForAdmin(self): # Given there are no blog entries in the database self.assertEqual(0, BlogEntry.all().count()) # And I am signed in as admin self.signInAsAdmin() # And I add a new blog entry "entry1" BlogEntry(title='entry1', text='entry1').save() self.assertEqual(1, BlogEntry.all().count()) # When I visit the home page result = IndexHandler().render() # Then I should see a "Edit" link self.assertRegexpMatches(result, r"<a href=[^>]+>Edit</a>")
def blog_edit(blog_id): query = BlogEntry.getAll() query = BlogEntry.addBlogIdFilter(query, blog_id) if not query.one().username == session['username']: return abort(401) g.session = session g.blog_entry = query.one() g.blog_name = config.blog_name g.blog_subtitle = config.blog_subtitle g.title = 'Edit entry: %s' %(g.blog_entry.name) return render_template('edit.html', g=g)
def test_publication_logic(self): """ Verify that unpublished entries cannot be viewed """ unpub_state = filter( lambda s: s[0] not in BloggingSettings.PUBLISHED_ENTRY_STATES, BloggingSettings.PUB_STATES )[0][0] pub_state = BloggingSettings.PUBLISHED_ENTRY_STATES[0] slug = 'publication-test' # Start by creating a new, unpublished entry: entry = BlogEntry( slug=slug, headline='Headline TKTK', intro='Loren ipsum...', author=Author.objects.all()[0], #any author is fine... status=unpub_state, ) entry.save() # Trying to view it should show a 404: response = self.client.get(entry.get_absolute_url()) self.assertTrue(response.status_code == 404) # Now publish it: entry.status = pub_state entry.save() # Should be visible: response = self.client.get(entry.get_absolute_url()) self.assertTrue(response.status_code == 200)
def updateblog(request): # Get feed url = "http://blog.instanssi.org/feeds/posts/default" feed = feedparser.parse(url) # Delete old entries BlogEntry.objects.filter(locked=False).delete() # Get items that have changed for item in feed["items"]: locked = False try: oldentry = BlogEntry.objects.get(title=item["title"]) locked = oldentry.locked except BlogEntry.DoesNotExist: pass if not locked: timestamp = datetime.fromtimestamp(time.mktime(item["published_parsed"])) + timedelta(hours=2) entry = BlogEntry() entry.title = item["title"] entry.summary = item["summary"] entry.date = timestamp entry.link = item["link"] entry.name = item["authors"][0]["name"] entry.save() # Just return "ok" return HttpResponse("ok")
def get(self): user_id = None # AUTHENTICATE check for valid cookie user_id = auth(self.request.cookies.get('user_id')) postId = self.request.get("postId") if user_id: q = BlogEntry.get_by_id(int(postId)) title = q.title body = q.body created = q.created last_mod = q.last_mod author = q.author_id logging.warning(author + " = " + user_id) # ONLY AUTHOR CAN EDIT: check that user_id matches the AUTHOR if author == user_id: self.render("delete.html", title=title, body=body, created=created, last_mod=last_mod, author=author, postId=postId) else: error = "Only the author can delete." self.redirect("/focus?postId=%s&error=%s" % (postId, error)) else: error = "Please signup and login to edit posts." self.redirect("/focus?postId=%s&error=%s" % (postId, error))
def post(self, post_id): content = self.request.get("content") cookie = self.request.cookies.get('name') user = check_login(cookie) blog_post = BlogEntry.get_by_id(int(post_id)) comments = Comment.query(Comment.parent_post == post_id).fetch() if not user: self.redirect("/signup") elif content: comment = Comment(content=content, creator=user, parent_post=post_id) comment.put() self.redirect("/blog") # Could not figure out how to re-render the same page # while updating with the new post for some reason # so this is my work-around else: error = "You must include content" self.render("/permalink.html", blog_post=blog_post, post_id=post_id, comments=comments, content=content, error=error, user=user)
def post(self): user_id = None # AUTHENTICATE check for valid cookie user_id = auth(self.request.cookies.get('user_id')) postId = self.request.get("postId") if user_id: try: u = Users.get_by_id(int(user_id)) q = BlogEntry.get_by_id(int(postId)) except: pass if q: title = q.title body = q.body created = q.created last_mod = q.last_mod author = q.author_id k = q.key() try: comments = Comments.all().ancestor(k) except: pass # check again if user is the author.. if user_id == author: title = self.request.get("title") body = self.request.get("body") postId = self.request.get("postId") # if field is left empty if title == "": error = "You must enter a new title." self.redirect("/editpost?postId=%s&error=%s" % (postId, error)) if body == "": error = "You must enter new content." self.redirect("/editpost?postId=%s&error=%s" % (postId, error)) else: if q: q.title = title q.body = body q.put() error = "Updated post." self.redirect("/focus?postId=%s&error=%s" % (postId, error)) else: error = "error updating post" self.redirect("/focus?postId=%s&error=%s" % (postId, error)) else: error = "You must be author to edit." self.redirect("/focus?postId=%s&error=%s" % (postId, error)) else: error = "Please signup and login to edit posts." self.redirect("/focus?postId=%s&error=%s" % (postId, error))
def testRenderingBlogEntriesWithMarkdown(self): self.assertEqual(0, BlogEntry.all().count()) BlogEntry( title='asdsad', text='Hello Markdown\n' + '==\n' + '\n' + 'This is an example post using [Markdown](http://a.b).').save() self.assertEqual(1, BlogEntry.all().count()) result = IndexHandler().render() today = datetime.datetime.now().strftime('%Y-%m-%d') self.assertRegexpMatches(result, r'<[^>]+ class="title"[^>]*>asdsad</') self.assertRegexpMatches( result, r'<[^>]+ class="text"[^>]*><h1>Hello Markdown</h1>' + '[^<]*' + '<p>This is an example post using <a href="http://a.b">Markdown</a>.</p></' ) self.assertRegexpMatches(result, r'<[^>]+ class="date"[^>]*>%s</' % today)
def post(self): title = self.request.get("subject") content = self.request.get("content") cookie = self.request.cookies.get('name') user = check_login(cookie) if title and content and user: blog_post = BlogEntry(title=title, content=content, creator=user) blog_post.put() post_id = blog_post.key.id() self.redirect("/blog/%s" % post_id) else: error = "You must include both a title and content" self.render("/newpost.html", title=title, content=content, error=error, user=user)
def get(self): # GET ALL BLOG POSTS TO LIST THEM posts = BlogEntry.all().order('-created') # get any error messages from get request error = self.request.get("error") self.render("login.html", error=error, posts=posts)
def get_context_data(self, **kwargs): """ add recent blog entries """ context = super(HomeView, self).get_context_data(**kwargs) context['blogs'] = [entry for entry in BlogEntry.all_recent()] return context
def blog_update(blog_id): query = BlogEntry.getAll() query = BlogEntry.addBlogIdFilter(query, blog_id) blog_entry = query.one() if not blog_entry.username == session['username']: return abort(401) need_update = False headline = request.form.get('headline', blog_entry.headline) if headline != blog_entry.headline: blog_entry.headline = headline need_update = True payload = request.form.get('payload', blog_entry.payload) if payload != blog_entry.payload: blog_entry.changePayload(payload) need_update = True new_tags = set() str_new_tags = request.form.get('tags', 'Untagged') if not str_new_tags: str_new_tags = 'Untagged' for tag in str_new_tags.split(','): new_tags.add(tag.rstrip().lstrip()) old_tags = set(t.name for t in blog_entry.tags) if new_tags != old_tags: blog_entry.tags = [] for tag in new_tags: blog_entry.addTag(tag) need_update = True if need_update: blog_entry.updateModifiedDate() db.session.add(blog_entry) db.session.commit() return redirect('/blog/by/id/%s' %(blog_entry.id))
def blog_by_name(name): query = BlogEntry.getAll() query = BlogEntry.addNameFilter(query, name) query = query.paginate(1, per_page=max_per_page) if 'page' in request.path: endpoint = request.path.rsplit('/', 1)[0] else: endpoint = os.path.join(request.path, 'page') g.session = session g.paginate = query g.endpoint = endpoint g.blog_name = config.blog_name g.title = '%s' %(g.paginate.items[0].name) g.blog_subtitle = config.blog_subtitle g.tags = get_used_tags() return render_template('child.html', g=g)
def post(self, *args): form = BlogEntryForm(data=self.request.POST) if form.is_valid(): shop = db.get(self.request.get('shop')) if self.request.get('key'): entry = db.get(self.request.get('key')) entry.shop = shop entry.title = self.request.get('title') entry.body = self.request.get('body') else: entry = BlogEntry(user = users.get_current_user(), shop = shop, title = self.request.get('title'), body = self.request.get('body'), ) entry.put() self.redirect('/blog') else: shops = Shop.all().order('area') template_vars = { 'shops': shops, 'form': form } self.render_response('blog/blog_edit.html', template_vars)
def get_context_data(self, **kwargs): """ fetch the blog that is about to be deleted """ context = super(DeleteBlogEntryView, self).get_context_data(**kwargs) blog = BlogEntry.get_blog(self.kwargs['key']) if not blog: raise Http404 context['blog'] = blog return context
def get_context_data(self, **kwargs): """ add recent blog entries """ context = super(ViewBlogEntryView, self).get_context_data(**kwargs) blog = BlogEntry.get_blog(kwargs['key']) if not blog: raise Http404 context['blog'] = blog return context
def blog_by_date(year=None, month=None, day=None, page=None): if page is None: page = 1 query = BlogEntry.getAll() if all((year is not None, month is not None, day is not None)): query = BlogEntry.addCreationDayFilter(query, year, month, day) elif all((year is not None, month is not None)): query = BlogEntry.addCreationMonthFilter(query, year, month) elif year is not None: query = BlogEntry.addCreationYearFilter(query, year) query = query.paginate(page, per_page=max_per_page) if 'page' in request.path: endpoint = request.path.rsplit('/', 1)[0] else: endpoint = os.path.join(request.path, 'page') g.session = session g.paginate = query g.BlogEntry = BlogEntry g.tags = get_used_tags() g.endpoint = endpoint g.blog_name = config.blog_name bf = 'Blog for' if year is not None: what = '/'.join(map(lambda x: str(x), filter(None, (g.year, g.month, g.day)))) else: what = '' g.title = '%s %s' %(bf, what) g.blog_subtitle = config.blog_subtitle return render_template('child.html', g=g)
def blog_by_tag(tag, page=None): if page is None: page = 1 query = BlogEntry.getAll() query = BlogEntry.addTagFilter(query, tag) query = query.paginate(page, per_page=max_per_page) if 'page' in request.path: endpoint = request.path.rsplit('/', 1)[0] else: endpoint = os.path.join(request.path, 'page') g.session = session g.paginate = query g.endpoint = endpoint g.blog_name = config.blog_name g.title = 'Blog for %s' %(tag) g.blog_subtitle = config.blog_subtitle g.tags = get_used_tags() return render_template('child.html', g=g)
def get(self, post_id): blog_post = BlogEntry.get_by_id(int(post_id)) comments = Comment.query(Comment.parent_post == post_id).fetch() user_name_cookie = self.request.cookies.get('name') user = check_login(user_name_cookie) if blog_post: self.render("permalink.html", blog_post=blog_post, post_id=post_id, comments=comments, user=user) else: self.error(404) return
def get(self, post_id): blog_post = BlogEntry.get_by_id(int(post_id)) if not blog_post: self.error(404) return user_name_cookie = self.request.cookies.get("name") user = check_login(user_name_cookie) if not user: self.redirect("/login") elif blog_post.creator != user: self.error(403) self.render("/blog.html", user=user, error="May only delete your own posts") else: blog_post.key.delete() self.render("/deleted.html")
def get(self): user_id = None # AUTHENTICATE check for valid cookie user_id = auth(self.request.cookies.get('user_id')) # get the blog post id from the get request postId = self.request.get("postId") if user_id: q = BlogEntry.get_by_id(int(postId)) title = q.title body = q.body self.render("comment.html", title=title, body=body, postId=postId) else: error = "Please signup and login to edit comments." # if you are not logged in, you must sign up and login. self.redirect("/focus?postId=%s&error=%s" % (postId, error))
def get(self, post_id): blog_post = BlogEntry.get_by_id(int(post_id)) if not blog_post: self.error(404) return title = blog_post.title content = blog_post.content user_name_cookie = self.request.cookies.get('name') user = check_login(user_name_cookie) if not user: self.error(401) self.redirect("/login") elif blog_post.creator != user: self.render("/blog.html", user=user, error="May only edit your own posts") else: self.render("/editpost.html", title=title, content=content)
def post(self, post_id): title = self.request.get("subject") content = self.request.get("content") cookie = self.request.cookies.get("name") user = check_login(cookie) if title and content and user: blog_post = BlogEntry.get_by_id(int(post_id)) blog_post.title = title blog_post.content = content blog_post.creator = user blog_post.put() self.redirect("/blog/%s" % post_id) else: error = "You must include both a title and content" self.render("/editpost.html", title=title, content=content, error=error)
def test_comments_logic(self): """ Verify that comments are closed as expected """ pub_state = BloggingSettings.PUBLISHED_ENTRY_STATES[0] # Create a published entry, set 'comments_allowed' off: entry = BlogEntry( slug='test-comments-entry', headline='Headline TKTK', intro='Loren ipsum...', author=Author.objects.all()[0], #any author is fine... status=pub_state, allow_comments=False ) entry.save() self.assertTrue(entry.allow_comments == False) entry.allow_comments = True entry.save() self.assertTrue(entry.comments_enabled) # Now set date to just before BloggingSettings.DAYS_COMMENTS_OPEN: pd = entry.pub_date - timedelta(BloggingSettings.DAYS_COMMENTS_OPEN + 1) entry.pub_date = pd entry.save() self.assertTrue(entry.comments_enabled == False)
def get(self): commentId = None user_id = None # AUTHENTICATE check for valid cookie user_id = auth(self.request.cookies.get('user_id')) commentId = self.request.get("commentId") postId = self.request.get("postId") q = BlogEntry.get_by_id(int(postId)) k = q.key() # must be logged in if user_id: commentId = int(commentId) comment = Comments.get_by_id(commentId, parent=k) # must be the author to edit the comment if user_id == comment.author_id: c = Comments.get_by_id(commentId, parent=k) if c: comment = c.comment created = c.created author_id = c.author_id u = Users.get_by_id(int(author_id)) user_name = u.userName self.render("edit-comment.html", author=user_name, comment=comment, created=created, commentId=commentId, postId=postId) else: error = "error" self.redirect("/focus?postId=%s&error=%s" % (postId, error)) else: error = "You must be the author to edit the comment." self.redirect("/focus?postId=%s&error=%s" % (postId, error)) else: error = "You must be loggen in to edit the comment." self.redirect("/focus?postId=%s&error=%s" % (postId, error))
def get(self, post_id): blog_post = BlogEntry.get_by_id(int(post_id)) if not blog_post: self.error(404) return user_name_cookie = self.request.cookies.get("name") user = check_login(user_name_cookie) if not user: self.redirect("/login") elif blog_post.creator == user: self.error(403) self.render("/blog.html", user=user, error="Cannot like your own posts") elif user in blog_post.liked: self.render("/blog.html", user=user, error="May only like a post one time") else: blog_post.liked.append(user) blog_post.put() self.redirect("/blog/" + post_id)
def post(self): # AUTHENTICATE user_id = None # AUTHENTICATE check for valid cookie user_id = auth(self.request.cookies.get('user_id')) u = Users.get_by_id(int(user_id)) user_name = u.userName if user_id: comment = None comment = self.request.get("comment") postId = self.request.get("postId") q = BlogEntry.get_by_id(int(postId)) if comment: if comment != "": c = Comments(parent=q, comment=comment, author_id=user_id, author_name=user_name) c.put() error = "Comment saved." self.redirect( "/focus?postId=%s&error=%s&user_name=%s" % (postId, error, user_name)) else: error = "Please add content for the comment or cancel." self.redirect( "/comment?postId=%s&error=%s&user_name=%s" % (postId, error, user_name)) else: error = "Please add a comment." # must include all the parameters below to preserve user # entered data self.redirect( "/comment?postId=%s&error=%s&user_name=%s" % (postId, error, user_name)) else: error = "Please signup and login to add a comment." self.redirect("/focus?postId=%s&error=%s&user_name=%s" % (postId, error, user_name))
def get(self): user_id = None u = None error = "" post = "" # GET ALL BLOG POSTS TO LIST THEM try: posts = BlogEntry.all().order('-created') except: pass # AUTHENTICATE: check for valid cookie user_id = auth(self.request.cookies.get('user_id')) if user_id: try: # check db to verify that the username exists even though \ # browser has a cookie. Maybe this user was deleted from the\ # db by the admin. u = Users.get_by_id(int(user_id)) except: pass if u: user_name = u.userName try: error = self.request.get("error") except: pass self.render("blogMain.html", user_name=user_name, posts=posts, error=error) else: # if user is NOT in the db error = "Could not verify username." self.redirect("/login?error=%s" % error) else: error = "Please log in." self.redirect("/login?error=%s" % error)
def get(self): user_id = None # AUTHENTICATE check for valid cookie user_id = auth(self.request.cookies.get('user_id')) postId = self.request.get("postId") if user_id: try: u = Users.get_by_id(int(user_id)) q = BlogEntry.get_by_id(int(postId)) except: pass if q: title = q.title body = q.body created = q.created last_mod = q.last_mod author = q.author_id k = q.key() try: comments = Comments.all().ancestor(k) except: pass # if user is the author then ok to edit if user_id == author: self.render("edit-post.html", body=body, title=title, postId=postId) else: error = "You must be author to edit." self.redirect("/focus?postId=%s&error=%s" % (postId, error)) else: error = "Please signup and login to edit posts." self.redirect("/focus?postId=%s&error=%s" % (postId, error))
def make_feed(): feed = Feed() feed.feed["title"] = app.config['FEED_TITLE'] feed.feed["link"] = app.config['FEED_LINK'] feed.feed["author"] = app.config['FEED_AUTHOR'] feed.feed["description"] = app.config['FEED_DESC'] entries = BlogEntry.select().order_by(('date', 'desc'), ).paginate(0, app.config['FEED_ITEMS']) for post in entries: item = {} item["title"] = post.title item["link"] = post.link item["description"] = post.summary item["pubDate"] = post.date.utctimetuple() item["guid"] = post.eid feed.items.append(item) return feed
def get(self): entries = BlogEntry.all().order('-updated_at') template_vars = { 'object_list': entries } self.render_response('blog/blog_list.html', template_vars)
def index(): entries = BlogEntry.select().order_by(('date', 'desc'), ).paginate(0, 20) return render_template('index.html', sorted_entries=entries)
def save_post(request, idee): if request.method == 'POST': submit_names = ('save', 'publish', 'quit') submit = [i for i in request.POST if i in submit_names][0] author = request.user form = BlogEntryForm(request.POST) if form.is_valid(): if idee: entry = get_object_or_404(BlogEntry, pk=idee, author=author) entry.title = form.cleaned_data['title'] entry.content = form.cleaned_data['content'] entry.updated = entry.updated.now() else: entry = BlogEntry(author=author) entry.title=form.cleaned_data['title'] entry.name = flatten(entry.title) + '.html' entry.content = form.cleaned_data['content'] # We need a pk before settings tag_names below entry.save() Tag.objects.update_tags(entry, form.cleaned_data['tags']) if submit == "publish": entry.published = True entry.posted = datetime.now() entry.save() return HttpResponseRedirect(reverse('index')) elif submit == "save": entry.save() return render_to_response('edit_post.html', {'form': form, 'entry': entry}) else: entry.save() return HttpResponseRedirect(reverse('admin')) elif submit == "quit": return HttpResponseRedirect(reverse('admin')) else: form = BlogEntryForm() return render_to_response('edit_post.html', {'form': form})
def form_valid(self, form): """ save the blog and delegate back up to formview for the redirect """ BlogEntry.put_blog(self.request.user,form.cleaned_data['title'],form.cleaned_data['body']) return super(AddBlogEntryView, self).form_valid(form)
def form_valid(self, form): """ save the blog and delegate back up to formview for the redirect """ BlogEntry.delete_blog(form.cleaned_data['key']) return super(DeleteBlogEntryView, self).form_valid(form)
def get(self): user_id = None # AUTHENTICATE check for valid cookie user_id = auth(self.request.cookies.get('user_id')) if user_id: # get the logged in user try: u2 = Users.get_by_id(int(user_id)) except: pass if u2: # get the username NOT the id user_name = u2.userName postId = self.request.get("postId") error = self.request.get("error") q = None # querie BlogEntry for the blog entity filtered by title try: q = BlogEntry.get_by_id(int(postId)) title = q.title body = q.body created = q.created last_mod = q.last_mod author_id = q.author_id k = q.key() except: pass if q: # get the user who is the author of the blogpost try: u = Users.get_by_id(int(author_id)) except: pass if u: # get the authors username NOT id author = u.userName comments = None # get all comments for this blogpost try: comments = Comments.all().ancestor(k) except: pass # if there are no comments.... if not comments: commentError = "No comments" else: commentError = "" else: error = "Could not access the blog post." self.redirect("/welcome?error=%s" % error) # count likes in the database for display, all relevant likes are\ # ancestors of the blog post with title count = 0 likes = None try: likes = Likes.all().ancestor(k) except: pass if likes: # iterate through all likes for this post to count them for like in likes: if like.user_id: count += 1 self.render("focus.html", postId=postId, title=title, body=body, created=created, last_mod=last_mod, author=author, comments=comments, error=error, count=count, commentError=commentError, user_name=user_name) else: self.redirct("/login")
def post(self): def render_focus(title, body, created, last_mod, author, comments, count, error, postId, user_name): self.render("focus.html", title=title, body=body, created=created, last_mod=last_mod, author=author, comments=comments, count=count, error=error, postId=postId, user_name=user_name) postId = self.request.get("postId") user_id = None # AUTHENTICATE check for valid cookie user_id = auth(self.request.cookies.get('user_id')) # get the logged in user to get username if user_id: try: u = Users.get_by_id(int(user_id)) except: pass if u: user_name = u.userName # query for the usual blogPost entity properties try: q = BlogEntry.get_by_id(int(postId)) if q: title = q.title body = q.body created = q.created last_mod = q.last_mod author = u.userName author_id = q.author_id # k is the key to the blog post. k = q.key() except: pass try: # get all comments for for the blogpost - that means get # all comments who are ancestors of K (the blogpost). comments = Comments.all().ancestor(k) except: pass # check if user has already liked this post # all Likes have a user_id property which corresponds to the # User who LIKED the post, so query Likes filtered by user_id # to get ALL the likes for this user try: z = Likes.all().filter("user_id =", user_id) except: pass # then get the ONE (if theres is one) that is an ancestor # of the blog post if z: try: alreadyLiked = z.ancestor(k).get() except: pass # set flag default = go flag = "go" # if there are ZERO likes in the db, you'll get an error bc # the query gets nothing. To prevent the error, use try/except try: if alreadyLiked.user_id: flag = "nogo" except: pass # initialize the counter count = 0 # If the logged in user is the author then error if user_id == author_id: # repaint page likes = Likes.all().ancestor(k) count = 0 for like in likes: try: if like.user_id: count += 1 except: pass error = "You can't like your own posts." render_focus(title, body, created, last_mod, author, comments, count, error, postId, user_name) else: # if the logged in user has already liked this post then error if flag == "nogo": error = "Stop it....You already liked this post." likes = Likes.all().ancestor(k) count = 0 if likes: for like in likes: if like.user_id: count += 1 # repaint page render_focus(title, body, created, last_mod, author, comments, count, error, postId, user_name) else: # if tests are passed....record the LIKE; # record the userIDKEY in LIKES as a CHILD of the BLOGPOST # increment the like so it updates the display (not the db) # record like in the db - user_id is the only property and # it's ancestor is the blogpost k. try: l = Likes(parent=k, user_id=user_id) except: pass if l: l.put() error = "The Like was recorded." # count ALL the existing LIKES to update display \ # on VIEW post # filter by ancestor bc ALL likes are recorded as an \ # ancestor of ONE blogPost likes = Likes.all().ancestor(k) count = 0 if likes: for like in likes: if like.user_id: count += 1 # repaint page render_focus(title, body, created, last_mod, author, comments, count, error, postId, user_name) else: error = "Please signup and login to like a post." # if you are not logged in, you must sign up and login. self.redirect("/focus?postId=%s&error=%s" % (postId, error))