Пример #1
0
 def post(self):
     header = self.get_argument("header", "")
     code = self.get_argument("code", "")
     describe = self.get_argument("describe", "")
     username = self.current_user().username
     error = False
     if self.is_admin():
         checked = 1
     else:
         checked = -1
     if header == "":
         self.messages.error("标题不能为空!")
         error = True
     if Article.num_lim(username):
         self.messages.error("文章过多,请联系管理员!")
         return self.redirect("/publish")
     elif not error and checked == 1:
         Article.new(username=username, header=header, code=code, describe=describe, checked=checked)
         self.messages.success("发表成功!")
     elif not error:
         Article.new(username=username, header=header, code=code, describe=describe, checked=checked)
         self.messages.success("等待管理员审核!")
     else:
         self.messages.warning("发表失败!")
     self.redirect("/")
Пример #2
0
    def post(self):
        if self.user:
            if 'main' in self.request.POST:
                self.redirect('/blog')
            elif 'sub' in self.request.POST:
                subject = self.request.get('subject')
                content = self.request.get('content')

                # created by someone. someone should be unique
                uid = self.read_secure_cookie('user_id')
                # if subject and content filled
                if subject and content:
                    article = Article(title=subject,
                                      text=content,
                                      likes=0,
                                      who_liked=[],
                                      created_by=uid)
                    # put the article to db
                    article.put()
                    self.redirect('/blog/%s' % str(article.key().id()))
                else:
                    # either subject or content missing
                    error = "Subject or Content is missing"
                    self.render("new_post.html",
                                title=subject,
                                text=content,
                                error=error,
                                likes=0,
                                who_liked=[],
                                created_by=uid)
        else:
            self.redirect('/blog/login')
Пример #3
0
 def post(self, *args, **kwargs):
     stype = args[0]
     if stype == "1":
         article_key = self.get_argument("theKey", "")
         user = self.current_user()
         article = Article.get_by_key(article_key)
         if article_key != "" and(user.level == 100 or user.username == article.username):
             if Article.dele_by_key(article_key):
                 Comment.dele_by_article(article_key)
                 self.write("删除成功!")
             else:
                 self.send_error(404)
         else:
             self.send_error(404)
     if stype == "2":
         comment_key = self.get_argument("theKey", "")
         user = self.current_user()
         comment = Comment.get_by_key(comment_key)
         if comment_key != "" and (user.level == 100 or user.username == comment.username):
             if Comment.dele_by_key(comment_key):
                 self.write("删除成功!")
             else:
                 self.send_error(404)
         else:
             self.send_error(404)
     else:
         self.redirect("/user/personal/manager/1")
Пример #4
0
def publish() :

  if not session.get('is_admin'):
    return redirect(url_for('admin.login'))
  article_id = int(request.args.get('articleId', 0))

  if not article_id :
    return abort(404)

  draft = db_session.query(Draft).filter(Draft.article_id == article_id).first()
  article = db_session.query(Article).filter(Article.id == article_id).first()

  if draft :
    if not article :
      article = Article(draft.user_id, draft.user_name, draft.title, draft.content)
      article.id = draft.article_id
      db_session.add(article)
    else :
      article.title = draft.title
      article.content = draft.content

    db_session.delete(draft)
    db_session.flush()
  
  return redirect('/detail?articleId=' + str(article_id))
Пример #5
0
def publish():

    if not session.get('is_admin'):
        return redirect(url_for('admin.login'))
    article_id = int(request.args.get('articleId', 0))

    if not article_id:
        return abort(404)

    draft = db_session.query(Draft).filter(
        Draft.article_id == article_id).first()
    article = db_session.query(Article).filter(
        Article.id == article_id).first()

    if draft:
        if not article:
            article = Article(draft.user_id, draft.user_name, draft.title,
                              draft.content)
            article.id = draft.article_id
            db_session.add(article)
        else:
            article.title = draft.title
            article.content = draft.content

        db_session.delete(draft)
        db_session.flush()

    return redirect('/detail?articleId=' + str(article_id))
Пример #6
0
 def get_data(self,id):
     result = self.redis.get('subject:%s'%id)
     if result:
         result = eval(result)
         article = Article()
         article.load_from_data(result)
         return article
     else:
         return None
 def post(self):
     user_id = self.request.cookies.get('user_id')
     user_id = int(user_id)
     user_info = ndb.Key('User', user_id).get()
     commit = Article(username=user_info.username,
                      title=self.request.get('title'),
                      text=self.request.get('text'))
     commit.put()
     return webapp2.redirect('/')
 def post(self):
     user_id = self.request.cookies.get('user_id')
     user_id = int(user_id)
     user_info = ndb.Key('User',user_id).get()
     commit = Article(username = user_info.username,
                 title=self.request.get('title'),
                 text=self.request.get('text'))
     commit.put()
     return webapp2.redirect('/')
Пример #9
0
 def get(self, *args, **kwargs):
     key = args[0]
     article = Article.get_by_key(key)
     if article.checked == -1:
         Article.check_pass(key)
         self.messages.success("审核通过!")
     elif article.checked == 1:
         Article.check_fail(key)
         self.messages.error("禁止成功!!")
     self.redirect("/manager/admin/1")
Пример #10
0
def get_article_list(index, type=''):
    try:
        index = int(index)
    except ValueError:
        index = 1
    type = str(type)

    query = {}
    if type != '' and type != 'all':
        tt = article_dao.get_article_type_by_name(str(type))
        if tt:
            query = {'type': str(tt['_id'])}
        else:
            return [], Page()

    item_limit = constants.item_limit * constants.item_limit_rate
    total_count = article_dao.get_article_count(query)
    page_count = int(math.ceil(total_count * 1.0 / item_limit))

    if index > page_count or index < 1:
        offset = 0
        index = 1
    else:
        offset = (index - 1) * item_limit

    page = Page()
    page.index = index
    page.count = constants.page_count if page_count > constants.page_count else page_count

    if page.index <= page.count / 2:
        page.start = 1
    else:
        page.start = page.index - int(page.count / 2)
        if page.start > page_count - page.count:
            page.start = page_count - page.count + 1

    result = list(article_dao.get_article_list(offset, item_limit, query))

    article_list = []
    for art in result:
        model = Article()
        model._id = art['_id']
        model.title = art['title']
        model.tag = art['tag']
        model.time = art['time']
        model.content = art['content']
        model.description = art['description']
        model.visit_count = art['visit_count']
        tt = article_dao.get_article_type_by_id(art['type'])
        if tt:
            model.type = tt['_id']
            model.type_name = tt['type']

        article_list.append(model)
    return article_list, page
Пример #11
0
 def post(self, *args, **kwargs):
     key = self.get_argument("theKey", "")
     user = self.current_user()
     article = Article.get_by_key(key)
     if key != "" and(user.level == 100 or user.username == article.username):
         if Article.dele_by_key(key):
             Comment.dele_by_article(key)
             self.write("删除成功!")
         else:
             self.send_error(404)
     else:
         self.send_error(404)
Пример #12
0
 def POST(self, name):
     authen = gc('name')
     if authen:
         article = Article.get(name)
         article.delete()
         return js(dict(r=True, id=name))
     return js(dict(r=False))
Пример #13
0
    def post(self):
        for row in Article.all():
            row.delete()

        for row in Comment.all():
            row.delete()
            self.redirect('/blog')
Пример #14
0
    def post(self, post_id):
        if self.user:
            if 'main' in self.request.POST:
                self.redirect('/blog')
            elif 'sub' in self.request.POST:
                # get inputs
                subject = self.request.get('subject')
                content = self.request.get('content')
                article = Article.by_id(post_id)
                uid = self.read_secure_cookie('user_id')

                if article.created_by == uid:

                    if subject and content:
                        article.title = subject
                        article.text = content
                        article.put()
                        self.redirect('/blog/%s' % str(article.key().id()))
                    else:
                        # error check if either one is empty
                        error = "Subject or Content is missing"
                        self.render("edit_post.html",
                                    title=subject,
                                    text=content,
                                    error=error)
                else:
                    self.redirect('/blog/broken')
        else:
            self.redirect('/blog/login')
            return
Пример #15
0
    def get(self, post_id):
        if self.user:
            article = Article.by_id(post_id)

            # checking if the article has the user on the who-liked list
            uid = self.read_secure_cookie('user_id')

            #if the author likes their own post,
            article_uid = article.created_by
            if article_uid == uid:
                #throw an error
                self.redirect('/blog/like_by_author')
                return

            if uid in article.who_liked:
                # user can't fall into this if clause since use won't see the like button
                self.redirect('/blog/broken')
                return
            else:
                # add uid to who_liked array
                article.who_liked.append(uid)
                article.likes = article.likes + 1
                article.put()
                self.render('liked.html', user=self.user)
        else:
            self.error = "You have to login to like the post"
            self.redirect("/blog/login")
Пример #16
0
 def GET(self, id):
     name = gc('name')
     article = Article.get(id)
     if article and name:
         user = get_user(name)
         return st("admin/edit.mako", **locals())
     return st("404.mako", **locals())
Пример #17
0
def edit():

    article_id = request.args.get("id", None)
    if article_id is None:
        return redirect(url_for("manage"))

    article = Article.get_article_by_id(article_id)
    if not article:
        return redirect(url_for("manage"))

    article_id = article.id
    title = article.title
    summary = article.summary
    content = article.content
    default_label_id = article.labelid

    labels = Label.get_labels()
    username = session.get("username", "")
    return render_template(
        "backend/post_article.html",
        id=article_id,
        title=title,
        summary=summary,
        content=content,
        default_label_id=default_label_id,
        labels=labels,
        username=username,
    )
Пример #18
0
 def GET(self, id):
     name = gc('name')
     article = Article.get(id)
     if article and name:
         user = get_user(name)
         return st("admin/edit.mako", **locals())
     return st("404.mako", **locals())
Пример #19
0
def article_to_model(article_dict):
    """
    :type article_dict: dict
    :rtype: model.article.Article | model.article.TrainingArticle
    """
    try:
        article_id = int(article_dict.get("id")[0])
        # article_categories = article_dict.get("categories")
        article_headline = (
            article_dict.get("headline")[0]).encode(TARGET_ENCODING)
        # article_keywords = [keyword.encode(TARGET_ENCODING) for keyword in article_dict.get("keywords")]
        # article_lead = article_dict.get("lede")[0].encode(TARGET_ENCODING)
        if article_dict.get("text"):
            article_text = article_dict.get("text")[0].encode(TARGET_ENCODING)
        else:
            article_text = ''
        article_model = Article(id=article_id,
                                categories=[],
                                headline=article_headline,
                                keywords=[],
                                lead=u'',
                                text=article_text)
        special_coverage_id = article_dict.get("specialCoverage")
        if special_coverage_id:
            return TrainingArticle(specialCoverage=int(special_coverage_id[0]),
                                   **article_model.__dict__)
        else:
            return article_model
    except Exception as e:
        log("Exception on parsing article: {}, could not create model. Context: {}"
            .format(e, article_dict.keys()))
        return None
Пример #20
0
    def test_call_switch_display(self, mock_main_view):
        """ Unit test of controller.title_loop.call_switch_display """

        test_feed = [Article('test title', "test url", "date")]
        call_switch_display(mock_main_view, test_feed)
        mock_main_view.display_entry.assert_called_with(
            'test title', "test url")
Пример #21
0
 def get(self, *args, **kwargs):
     user = self.current_user()
     stype = args[0]
     if stype == "1":
         article_query = Article.get_by_username(user.username)
         page_size = 5
         cur_page = self.get_argument("cur_page", int(math.ceil(article_query.count() / page_size)))
         article = pagination(count_all=article_query.count(), query=article_query, page_size=page_size,
                              cur_page=cur_page)
         self.render(
             'personal/manager.html',
             article=article,
             comment={},
             forperson={},
             page_title="文章管理",
         )
     elif stype == "2":
         comment_query = Comment.get_by_username(user.username)
         forperson_query = Comment.get_by_foruser(user.username)
         page_size = 5
         cur_page1 = self.get_argument("cur_page1", int(math.ceil(comment_query.count() / page_size)))
         cur_page2 = self.get_argument("cur_page2", int(math.ceil(forperson_query.count() / page_size)))
         comment = pagination(count_all=comment_query.count(), query=comment_query, page_size=page_size,
                              cur_page=cur_page1)
         forperson = pagination(count_all=forperson_query.count(), query=forperson_query, page_size=page_size,
                                cur_page=cur_page2)
         self.render(
             'personal/manager.html',
             article={},
             comment=comment,
             forperson=forperson,
             page_title="评论管理",
         )
     else:
         return self.redirect(url_for("index"))
Пример #22
0
def move_article():
    article_id = request.json["article_id"]
    cluster_from = request.json["cluster_from"]
    cluster_to = request.json["cluster_to"]

    if not article_id or not cluster_from or not cluster_to:
        return jsonify({
            "error":
            "argument `article_id`, `cluster_from` and `cluster_to` must be in JSON input"
        }), 400

    # Get info from database
    result = db["articles"].find_one({"_id": bson.ObjectId(oid=article_id)})
    cluster_from = db["clusters"].find_one(
        {"_id": bson.ObjectId(oid=cluster_from)})
    cluster_to = db["clusters"].find_one(
        {"_id": bson.ObjectId(oid=cluster_to)})
    if not cluster_from or not cluster_to or not result:
        return jsonify({"error": "An id is invalid"}), 400

    article = Article.from_database(db, result)
    transformer_outputs = models["categorisation"].transformer(
        np.array([article.token_ids]).reshape(1, -1))[0][0]
    article.cls_token = transformer_outputs[0].numpy().tolist()

    clusters.move_article(article, cluster_from, cluster_to)
    return jsonify({"success": True}), 200
Пример #23
0
 def article_list(cls, user_name, is_published=True):
     if is_published:
         articles = Article.select().filter(Article.is_published).order_by(
             Article.updated_at.desc()).all()
     else:
         articles = Article.select().filter(
             Article.user_name == user_name).order_by(
                 Article.updated_at.desc()).all()
     results = []
     for article in articles:
         data = article.get_json()
         data['author'] = article.user_name
         data['can_edit'] = user_name == article.user_name
         data.pop('user_name')
         results.append(data)
     return results
Пример #24
0
def rss_author(name):
    articles = Article().get_author_paged(name, start=0, amount=100)
    payload = render_template('rss.xml',
                              articles=articles,
                              version=settings.corres_version,
                              author=name)
    return Response(payload, mimetype='text/xml')
Пример #25
0
 def get(self, *args):
     key = args[0]
     if key == "1":
         article_query = Article.get_all()
         page_size = 5
         #cur_page = self.get_argument("cur_page", int(math.ceil(article_query.count() / page_size)))
         cur_page = self.get_argument("cur_page", 1)
         article = pagination(count_all=article_query.count(), query=article_query, page_size=page_size,
                              cur_page=cur_page)
         self.render(
             'user/manager.html',
             article=article,
             users={},
             page_title="文章管理",
         )
     elif key == "2":
         user_query = User.get_all()
         page_size = 5
         cur_page = self.get_argument("cur_page", int(math.ceil(user_query.count() / page_size)))
         users = pagination(count_all=user_query.count(), query=user_query, page_size=page_size, cur_page=cur_page)
         self.render(
             'user/manager.html',
             article={},
             users=users,
             page_title="用户管理",
         )
     else:
         self.redirect("/manager/" + key)
Пример #26
0
 def POST(self, name):
     authen = gc('name')
     if authen:
         article = Article.get(name)
         article.delete()
         return js(dict(r=True, id=name))
     return js(dict(r=False))
Пример #27
0
def save():
    userid = session.get('userid')
    username = session.get('username')

    if not userid or not username or not session.get('is_admin'):
        return redirect(url_for('admin.login'))

    title = request.form.get('title')
    content = request.form.get('content')

    if not title or not content:
        tag_chk_list = get_article_taglist(0)
        return render_template('admin/publish.html',
                               active='publish',
                               article=None,
                               tag_list=tag_chk_list)

    ## 去掉HTML的背景颜色,防止和现有CSS的背景颜色冲突
    content = htmlHelper.purge_background(content)

    ## 向数据库添加一篇文章
    article = Article(userid, username, '', '')
    db_session.add(article)
    db_session.flush()

    draft = Draft(article.id, userid, username, title, content)
    db_session.add(draft)
    db_session.flush()

    ## 向数据库添加文章标签
    tag_list = request.form.getlist('tags')
    dao.save_tags(article.id, tag_list)
    return redirect('/admin/draft?draftId=%d' % draft.id)
 def get(self):
     articles = Article.query().order(-Article.date)
     templatevalues = {
         'articles': articles,
         'user_log' : checkcookies(self),
     }  
     template = jinja_environment.get_template('index.html')
     self.response.out.write(template.render({'templatevalues':templatevalues}))
Пример #29
0
 def process_item(self, item, spider):
     a = Article(title=item["title"].encode("utf-8"),
                 url=item["url"],
                 body=item["body"].encode("utf-8"),
                 publish_time=item["publish_time"].encode("utf-8"),
                 source_site=item["source_site"].encode("utf-8"))
     self.session.add(a)
     self.session.commit()
Пример #30
0
    def extract(self):
        article_json = self.__crawler()

        article = Article(article_json)

        self.__storage(article)

        return article
 def get(self):
     #logging.info(os.path.join(os.path.dirname(__file__))
     articles = Article.query().order(-Article.date)
     templatevalues = {
         'user_log' : checkcookies(self),
     }
     template = jinja_environment.get_template('create.html')
     self.response.out.write(template.render({'templatevalues':templatevalues}))
Пример #32
0
    def test_ten_second_loop_calls_its_self(self, mock_timer, mock_main_view,
                                            mock_switch_display):
        """ Unit test of controller.title_loop.ten_second_loop """

        test_feed = [Article('test title', "test url", "date")]
        ten_second_loop(mock_main_view, 7, test_feed)
        self.assertTrue(mock_timer.called)
        self.assertTrue(mock_switch_display.called)
Пример #33
0
 def get(self, *args, **kwargs):
     cur_page = self.get_argument("cur_page", "1")
     article_query = Article.get_all()
     article = pagination(count_all=article_query.count(), query=article_query, page_size=5, cur_page=cur_page)
     self.render(
         'community.html',
         article=article,
     )
Пример #34
0
def home():
    start, amount = pager_args()
    articles = Article().get_paged(start=start, amount=amount)
    tot_count = Article().get_count_filtered()
    tweet_count = Tweet().get_tweetcount_filtered()
    payload = render_template(
        'home.html',
        articles=articles,
        start=int(start),
        amount=int(amount),
        tot_count=tot_count,
        tweet_count=tweet_count,
        cssver=os.path.getmtime(
            os.path.join(os.path.dirname(__file__), 'static/thcrrspndnt.css')),
        site=settings.CONFIG.get('site', 'thecorrespondent.com'),
        version=settings.corres_version,
    )
    return payload
Пример #35
0
    def test_call_new_feed(self, mock_feedmanager, mock_getfeedcontents,
                           mock_getfeedname):
        """Unit test of controller.title_loop.test_call_new_feed"""

        test_url = "https://www.theguardian.com/us/rss"
        article_1 = Article(
            "Article 1", "Link 1",
            (datetime.now() - timedelta(days=1)))  # 1 day ago (most recent)
        article_2 = Article("Article 2", "Link 2",
                            (datetime.now() - timedelta(days=2)))  # 2 days ago
        article_3 = Article("Article 3", "Link 3",
                            (datetime.now() - timedelta(days=3)))  # 3 days ago

        mock_getfeedcontents.return_value = [article_1, article_2, article_3]
        mock_getfeedname.return_value = "Test Feed Name"

        call_new_feed(mock_feedmanager, test_url)
        mock_feedmanager.update.assert_called_once()
Пример #36
0
def get_article(title):
    model = Article()
    if title != '':
        art = article_dao.get_article_by_title(str(title))
        if art:
            model._id = art['_id']
            model.title = art['title']
            model.tag = art['tag']
            model.time = art['time']
            model.content = art['content']
            model.description = art['description']
            model.visit_count = art['visit_count']
            tt = article_dao.get_article_type_by_id(art['type'])
            if tt:
                model.type = tt['_id']
                model.type_name = tt['type']

    return model
Пример #37
0
 def process_item(self, item, spider):
     a = Article(title=item["title"].encode("utf-8"),
                 url=item["url"],
                 content=item["content"].encode("utf-8"),
                 publish_time=item["publish_time"].encode("utf-8"),
                 publish_user=item["publish_user"].encode("utf-8"),
                 folder_id=2)
     self.session.add(a)
     self.session.commit()
Пример #38
0
 def on_delete(self, req, resp):
     articles = Article.fetch(req)
     if len(articles) != 1:
         resp.status = falcon.HTTP_400
         resp.body = '400 Bad Request'
     else:
         article = articles[0]
         article.key.delete()
         resp.status = falcon.HTTP_204
 def get(self):
     #logging.info(os.path.join(os.path.dirname(__file__))
     articles = Article.query().order(-Article.date)
     templatevalues = {
         'user_log': checkcookies(self),
     }
     template = jinja_environment.get_template('create.html')
     self.response.out.write(
         template.render({'templatevalues': templatevalues}))
Пример #40
0
    def extract(self, count):
        links = self.link_collector.collect(count)

        articles = []
        for link in links:
            content = self.content_extractor.extract(link.url)
            articles.append(Article(link.title, link.url, content.snippet))

        return articles
Пример #41
0
 def on_post(self, req, resp):
     article = Article.create(req)
     if article:
         key = article.put()
         resp.status = falcon.HTTP_200
         resp.body = json.dumps({'key': key.urlsafe()})
     else:
         resp.status = falcon.HTTP_400
         resp.body = "400 Bad Request."
 def get(self):
     articles = Article.query().order(-Article.date)
     templatevalues = {
         'articles': articles,
         'user_log': checkcookies(self),
     }
     template = jinja_environment.get_template('index.html')
     self.response.out.write(
         template.render({'templatevalues': templatevalues}))
Пример #43
0
def create_article(request, board, subject, content):
    article = Article()
    article.board = board
    board.article_count += 1
    article.user = request.user
    article.subject = subject
    article.change_content(content)
    return article
Пример #44
0
def get_article():
    article_id = request.args.get("_id")
    if article_id == None:
        return jsonify({"error": "You must set an article id"}), 400

    result = db["articles"].find_one({"_id": bson.ObjectId(oid=article_id)})
    if result:
        return jsonify(Article.from_database(db, result).toJson(categories))
    else:
        return jsonify({"error": "No article found with this id"}), 400
Пример #45
0
 def POST(self, id):
     article = Article.get(id)
     cate = article.cate
     req = gd()
     article.title = req.title
     article.cate = req.cate
     article.url = req.url
     article.content = req.content
     article.update(cate)
     return js(dict(r=True, ok=True, id=id))
Пример #46
0
 def POST(self, id):
     article = Article.get(id)
     cate = article.cate
     req = gd()
     article.title = req.title
     article.cate = req.cate
     article.url = req.url
     article.content = req.content
     article.update(cate)
     return js(dict(r=True, ok=True, id=id))
Пример #47
0
 def article_detail(cls, id, user_name):
     article = Article.select().get(id)
     if not article.is_published and user_name != article.user_name:
         raise ServerException('该文章未发布')
     cls.view_article(id, user_name)
     content = QiniuService.get_doc(article.url)
     result = article.get_json()
     result['content'] = content
     result['liked'] = cls.is_user_liked(user_name, id)
     return result
 def post(self):
     datearticle = self.request.get('datearticle')
     datearticle = datetime.strptime(datearticle+' 00:00:00', '%m/%d/%Y %H:%M:%S')
     articles = Article.query(Article.date == datearticle).order(-Article.date)
     templatevalues = {
         'articles': articles,
         'user_log' : checkcookies(self),
     }  
     template = jinja_environment.get_template('index.html')
     self.response.out.write(template.render({'templatevalues':templatevalues}))
Пример #49
0
 def get(self, *args):
     key = args[0]
     ar = Article.get_by_key(key)
     page_size = 5
     comment_query = Comment.get_by_article(key)
     cur_page = self.get_argument("cur_page", int(math.ceil(comment_query.count() / page_size)))
     comment = pagination(count_all=comment_query.count(), query=comment_query, page_size=page_size, cur_page=cur_page)
     next_back = Article.get_next_back(key)
     if ar is not None:
         page_title = ar.header
         self.render(
             "spider.html",
             page_title=page_title,
             ar=ar,
             comment=comment,
             next_back=next_back,
         )
     else:
         self.messages.error("文章链接已经更新")
         self.redirect(url_for("index"))
Пример #50
0
def get_latest_article():
    result = list(article_dao.get_latest_article(constants.item_limit))
    latest_articles = []
    for art in result:
        model = Article()
        model._id = art['_id']
        model.title = art['title']
        model.tag = art['tag']
        model.time = art['time']
        model.content = art['content']
        model.description = art['description']
        model.visit_count = art['visit_count']
        tt = article_dao.get_article_type_by_id(art['type'])
        if tt:
            model.type = tt['_id']
            model.type_name = tt['type']

        latest_articles.append(model)

    return latest_articles
Пример #51
0
 def on_get(self, req, resp):
     articles = Article.fetch(req)
     resp.status = falcon.HTTP_200
     resp.body = json.dumps({
         'articles': [{
             'key': article.key.urlsafe(),
             'author': article.author,
             'title': article.title,
             'body': article.body
         } for article in articles]
     })
Пример #52
0
    def post(self, title=''):
        art = Article()
        art._id = self.get_argument('_id', '')
        art.title = self.get_argument('title', '')
        art.type = self.get_argument('type', '')
        art.tag = self.get_argument('tag', '')
        art.description = self.get_argument('description', '')
        art.content = self.get_argument('content', '')

        article_service.add_or_update_article(art)

        self.redirect('/system/article/list/1')
Пример #53
0
def list_articles():
    current_page = request.args.get("page", 1)
    label_id = request.args.get("labelid", None)

    try:
        current_page = int(current_page)
    except:
        abort(404)

    if current_page < 1:
        abort(404)

    if label_id is not None:
        try:
            label_id = int(label_id)
        except:
            abort(404)

    articles = Article.get_articles_of_current_page(current_page, label_id=label_id, article_status=STATUS_PUBLISH, rows=FRONTEND_ARTICLE_ROWS)

    # Deal with paging
    paging_amount = Article.get_articles_paging_amount(article_status=STATUS_PUBLISH, rows=FRONTEND_ARTICLE_ROWS)

    if current_page > paging_amount: # Deal url current_page error
        abort(404)

    labels, has_login = _prepare_base_data()
    uri = str(request.url_rule)


    return render_template('/frontend/list_articles.html',
                            articles=articles,
                            labels=labels,
                            has_login=has_login,
                            current_page=current_page,
                            paging_amount=paging_amount,
                            uri=uri
                        )
Пример #54
0
def manage():

    page = request.args.get("page", 1)
    logging.info("page: {}".format(page))
    try:
        current_page = int(page)
    except Exception:
        return abort(404)

    uri = str(request.url_rule)
    template = "/backend/manage_articles.html"
    # Choose article status
    article_status = STATUS_PUBLISH
    if len(uri) > 5 and uri[-5:] == "draft":
        article_status = STATUS_SAVE
        template = "/backend/draft.html"

    logging.info("uri: {}".format(uri))

    paging_amount = Article.get_articles_paging_amount()
    # Deal with current_page params error
    if current_page > paging_amount or current_page < 1:
        return abort(404)

    articles = Article.get_articles_of_current_page(current_page=current_page, article_status=article_status)
    logging.info("articles: {}".format(articles))
    label = Label.get_labels()
    status = {STATUS_PUBLISH: u"发布", STATUS_SAVE: u"保存"}

    for article in articles:
        article.label = label[article.labelid - 1]["name"]
        article.status = status[article.status]

    username = session.get("username", "")
    return render_template(
        template, username=username, articles=articles, current_page=current_page, paging_amount=paging_amount, uri=uri
    )
Пример #55
0
def delete():
    article_id = request.args.get("id", None)
    current_page = request.args.get("page", None)
    uri = request.url_rule
    logging.info("uri: {}".format(uri))

    if article_id is None or current_page is None:
        return redirect(url_for("admin.manage"))

    # delete the article by id
    Article(id=article_id).delete()
    current_page = int(current_page)

    # check data of current page
    articles = Article.get_articles_of_current_page(current_page=current_page, article_status=STATUS_PUBLISH)
    if not articles:
        current_page = current_page - 1 if current_page - 1 else current_page
    url = "{}?page={}".format(str(uri)[:-7], current_page)
    logging.info("url: {}".format(url))
    return redirect(url)
Пример #56
0
def article():
    id = request.args.get("id", 1)
    try:
        article_id = int(id)
    except:
        return abort(404)

    article = Article.get_article_by_id(id)

    # The id not exist, url error
    if not article:
        abort(404)

    md = markdown.Markdown(extensions=['codehilite'])
    article.content = Markup(md.convert(article.content))

    labels, has_login = _prepare_base_data()
    return render_template('/frontend/article.html',
                            labels=labels,
                            article=article,
                            has_login=has_login
                        )
Пример #57
0
def article_edit(request):
    '文章编辑'
    article_facade = facade.factory.create_article_facade()
    topic_facade = facade.factory.create_topic_facade()
    category_facade = facade.factory.create_category_facade()
    tag_facade = facade.factory.create_tag_facade()

    #如果是提交信息
    if request.method =="POST":
        article = Article()
        id = func.get_int_param_from_post(request,'id')
        article.id=id
        article.title = func.get_str_param_from_post(request,'title')
        article.root_category_id = func.get_int_param_from_post(request,'root_category')
        article.category_id = func.get_int_param_from_post(request,'category1')
        article.category_id2 = func.get_int_param_from_post(request,'category2')
        article.category_id3 = func.get_int_param_from_post(request,'category3')
        article.author = func.get_str_param_from_post(request,'author')
        article.source = func.get_str_param_from_post(request,'source')
        article.short_description = func.get_str_param_from_post(request,'short_description')
        article.description = func.get_str_param_from_post(request,'description')
        article.demo_code = func.get_str_param_from_post(request,'demo_code')
        article.demo_url = func.get_str_param_from_post(request,'demo_url')
        article.dev_view_code = func.get_str_param_from_post(request,'dev_view_code')
        article.full_download_url = func.get_str_param_from_post(request,'full_download_url')
        article.head_code = func.get_str_param_from_post(request,'head_code')
        article.body_code = func.get_str_param_from_post(request,'body_code')
        article.compatibility = func.get_str_param_from_post(request,'compatibility')
        article.pic = func.get_str_param_from_post(request,'pic')
        article.small_pic = func.get_str_param_from_post(request,'small_pic')
        article.recommend = func.get_str_param_from_post(request,'recommend')=='on'
        article.topic_id = func.get_str_param_from_post(request,'topic_id')
        article.state = 0
        article.isrtdate = func.format_date_time(func.str_to_datetime(func.get_str_param_from_post(request,'isrtdate')))
        article.last_hit_date=func.format_date_time(func.str_to_datetime(func.get_str_param_from_post(request,'last_hit_date')))
        article.hits = func.get_int_param_from_post(request,'hits')

        id = article_facade.post_data(article)
        #添加Tags
        tag_facade.insert_tags(id,func.get_str_param_from_post(request,'tags'))

        refer_url = func.get_str_param_from_post(request,'refer_url')
        if not refer_url:
            refer_url = "article_list"

        return HttpResponseRedirect(refer_url)
        

    id = func.get_int_param_from_get(request,'id')
    output = {}

    if id>0:
        article = article_facade.get_data(id)
        article.tags = tag_facade.get_tags_str(id)
        output['article'] = article

    topic_list = topic_facade.get_all_topic()
    root_category_list = category_facade.get_child_category_list(0)
    output['topic_list'] = topic_list
    output['root_category_list'] = root_category_list
    output['refer_url'] = func.get_referer(request,'article_list')
    

    return render_to_response('admin/article_edit.html',output)
Пример #58
0
 def GET(self, name):
     article = Article.get(name)
     if article:
         return st("article.mako", **locals())
     return st("404.mako", **locals())
Пример #59
0
from facade import articlefacade
from facade import factory
from model.article import Article

#列表目录到数组
root_dir = r'D:\python\sharejs\vectors\d1'

dirs = os.listdir(root_dir)
print(dirs)

i=0;
#dirs =['blue', 'cantya', 'creative-media', 'green', 'happy-print-shop', 'indeziner-form-templates', 'one-page-cv', 'product-landing-page', 'sindromk', 'violet', 'write-to-santa']
for dir in dirs:
    i+=1
    if i<=100000:
        article = Article()
        article.title = u'矢量素材'
        article.short_description=u'矢量图格式为EPS,含JPG预览图,关键词:'
        article.compatibility = u''
        #article.demo_url = '/vectors/d1/%s/index.html'%dir
        article.root_category_id = 700
        article.category_id = 751
        article.full_download_url = '/vectors/d1/%s/%s.zip'%(dir,dir)
        article.pic = '/vectors/d1/%s/demo.jpg'%dir
        img_description = ''
        for file in os.listdir(root_dir + '\\' + dir):
            if file.endswith('.jpg') and file != 'demo.jpg':
                img_description += '[img]%s[/img]\r\n'%('/vectors/d1/'+dir+'/'+file)
        article.description = img_description
        #article.source = ''
        article_facade = factory.create_article_facade()