示例#1
0
 def __search(key, user):
     science_direct_crawler = ScienceDirectCrawler()
     scielo_crawler = ScieloCrawler()
     science_direct_crawler.set_main_key(key)
     scielo_crawler.set_main_key(key)
     content = science_direct_crawler.search(
         {"class": "result-item-content"})
     prepared_content = []
     bow = Bow(
         BowTypes.NONE, {
             "framework": [],
             "technology": [],
             "computer": ["machine"],
             "program": ["software"],
             "IT": ["I.T."],
             "AI": [
                 "A.I.", "A.I", "artificial intelligence",
                 "Artificial Intelligence"
             ],
             "OOP":
             ["Object-Oriented Programming, object-oriented programming"],
             "Bugs": ["Bugs"],
             "DEVOPS": [],
             "Version Control":
             ["GIT", "git", "Mercurial", "mercurial", "SVN"],
             "Firewall": ["firewall", "FIREWALL"],
             "Cloud": ["Cloud Computing"],
             "Routers": [],
             "VM": ["Virtual Machine", "Virtual Machines"],
             "VPN": ["Virtual Private Network"],
             "Big Data": ["BD", "big data"],
             "IDE": [],
             "apps": ["APP", "App"],
             "SDK": [],
             "Web Apps": ["site"],
             "Database": ["database"]
         })
     prepared_content.append(
         RankingPreprocessor(
             bow.count(content),
             ScienceDirectCrawler.tags).get_prepared_ranking())
     content = scielo_crawler.search({"class": "results"})
     prepared_content.append(
         RankingPreprocessor(bow.count(content),
                             ScieloCrawler.tags).get_prepared_ranking())
     if user is not None:
         article = Article(datetime.now().timestamp(),
                           science_direct_crawler.get_original_target(),
                           content, user)
         article.save()
     return prepared_content
def edit_article(id):
  article = db.get_article_by_id_and_author(id, session['username'])
  if not article:
    flash('Permission denied', 'danger')
    return redirect(url_for('dashboard_route.dashboard'))
  # Get form
  form = ArticleForm(request.form)
  # Populate form fields
  form.title.data = article['title']
  form.body.data = article['body']

  if request.method == 'POST' and form.validate():
    title = request.form['title']
    body = request.form['body']

    article = db.get_article_by_id_and_author(id, session['username'])

    if not article:
      flash('Permission denied', 'danger')
      return redirect(url_for('dashboard_route.dashboard'))

    new_article = Article(title, body, article['author'])

    db.update_article_by_id(id, new_article)

    flash('Article Updated', 'success')
    return redirect(url_for('dashboard_route.dashboard'))
  return render_template('edit_article.html', form=form)
示例#3
0
def populate_database(data: dict = {}):
    print(f">>>> Type of data argument: {type(data)}")
    d = [("art-name", "art-maker", "art-model", 1250 * i, 3 * i, "wearables")
         for i in range(0, 10, 1)]
    for idx, art in enumerate(d):
        #if(data[f'{art[5]}']):
        if (len(data.keys()) == 0):
            data[f'{art[5]}'] = []
        else:
            if (data[f'{art[5]}']):
                data[art[5]].append(
                    Article(art[0], art[1], art[2], art[3], art[4], art[5]))
            else:
                data[art[5]] = []
                data[art[5]].append(
                    Article(art[0], art[1], art[2], art[3], art[4], art[5]))
示例#4
0
def article_add():
    form = ArticleForm()
    print(form)
    # 判断表单验证是否通过
    if form.validate_on_submit():
        try:
            filename = secure_filename(''.join(lazy_pinyin(form.img_url.data.filename)))
            print(filename)
            form.img_url.data.save('./static/img/' + filename)
            print("上传成功!")
            # 获取表单提交的数据
            articles = Article(
                title=form.title.data,
                content=form.content.data,
                types=form.types.data,
                # img_url=form.img_url.data,
                img_url=filename,
                author=form.author.data,
                is_recommend=form.is_recommend.data,
                is_valid=form.is_valid.data,
                created_at=datetime.now())
            db.session.add(articles)
            db.session.commit()
            flash("新闻添加成功!")
            return redirect(url_for('.article_index'))
        except:
            flash("新闻添加失败!", category="error")

    return render_template("/admin/article/add.html", form=form)
示例#5
0
 def get(self, post_id):
     a = Article.check_if_user_owns_post(post_id, self.user.name)
     if a:
         self.render("edit-post.html", a=a)
     else:
         error = "Sorry, This is not your article"
         self.render('error.html', error=error)
示例#6
0
    def post(self, post_id):
        a = Article.check_if_valid_post(post_id)
        if a:
            if self.user:
                key = db.Key.from_path('Article',
                                       int(post_id),
                                       parent=blog_key())
                a = db.get(key)
                comment = self.request.get('comment')
                created_by = self.user.name

                if comment:
                    c = Comment(parent=blog_key(),
                                comment=comment,
                                post_id=int(post_id),
                                created_by=created_by)
                    c.put()

                    comments = db.GqlQuery(
                        "select * from Comment where post_id = " + post_id +
                        " order by created desc")
                    self.render("permalink.html", a=a, comments=comments)
            else:
                self.redirect('/blog/login')
        else:
            self.error(404)
            return
示例#7
0
 def get(self, post_id):
     a = Article.check_if_user_owns_post(post_id, self.user.name)
     if a:
         a.delete()
         self.redirect('/blog/')
     else:
         error = "This is not your article"
         self.render('error.html', error=error)
示例#8
0
    def get(self, post_id):
        a = Article.check_if_valid_post(post_id)
        if a:
            comments = db.GqlQuery("select * from Comment where post_id = " +
                                   post_id + " order by created desc")
        else:
            self.error(404)
            return

        self.render("permalink.html", a=a, comments=comments)
示例#9
0
 def get(self, **kwargs):
     articles = Article.get({
         "user.username": session["user"]["username"],
         "user.password": session["user"]["password"]
     })
     user = User.get({
         "username": session["user"]["username"],
         "password": session["user"]["password"]
     })[0]
     kwargs.__setitem__("articles", articles)
     kwargs.__setitem__("user", user)
     return super().get(**kwargs)
示例#10
0
    def post(self):
        if self.user:
            title = self.request.get("title")
            contents = self.request.get("contents")
            created_by = self.user.name

            if title and contents:
                a = Article(parent=blog_key(),
                            title=title,
                            contents=contents,
                            created_by=created_by)
                a.put()
                self.redirect('/blog/%s' % str(a.key().id()))
            else:
                error = "We need both a title and blog content"
                self.render("newpost.html",
                            title=title,
                            contents=contents,
                            error=error)
        else:
            error = "Please login or register to write your story!"
            self.render("error.html", error=error)
def download_history():
    try:
        session_user = session["user"]
        articles = Article.get({
            "user.username": session_user["username"],
            "user.password": session_user["password"]
        })
        print(articles)
        make_pdf = MakePDF(json.dumps(articles))
        return send_from_directory("./files/pdf",
                                   make_pdf.generate_from_string())
    except KeyError:
        return json.dumps([{"result": False}])
def add_article():
  form = ArticleForm(request.form)
  if request.method == 'POST' and form.validate():
    title = form.title.data
    body = form.body.data
    author = session['username']

    article = Article(title, body, author)

    db.add_article(article)
    flash('Article Created', 'success')
    return redirect(url_for('dashboard_route.dashboard'))
  return render_template('add_article.html', form=form)
示例#13
0
 def post(self, post_id):
     a = Article.check_if_user_owns_post(post_id, self.user.name)
     if a:
         title = self.request.get("title")
         contents = self.request.get("contents")
         if title and contents:
             a.title = title
             a.contents = contents
             a.put()
             self.redirect('/blog/%s' % post_id)
         else:
             error = "We need both a title and blog content"
             self.render("edit-post.html", a=a, error=error)
     else:
         error = "Sorry, This is not your article."
         self.render('error.html', error=error)
示例#14
0
    def post(self, post_id, comment_id):
        a = Article.check_if_valid_post(post_id)
        c = Comment.check_if_user_owns_comment(comment_id, self.user.name)
        if a and c:
            comment = self.request.get('comment')
            if comment:
                c.comment = comment
                c.put()
                self.redirect('/blog/%s' % post_id)
            else:
                error = "Please input comment"
                self.redner("comment.html", error=error, c=c)

        else:
            error = "Oops, this is not your comment"
            self.render("error.html", error=error)
示例#15
0
def form():
    """
        Rajouter dans votre lsite_articles
        un article du formulaire (titre, prix...)
    """
    file_img = request.files["img"]
    filename = str(uuid4()) + file_img.filename
    file_img.save(f"public/images/{filename}")
    article = Article(titre=request.form.get("titre"),
                      prix=request.form.get("prix"),
                      description=request.form.get("desc"),
                      location=request.form.get("location"),
                      image=filename)
    db.session.add(article)
    db.session.commit()
    return redirect("/")
示例#16
0
    def get(self, post_id):
        a = Article.check_if_valid_post(post_id)
        uid = self.read_secure_cookie('user_id')

        if a:
            if a.created_by == self.user.name:
                error = "you can\'t like your own post"
                self.render('error.html', error=error)
            elif not self.user:
                self.redirect('/blog/login')
            elif a.likes and uid in a.likes:
                a.likes.remove(uid)
                a.put()
                self.redirect(self.request.referer)

            else:
                a.likes.append(uid)
                a.put()
                self.redirect(self.request.referer)
示例#17
0
def getData():
    """ read data from the file """
    data = {"cat": []}
    if os.path.exists(file_path):
        if (os.stat(file_path).st_size == 0):
            # raise Exception("Empty file")
            print("Database file is empty")
            return {}
        l = {}
        with open(file_path, 'r') as file:
            DB_OPEN_FLAG = True
            try:
                l = parseLine(file.readlines())  # [count, article, category]
            except Exception as ex:
                print("File data structure miss matched", file=sys.stderr)
                return
            data[str.lower(l[3])].append(Article.get_instance(json.loads(
                l[1])))
    return data
示例#18
0
文件: admin.py 项目: hqhiwqy/AI-2
def article_add():
    form = ArticleForm()
    # 判断表单是否验证通过
    if form.validate_on_submit():
        try:
            # 获取表单提交的数据
            article = Article(title=form.title.data,
                              content=form.content.data,
                              types=form.types.data,
                              img_url=form.img_url.data,
                              author=form.author.data,
                              is_recommend=form.is_recommend.data,
                              is_valid=form.is_valid.data,
                              created_at=datetime.now())
            db.session.add(article)
            db.session.commit()
            flash("添加新闻成功!")
            return redirect(url_for(".article_index"))
        except:
            flash("添加新闻失败!", category="error")

    return render_template("admin/article/add.html", form=form)
示例#19
0
def article_add():
    form = ArticleForm()
    # form2 = UploadForm()
    # if form2.validate():
    #     try:
    #         filename = secure_filename(''.join(lazy_pinyin(form2.upload.data.filename)))
    #         form2.upload.data.save('./images/' + filename)
    #         flash("上传成功")
    #         # return redirect(url_for('.article_add'))
    #     except:
    #         flash("上传失败", category="error")
    if form.validate_on_submit():

        try:
            filename = secure_filename(''.join(
                lazy_pinyin(form.img_url.data.filename)))
            print(filename)
            form.img_url.data.save('./static/images/' + filename)
            print("上传成功!")
            article = Article(
                title=form.title.data,
                content=form.content.data,
                types=form.types.data,
                # img_url=form.img_url.data,
                img_url=filename,
                author=form.author.data,
                is_recommend=form.is_recommend.data,
                is_valid=form.is_valid.data,
                created_at=datetime.now())
            db.session.add(article)
            db.session.commit()
            flash("添加新闻成功!")
            return redirect(url_for('.article_index'))
        except:
            flash("添加新闻失败!", category="error")
    return render_template('/admin/article/add.html', form=form)
示例#20
0
def save_article_from_json(json_article):
  article = Article(title=json_article['title'][:99], content='', url='')
  db.session.add(article)
  db.session.commit()