예제 #1
0
def process_pack(request, pack_id=None):
    if pack_id:
        pack = ArticlePackModel.objects.get(id = pack_id)
        if pack:
            try:
                tar = tarfile.open(pack.packfile.path, 'r:tar')
                members = tar.getmembers()
                for member in members:
                    try:
                        if member.isfile and member.size > 0 :
                            title = member.name
                            while '/' in title:
                                title = title[title.index('/')+1:]
                            if '.' in title:
                                title = title[0:title.index('.')]
                            newarticle = ArticleModel(title = title[:100], text = tar.extractfile(member.name).read(), niche=pack.niche)
                            newarticle.save()
                    except Exception,e:
                        print e
                pack.processed = True
                pack.save()
                return {'status':'success'}
            except Exception, e:
                print e
                return {'status':'error'}
예제 #2
0
def process_pack(request, pack_id=None):
    if pack_id:
        pack = ArticlePackModel.objects.get(id=pack_id)
        if pack:
            try:
                tar = tarfile.open(pack.packfile.path, 'r:tar')
                members = tar.getmembers()
                for member in members:
                    try:
                        if member.isfile and member.size > 0:
                            title = member.name
                            while '/' in title:
                                title = title[title.index('/') + 1:]
                            if '.' in title:
                                title = title[0:title.index('.')]
                            newarticle = ArticleModel(title=title[:100],
                                                      text=tar.extractfile(
                                                          member.name).read(),
                                                      niche=pack.niche)
                            newarticle.save()
                    except Exception, e:
                        print e
                pack.processed = True
                pack.save()
                return {'status': 'success'}
            except Exception, e:
                print e
                return {'status': 'error'}
예제 #3
0
    def post(cls, slug):
        """Update article title field."""
        new_title = request.get_json()["title"]
        article = ArticleModel.find_by_slug(slug)
        if not article:
            return {"message": "Article not found"}, 404
        if new_title == article.title:
            return {"message": "You're trying to change to existing title"}
        if ArticleModel.find_by_title(new_title):
            return {"message": "This title is taken"}

        article.title = new_title
        article.save_to_db()
        return {"message": "Title has been changed"}, 200
예제 #4
0
 def create_one(author_id, content, title) -> ArticleModel:
     article = ArticleModel(author_id=author_id,
                            content=content,
                            title=title)
     DBSession().add(article)
     DBSession().flush()
     return article
 def create_new_article(db: Session, article: ArticleCreate):
     """Insert an article in the database"""
     the_article = ArticleModel(**article.dict())
     db.add(the_article)
     db.commit()
     # db.refresh(the_article)
     return the_article
예제 #6
0
    def put(cls, slug):
        """
        Assign image to specific article instance.
        """
        article = ArticleModel.find_by_slug(slug)
        if not article:
            return {"message": "Article does not exist"}, 404

        data = image_schema.load(request.files)
        folder = "article_images"

        try:
            image_path = image_helper.save_image(data["image"], folder=folder)
            basename = image_helper.get_basename(image_path)

            previous_article_image = article.image_url
            article.image_url = basename
            article.save_to_db()

            if previous_article_image:
                image_helper.delete_image(previous_article_image, folder)

            return {"message": "Image {} uploaded".format(basename)}, 201
        except UploadNotAllowed:
            extension = image_helper.get_extension(data["image"])
            return {"message": "Extension not allowed"}, 400
        except Exception:
            traceback.print_exc()
            return {"message": "Internal server error"}, 500
예제 #7
0
def index():
    page = int(request.args.get('page', 1))
    tag = request.args.get('tag')

    # 分页控制
    if page < 1:
        page = 1

    # 标签查询
    if tag:
        rows = (ArticleModel.filter(ArticleModel.tag == tag).order_by(
            -ArticleModel.publish_time).paginate(page))
    else:
        rows = (ArticleModel.select().order_by(
            -ArticleModel.publish_time).paginate(page))

    return render_template('toutiao.html', rows=rows, page=page, tag=tag)
예제 #8
0
 def post(cls, slug):
     """
     Unpublish article by unsetting published_date field.
     """
     article = ArticleModel.find_by_slug(slug)
     if not article:
         return {"message": "Article not found"}, 404
     article.unpublish()
     return {"message": "Article has been unpublished"}, 200
예제 #9
0
 def delete(cls, slug: str):
     """
     Delete specific data instance
     """
     article = ArticleModel.find_by_slug(slug)
     if not article:
         return {"message": "Article not found"}, 404
     article.delete_from_db()
     return {"message": "Article deleted"}, 200
예제 #10
0
    def get(cls, slug: str):
        """
        Return specific article data.

        Only published articles are available via this endpoint
        """
        article = ArticleModel.find_by_slug(slug)
        if not article or not article.published_date:
            return {"message": "Article not found"}, 404
        return article_schema.dump(article), 200
예제 #11
0
    def get(cls, slug: str):
        """
        Return specific article data.

        Only published articles are available via this endpoint
        """
        article = ArticleModel.find_by_slug(slug)
        if not article:
            return {"message": "Article does not exist"}, 404
        if article.published_date:
            return {"message": "Article already published, it's not in draft list"}, 400
        return article_schema.dump(article), 200
예제 #12
0
    def post(cls, slug):
        """Revoke like from article by logged in user."""
        article = ArticleModel.find_by_slug(slug)
        if not article:
            return {"message": "Article not found"}, 404
        user_id = get_jwt_identity()
        user = UserModel.find_by_id(user_id)

        if not user in article.likes:
            return {"message": "You have to like this article before you can revoke like"}, 403

        article.likes.remove(user)
        article.save_to_db()
        return {"message": "Article with id={} has been disliked by {}".format(article.id, user.username)}, 200
예제 #13
0
    def put(cls, slug: str):
        """
        Update specific article instance
        """
        article = ArticleModel.find_by_slug(slug)
        if not article:
            return {"message": "Article not found"}, 404

        article_json = request.get_json()
        article.description = article_json["description"]
        article.content = article_json["content"]
        article.save_to_db()

        return article_schema.dump(article), 200
예제 #14
0
def insert():
    if flask.session.get('user_id'):
        if flask.request.method == 'GET':
            user1 = UserModel.query.filter(UserModel.id == session.get('user_id')).first()
            context={'user':user1}
            return flask.render_template('insert.html',**context)
        else:
            title=flask.request.form.get('title')
            article=flask.request.form.get('content')
            article_all=ArticleModel(title=title,article=article)
            db.session.add(article_all)
            db.session.commit()
            return u'发布成功!'
    else:
        return redirect(url_for('login'))
예제 #15
0
    def post(cls):
        """
        Create new article.

        Article published_date field is not set which means is not available
        publicly.
        """
        article_json = request.get_json()
        article_data = article_schema.load(article_json)

        if ArticleModel.find_by_title(article_data.title):
            return {"message": "Article with given title already exists"}

        article_data.save_to_db()
        return article_schema.dump(article_data), 201
예제 #16
0
    def put(cls, slug):
        """
        Assign tags to specific article instance.
        """
        article = ArticleModel.find_by_slug(slug)
        if not article:
            return {"message": "Article does not exist"}, 404
        tags = request.get_json()["tags"]
        article.tags = []
        for tag in tags:
            tag_object = TagModel.get_or_create(name=tag)
            if not tag_object in article.tags:
                article.tags.append(tag_object)
        article.save_to_db()

        return article_schema.dump(article), 200
예제 #17
0
    def post(cls, slug):
        """
        Publish article instance by setting it's published_date field.
        """
        article = ArticleModel.find_by_slug(slug)
        if not article:
            return {"message": "Article not found"}, 404
        if not article.image_url:
            return {"message": "Article must contain image before publishing"}, 400
        if article.tags == []:
            return {"message": "Article must have at least one tag assigned"}, 400
        if article.published_date:
            return {"message": "Article has been already published"}, 400

        article.publish()
        return {"message": "Article has been published"}, 200
예제 #18
0
    def post(cls, slug):
        """Like specific article instance by current logged in user."""
        article = ArticleModel.find_by_slug(slug)
        if not article:
            return {"message": "Article not found"}, 404
        user_id = get_jwt_identity()
        user = UserModel.find_by_id(user_id)

        if user == article.author:
            return {"message": "You can't like your own article"}, 403
        if user in article.likes:
            return {"message": "You can't like this article twice"}, 403

        article.likes.append(user)
        article.save_to_db()
        return {"message": "Article with id={} has been liked by {}".format(article.id, user.username)}, 200
예제 #19
0
 def save(self, link):
     article = self.parse(link)
     with MongoController():
         connect(host=MongoController.host, port=int(MongoController.port))
         ArticleModel(**article).save()
예제 #20
0
 def get(cls):
     """
     Return list of unpublished articles.
     """
     unpublished_articles = ArticleModel.find_all(published=False)
     return article_schema_many.dump(unpublished_articles), 200
예제 #21
0
def index():
    # membuat objek dari kelas ArticleModel
    model = ArticleModel()

    # mengisi nilai ke dalam model
    model.setTitle('Mengenal Flask')
    model.setDate('01/02/2019')
    model.setContent(content)

    # mengirim nilai ke view
    return render_template('article.html',
                           judul=model.getTitle(),
                           tanggal=model.getDate(),
                           isi=model.getContent())
예제 #22
0
 def create_new_article(db:Session, article:ArticleCreate):
     """Insert an article"""
     the_article = ArticleModel(**article.dict())
     db.add(the_article)
     db.commit()
     return the_article
예제 #23
0
 def get(cls):
     """
     Returns list of published articles.
     """
     published_articles = ArticleModel.find_all()
     return article_schema_many.dump(published_articles), 200
예제 #24
0
 def mutate(self, info, text, username):
     article = ArticleModel(text=text,
                            textstate=predict.fake_news_prediction([text]),
                            username=username)
     article.save()
     return CreateArticle(article)