def get_categories(include_info=False): print "Getting categories" categories_collection = db.get_categories_collection() cursor = categories_collection.find() categories = [] if include_info: posts_collection = db.get_posts_collection() for category in cursor: posts_count = posts_collection.find({ 'category_id': category['_id'] }).count() categories.append({ 'id': category['_id'], 'name': category['name'], 'date': category['date'].strftime("%A, %B %d %Y at %I:%M%p"), 'created_by': category['created_by'], 'posts': posts_count }) else: categories = [category['name'] for category in cursor] return categories
def get_post_by_permalink(permalink): posts = db.get_posts_collection() post = posts.find_one({'permalink': permalink}) if post is None: return post post['date'] = post['date'].strftime("%A, %B %d %Y at %I:%M%p") post['category'] = '' if 'category_id' in post: post_category = category.get_category_by_id(post['category_id']) if post_category: post['category'] = post_category['name'] if 'tags' not in post: post['tags'] = [] if 'comments' not in post: post['comments'] = [] else: for comment in post['comments']: comment['date'] = comment['date'].strftime( "%A, %B %d %Y at %I:%M%p") return post
def insert_post(title, body, category_id, tags, author): print "Inserting post....", title posts = db.get_posts_collection() # Combine everything that isn't alphanumeric exp = re.compile('\W') whitespace = re.compile('\s') temp_title = whitespace.sub('_', title) permalink = exp.sub('', temp_title) post = { "title": title, "author": author, "body": body, "permalink": permalink, "tags": tags, "category_id": category_id, "date": datetime.utcnow() } try: result = posts.insert_one(post) print "Post inserted!", result.inserted_id except: print "Error inserting post", sys.exc_info()[0] return permalink
def insert_comment(post_permalink, comment): posts = db.get_posts_collection() posts.update({'permalink': post_permalink}, {'$push': { 'comments': comment }}, upsert=False)
def get_formatted_posts(where=None, limit=10): print "Getting posts" posts = db.get_posts_collection() cursor = posts.find(where).sort('date', direction=-1).limit(limit) formatted_posts = [] for post in cursor: print "Reading post", post['title'] if 'tags' not in post: post['tags'] = [] if 'comments' not in post: post['comments'] = [] post['category'] = '' if 'category_id' in post: post_category = category.get_category_by_id(post['category_id']) if post_category: post['category'] = post_category['name'] formatted_posts.append({ 'title': post['title'], 'body': post['body'], 'date': post['date'].strftime("%A, %B %d %Y at %I:%M%p"), 'permalink': post['permalink'], 'author': post['author'], 'tags': post['tags'], 'comments': post['comments'], 'category': post['category'], 'category_id': post['category_id'] }) return formatted_posts