def post(self, channel): update = json.loads(self.request.body.decode('UTF-8')) channel_id = yield Op(self.channels.save, update) channel = yield Op(self.channels.find_one, channel_id) self.write(json.dumps(channel)) self.finish()
def post(self): new_maraphone = json.loads(self.request.body.decode('UTF-8')) maraphone_id = yield Op(self.maraphones.insert(new_maraphone)) maraphone = yield Op(self.maraphones.find_one(maraphone_id)) self.write(json.dumps(maraphone_id))
def get(self): live = self.get_argument('live', False) main_channels = self.channels.find({'main': True}).sort('order') if live: other_channels = self.channels.find({'main': False, 'live': True}) else: other_channels = self.channels.find({'main': False}) main_channels = yield Op(main_channels.to_list) other_channels = yield Op(other_channels.to_list) main_live_count = yield Op( self.channels.find({ 'main': True, 'live': True }).count) other_live_count = yield Op( self.channels.find({ 'main': False, 'live': True }).count) chanlist = { 'main': main_channels, 'other': other_channels, '_meta': { 'main_live': main_live_count, 'other_live': other_live_count } } self.write(json.dumps(chanlist)) self.finish()
def post(self): channel = json.loads(self.request.body.decode('UTF-8')) channel_id = yield Op(self.channels.insert, channel) channel = yield Op(self.channels.find_one, channel_id) self.write(json.dumps(channel)) self.finish()
def get(self, tag, page=1): @tornado.gen.engine def find_comments(post, callback): post['comments'] = yield Op( self.db.comments.find({ 'postid': post['_id'] }).to_list) callback(post) page = int(page) posts = yield Op( self.db.posts.find({ 'tags': tag, 'status': 'published' }).sort('date', -1).skip( (page - 1) * options.page_size_posts).limit( options.page_size_tag_posts).to_list) if not len(posts): raise tornado.web.HTTPError(404) for post in posts: find_comments(post, (yield tornado.gen.Callback(post['_id']))) posts = yield tornado.gen.WaitAll([post['_id'] for post in posts]) total = yield Op( self.db.posts.find({ 'tags': tag, 'status': 'published' }).count) self.render('tag.html', tag=tag, posts=posts, total=total, page=page, page_size=options.page_size_tag_posts)
def get(self, comment_id): comment = yield Op(self.db.comments.find_one, {'_id': ObjectId(comment_id)}) if not comment: raise tornado.web.HTTPError(404) post = yield Op(self.db.posts.find_one, {'_id': comment['postid']}) self.render('deletecomment.html', post=post, comment=comment)
def post(self, comment_id): comment = yield Op(self.db.comments.find_one, {'_id': ObjectId(comment_id)}, {'postid': 1}) if not comment: raise tornado.web.HTTPError(404) post = yield Op(self.db.posts.find_one, {'_id': comment['postid']}) yield Op(self.db.comments.remove, {'_id': ObjectId(comment_id)}) self.redirect('/post/%s' % post['slug'])
def post(self): newsflash = json.loads(self.request.body) result_id = yield Op(self.news.insert, newsflash) result = yield Op(self.news.find_one(result_id)) self.write(json.dumps(result)) self.finish()
def post(self, id): post = json.loads(self.request.body) post["_id"] = ObjectId(post["_id"]) result_id = yield Op(self.news.save, post) result = yield Op(self.news.find_one, result_id) self.write(json.dumps(result)) self.finish()
def render(self, template_name, **kwargs): @tornado.gen.engine def find_post(comment, callback): comment['post'] = yield Op(self.db.posts.find_one, {'_id': comment['postid']}) callback(comment) posts = yield Op( self.db.posts.find({ 'status': 'published' }).sort('date', -1).limit(options.recent_posts_limit).to_list) comments = yield Op(self.db.comments.find().sort('date', -1).limit( options.recent_comments_limit).to_list) for comment in comments: find_post(comment, (yield tornado.gen.Callback(comment['_id']))) comments = yield tornado.gen.WaitAll( [comment['_id'] for comment in comments]) tags = yield Op(self.db.posts.aggregate, [{ '$match': { 'status': 'published' } }, { '$unwind': '$tags' }, { '$group': { '_id': '$tags', 'sum': { '$sum': 1 } } }, { '$limit': options.tag_cloud_limit }]) kwargs.update({ 'current_user': (yield tornado.gen.Task(self.get_current_user_async)), 'url_path': self.request.uri, '_next': self.get_argument('next', ''), '_posts': posts, '_comments': comments, 'opts': opts, 'options': options, 'forms': forms, '_tags': tags['result'] }) super(BaseHandler, self).render(template_name, **kwargs)
def login(self, username, password): user = yield Op(self.users.find_one, username) if user: if hashlib.sha256( password.encode('ASCII')).hexdigest() == user['password']: session = yield Op(self.sessions.insert, {'user': username}) self.set_secure_cookie('user_token', str(session)) del user['password'] return user else: return False else: return False
def post(self, comment_id): comment = yield Op(self.db.comments.find_one, {'_id': ObjectId(comment_id)}, {'postid': 1}) if not comment: raise tornado.web.HTTPError(404) yield Op(self.db.comments.update, {'_id': ObjectId(comment_id)}, { '$set': { 'name': self.get_argument('name'), 'email': self.get_argument('email'), 'content': self.get_argument('content') } }) post = yield Op(self.db.posts.find_one, {'_id': comment['postid']}) self.redirect('/post/%s' % post['slug'])
def get_current_user(self): token = self.get_secure_cookie('user_token') if token: session = yield Op(self.sessions.find_one, ObjectId(token.decode('UTF-8'))) if session: user = yield Op(self.users.find_one, session['user']) if user: return user else: return False else: return False
def get(self, slug_post): post = yield Op(self.db.posts.find_and_modify, { 'slug': slug_post, 'status': 'published' }, update={'$inc': { 'views': 1 }}, new=True) if not post: raise tornado.web.HTTPError(404) comments = yield Op( self.db.comments.find({ 'postid': post['_id'] }).to_list) older = None newer = None older_cursor = self.db.posts.find({ '_id': { '$lt': post['_id'] }, 'status': 'published' }).sort('date', -1).limit(1) newer_cursor = self.db.posts.find({ '_id': { '$gt': post['_id'] }, 'status': 'published' }).sort('date', 1).limit(1) while (yield older_cursor.fetch_next): older = older_cursor.next_object() while (yield newer_cursor.fetch_next): newer = newer_cursor.next_object() older = None if older.count() == 0 else older[0] newer = None if newer.count() == 0 else newer[0] data = {} if self.current_user: data.update({ 'name': self.current_user['full_name'], 'email': self.current_user['email'] }) comment_form = forms.CommentForm(locale_code=self.locale.code, **data) self.render('post.html', post=post, comments=comments, older=older, newer=newer, form_message=None, comment_form=comment_form)
def post(self, comment_id, action): if action not in ['like', 'dislike']: raise tornado.web.HTTPError(404) comment_id = ObjectId(comment_id) comment = yield Op(self.db.comments.find_and_modify, {'_id': comment_id}, fields={'postid': 1}, update={'$inc': { action + 's': 1 }}, new=True) if not comment: raise tornado.web.HTTPError(404) post = yield Op(self.db.posts.find_one, {'_id': comment['postid']}) self.redirect('/post/%s' % post['slug'])
def remove(self, collection, **kwargs): ''' remove records from collection whose parameters match kwargs ''' callback = kwargs.pop('callback') yield Op(self.db[collection].remove, kwargs) callback()
def create_token(self, email, ip=None, expire=None, token_size=64, retval=None): ''' Generate a token of a given length, tied to email address, and store it. Optionally store ip address, expiration (in days), and retval (see set_retval for additional information on this). Return the token. ''' token = ''.join( choice(ascii_letters + digits) for x in range(token_size)) payload = {'email': email.lower(), 'token': token} if ip: payload.update(ip=ip) if expire: expire = (datetime.now() + timedelta(days=expire)).strftime('%s') payload.update(expire=expire) yield Op(self.db.tokens.insert, payload) if retval: yield Task(self.set_retval, email, retval) raise Return(token)
def get(self): news_cursor = self.news.find().sort('$natural', -1).limit(10) news = yield Op(news_cursor.to_list) self.write(json.dumps(news)) self.finish()
def auth_token(self, email, token, ip=None): ''' Return True if email address and token match. If IP exists, also verify that. If expiration was set when create_token was called, verify that the token hasn't expired. If for any reason the token is not valid, remove it. ''' criteria = {'email': email.lower(), 'token': token} if ip: criteria.update(ip=ip) data = yield Op(self.db.tokens.find_one, criteria) if not data: raise Return(False) token_ip = data.get('ip', None) if token_ip is not None and token_ip != ip: raise Return(False) token_expire = data.get('expire', None) if token_expire is not None and \ token_expire < datetime.now().strftime('%s'): yield Task(self.remove_token, token, email) raise Return(False) retval = yield Task(self.fetch_retval, email) if retval is None: raise Return(True) else: raise Return(retval)
def post(self, slug): post = yield Op(self.db.posts.find_one, {'slug': slug}) if not post: raise tornado.web.HTTPError(404) self.db.comments.remove({'postid': post['_id']}) self.db.posts.remove({'slug': slug}) self.redirect(self.reverse_url('posts'))
def post(self): user = yield Op(self.db.users.find_one, {'email': self.form.data['email']}) if user: reset_hash = helpers.generate_md5() user = yield Op(self.db.users.find_and_modify, {'email': self.form.data['email']}, {'$set': {'reset_hash': reset_hash, 'enabled': True}, '$unset': {'join_hash': 1}}, new=True) yield tornado.gen.Task(self.smtp.send, constants.RESET_PASSWORD, 'newpassword.html', user["email"], {'user': user}) self.redirect(self.reverse_url('home')) return self.render('newpassword.html', message=constants.USER_IS_NOT_EXIST, form=self.form)
def get(self): title = self.get_argument('title', '') title_filter = re.compile('.*%s.*' % title, re.IGNORECASE) posts = yield Op( self.db.posts.find({ 'title': title_filter }).sort('date', -1).to_list) self.render("posts.html", title=title, posts=posts)
def remove_token(self, email, token): ''' Remove token from Moth ''' yield Op(self.db.tokens.remove, { 'email': email.lower(), 'token': token })
def setup_fts(self): # TODO: Should be used with a sync db connection. if opts.db_use_fts: try: yield Op(self.db.connection.admin.command, SON([('getParameter', 1), ('textSearchEnabled', 1)]))['textSearchEnabled'] yield Op(self.db.posts.ensure_index, [('plain_content', 'text')]) except: opts.db_use_fts = False logging.warning( 'Full text search is probably not activated ' 'on MongoDB server, If you want to activated it, use 2.4 ' 'version and issue the following command on admin ' 'database:\n db.runCommand({ setParameter: 1, ' 'textSearchEnabled: true })')
def get(self): page = int(self.get_argument('page', 0)) maraphones_cursor = self.maraphones.find().skip(page*10).limit(10) maraphones = yield Op(maraphones_cursor.to_list) maraphones_count = yield Op(self.maraphones.count) response = { 'maraphones': maraphones, '_meta': { 'count': maraphones_count, 'offset': 10 } } self.write(json.dumps(maraphones)) self.finish()
def fetch_retval(self, email): ''' If retval exists, return it. If it doesn't, return True. ''' result = yield Op(self.db.retvals.find_one, {'email': email.lower()}) if result is None: raise Return(None) else: raise Return(result.get('retval', True))
def get(self, slug): post = yield Op(self.db.posts.find_one, {'slug': slug}) if not post: raise tornado.web.HTTPError(404) post['tags'] = ','.join(post['tags']) form = forms.PostForm(locale_code=self.locale.code, status_choices=opts.STATUSES, text_type_choices=opts.get_allowed_text_types(), **post) self.render("editpost.html", form=form)
def post(self): slug_flag = self.get_argument('slug', False) if slug_flag: slug = self.get_argument('customslug', '') else: slug = helpers.get_slug(self.get_argument('title'), stop_words=options.slug_stop_words) html_content, plain_content = helpers.get_html_and_plain( self.get_argument('content'), self.get_argument('text_type')) post = { 'title': self.get_argument('title'), 'slug': slug, 'date': datetime.datetime.now(), 'tags': helpers.remove_duplicates(self.get_argument('tags')), 'text_type': self.get_argument('text_type'), 'content': self.get_argument('content'), 'html_content': html_content, 'plain_content': plain_content, 'status': self.get_argument('status'), 'text_type': self.get_argument('text_type'), 'author': self.current_user['name'], 'email': self.current_user['email'], 'votes': 0, 'views': 0 } existing_post = yield Op(self.db.posts.find_one, {'slug': slug}, {'_id': 1}) if existing_post: self.render('newpost.html', message=('There are already an ' 'existing post with this title or slug.'), post={}, new=True) return yield Op(self.db.posts.insert, post) if post['status'] == 'published': self.redirect('/post/%s' % post['slug']) else: self.render('newpost.html', message=self.form.errors, form=self.form)
def store(self, collection, **kwargs): ''' validate the passed values in kwargs based on the collection, store them in the mongodb collection ''' callback = kwargs.pop('callback') key = validate(collection, **kwargs) data = yield Task(self.fetch, collection, **{key: kwargs[key]}) if data is not None: raise Proauth2Error('duplicate_key') yield Op(self.db[collection].insert, kwargs) callback()
def set_retval(self, email, retval): ''' Store retval associated with the email address. When ``auth_token`` is called, if the authentication was successful, and a retval exists, it will be returned by the auth_token call. If retval does not exist, auth_token returns True. ''' yield Op(self.db.retvals.update, {'email': email.lower()}, { 'email': email.lower(), 'retval': retval }, upsert=True)