def post_article_password(self): """Validate the password of locked article. """ logger.info("post_article_password") name = self.parse_post_name(self.get_argument('name', default='', strip=True)) password = self.get_argument('password', strip=True) logger.debug('post_article_password for name {}, password {}' .format(name, password)) post = yield ArticlesModel.get({'post_name': name}) if not post: self.set_status(202, 'Post name not exists.') self.write_json(msg='post_name 不存在', status=ERROR) self.finish() return elif password != post['post_password']: self.set_status(202, 'Password wrong.') self.write_json(msg='密码错误', status=ERROR) self.finish() return cookie_name = self.get_cookie_name(name) self.set_secure_cookie(cookie_name, password, expires_days=None) self.write_json(msg='ok')
def post(self, url): logger.info('POST UserHandler %s', url) router = { 'api/user/login': self.login_api, } router.get(url, self.redirect_404)()
def list(self): logger.info('TweetsAPIHandler list') try: truncate = int(self.get_argument('truncate', default='300', strip=True)) topic = self.get_argument('topic', default=None, strip=True) assert(truncate >= 0) except (ValueError, AssertionError) as err: logger.exception(err) self.http_400_bad_request(err=err) return if topic: select = {'topics': topic} else: select = None cursor = self.get_cursor(select) if not cursor: return posts = [] while (yield cursor.fetch_next): docu = cursor.next_object() parsed_docu = self.parse_docu( docu, truncate=truncate ) posts.append(parsed_docu) col = self.get_col() total = yield col.count() self.success(posts, total=total)
def main(): opt.parse_command_line() try: tornado.platform.asyncio.AsyncIOMainLoop().install() except AttributeError: # this method in tornado is deprecated after python 3.4 pass ioloop = asyncio.get_event_loop() http_server = tornado.httpserver.HTTPServer(Application(), xheaders=True) http_server.listen(options.port) if options.debug: logger.info('start application in debug mode localhost:%s', options.port) logger.setLevel(logging.DEBUG) else: logger.info('start application in normal mode localhost:%s', options.port) if not options.debug: setup_tasks(ioloop) ioloop.run_forever()
def list(self): logger.info('TweetsAPIHandler list') try: truncate = int( self.get_argument('truncate', default='300', strip=True)) topic = self.get_argument('topic', default=None, strip=True) assert (truncate >= 0) except (ValueError, AssertionError) as err: logger.exception(err) self.http_400_bad_request(err=err) return if topic: select = {'topics': topic} else: select = None cursor = self.get_cursor(select) if not cursor: return posts = [] while (yield cursor.fetch_next): docu = cursor.next_object() parsed_docu = self.parse_docu(docu, truncate=truncate) posts.append(parsed_docu) col = self.get_col() total = yield col.count() self.success(posts, total=total)
def patch(self, url): """Update existed article """ logger.info('PATCH PostsHandler for url {}'.format(url)) router = { 'api/posts/amend': self.patch_article, } router.get(url)()
def get_post_by_keyword(self): logger.info('GET get_post_by_keyword') keyword = self.get_argument('keyword', strip=True) logger.debug('GET get_post_by_keyword for keyword {}'.format(keyword)) q = 'https://cse.google.com/cse/publicurl?cx=004733495569415005684:-c6y46kjqva&q={keyword}' self.redirect(q.format(keyword=keyword, permanent=True))
def post(self, url=None, *args, **kw): logger.info('POST PostsHandler {}'.format(url)) router = { 'api/posts/post-article-password': self.post_article_password, 'api/posts/publish': self.post_new_article, } router.get(url, self.redirect_404)(*args, **kw)
def get(self, url): logger.info('GET UserHandler %s', url) router = { 'login': self.login_page, 'profile': self.profile, 'api/user/ramjet-login': self.ramjet_login, } router.get(url, self.redirect_404)()
def get_amend_post(self): post_name = self.get_argument('post-name', strip=True) post_name = urllib.parse.quote(post_name) logger.info('get_amend_post with post_name {}'.format(post_name)) post = yield self.db.posts.find_one({'post_name': post_name}) post = unquote_fr_mongo(post) if not post: raise tornado.httpclient.HTTPError(406, 'post-name not exists') self.render2('amend/index.html', post=post) self.finish()
def update_posts_categories(cls, postid_category_map): """ Args: postname_category_map (dict): {post_id: category_id} """ logger.info('CategoriesModel.update_posts_categories') for post_id, cate in postid_category_map.items(): r = yield cls.collection.update_one( {'_id': cls.oid(post_id)}, {'$set': {'category': cls.oid(cate)}}, upsert=False ) logger.debug('update post %s category to %s for %s', post_id, cate, r.modified_count)
def get(self, url=None, *args, **kw): logger.info('GET PostsHandler {}'.format(url)) router = { 'archives': self.get_post_by_page, # 按页数获取文章 'search': self.get_post_by_keyword, # 按关键词搜索 'publish': self.get_new_post, # 发表新文章 'p': self.get_post_by_name, # 单篇文章的页面 'api/posts/keywords': self.get_post_keywords, 'api/posts/get-amend-post': self.get_amend_post, # 编辑文章 'rss': self.get_rss, # 获取订阅 'api/posts/get-post-by-page': self.get_post_by_page, } router.get(url, self.redirect_404)(*args, **kw)
def update_posts_categories(cls, postid_category_map): """ Args: postname_category_map (dict): {post_id: category_id} """ logger.info('CategoriesModel.update_posts_categories') for post_id, cate in postid_category_map.items(): r = yield cls.collection.update_one( {'_id': cls.oid(post_id)}, {'$set': { 'category': cls.oid(cate) }}, upsert=False) logger.debug('update post %s category to %s for %s', post_id, cate, r.modified_count)
async def retrieve(self, oid): logger.info('retrieve {} for oid {}' .format(self._collection, oid)) col = self.get_col() oidname = self.get_oidname() try: f_oid = self.parse_oid(oid) docu = await col.find_one({oidname: f_oid}) assert docu, 'article not exists!' except Exception as err: self.http_404_not_found(err=err) return parsed_docu = await self.parse_docus([docu]) if not parsed_docu: return self.success(parsed_docu[0])
def get_post_by_page(self): logger.info('GET get_post_by_page') try: page = int(self.get_argument('page', strip=True, default=1)) is_full = self.get_argument('is_full', strip=True, default=False) logger.debug('get_post_by_page for page {}'.format(page)) except ValueError as err: logger.error('when get_post_by_page: ', exc_info=err) self.finish() return skip = (page - 1) * N_POST_PER_PAGE cursor = self.db.posts.find() cursor.sort([('_id', pymongo.DESCENDING)]) \ .limit(N_POST_PER_PAGE) \ .skip(skip) posts = [] while (yield cursor.fetch_next): docu = cursor.next_object() docu = unquote_fr_mongo(docu) if not is_full: if docu.get('post_password'): docu['post_content'] = """ <div class="preview"> <span class="glyphicon glyphicon-lock" aria-hidden="true"></span> </div> """ else: docu['post_content'] = self.shortly_content(docu['post_content'], 500) posts.append(docu) # tags tags = (yield self.db.statistics.find_one( {'types': 'keyword'}, {'keywords': 1} ))['keywords'] self.render_post('archives/archives.html', posts=posts, current_page=page, tags=tags) self.finish()
def get_post_by_name(self, name): logger.info('get_post_by_name for name {}'.format(name)) name = self.parse_post_name(name) post = yield ArticlesModel.get({'post_name': name}) if not post: self.redirect_404() return if post.get('post_password'): cookie_name = self.get_cookie_name(name) cookie = self.get_secure_cookie(cookie_name) logger.debug('get cookie {}'.format(cookie)) if not cookie or cookie.decode() != post['post_password']: self.render2('archives/ajax/auth.html', post_name=post['post_name']) return post['post_type'] = post.get('post_type', 'text') self.render2('archives/article.html', post=post) self.finish()
def post_new_article(self): """Create new article.""" logger.info('post_new_article') try: post_docu = self.validate_post(create_new=True) except PostValidatorError as err: self.http_400_bad_request(err=err) self.finish() return try: yield self.db.posts.insert(post_docu) except Exception as err: logger.exception(err) self.http_400_bad_request(err=err) else: self.write_json(msg='post new article {}' .format(post_docu['post_name'])) finally: self.finish()
def main(): opt.parse_command_line() tornado.platform.asyncio.AsyncIOMainLoop().install() ioloop = asyncio.get_event_loop() http_server = tornado.httpserver.HTTPServer(Application(), xheaders=True) http_server.listen(options.port) if options.debug: logger.info('start application in debug mode localhost:%s', options.port) logger.setLevel(logging.DEBUG) else: logger.info('start application in normal mode localhost:%s', options.port) if not options.debug: setup_tasks(ioloop) ioloop.run_forever()
def patch_article(self): """Update article.""" logger.info('patch_article') try: post_docu = self.validate_post(create_new=False) except PostValidatorError as err: self.http_400_bad_request(err=err) self.finish() return try: yield self.db.posts.update( {'post_name': post_docu['post_name']}, {'$set': post_docu}, ) except Exception as err: logger.exception(err) self.http_400_bad_request(err=err) else: self.write_json(msg='amend article {}' .format(post_docu['post_name'])) finally: self.finish()
def get_new_post(self): logger.info('get_new_post') self.render2('archives/publish.html') self.finish()
async def delay_task(func, *args, **kw): logger.info('delay_task for func {}'.format(str(func))) return (await executor.submit(func, **kw))