Ejemplo n.º 1
0
def create_post_page():
    session = getSessionFactory().get_session()
    categories = session.query(Categories).order_by(Categories.id).all()
    category_datas = [category.get_map_data() for category in categories]
    session.close()

    return render_template('post.html', username=flask_session['username'], categories=category_datas)
Ejemplo n.º 2
0
def login():
    username = request.json.get('username')
    password = request.json.get('password')

    if not username or not password:
        abort(400, 'bad request')

    sessionFactory = getSessionFactory()
    session = sessionFactory.get_session()
    user = session.query(Admin).filter(Admin.username == username,
                                       Admin.password == password).first()
    session.close()

    if user is None:
        abort(401, 'wrong password')

    resp = make_response()
    resp.headers['Content-Type'] = 'application/json'
    resp.body = json.dumps({'msg': 'ok'})
    resp.status_code = 200
    resp.set_cookie('user_id',
                    str(user.id),
                    max_age=current_app.config['COOKIE_EXPIRE'])
    resp.set_cookie('username',
                    user.username,
                    max_age=current_app.config['COOKIE_EXPIRE'])

    return resp
Ejemplo n.º 3
0
def upload_resource():
    if 'file' not in request.files:
        abort(400, 'no file has been uploaded.')
    file = request.files['file']
    if file.filename == '':
        abort(400, 'no file has been uploaded')

    file_extension = get_file_extension(file.filename)
    if file and allowed_file(file_extension,
                             current_app.config['ALLOWED_EXTENSIONS']):
        ret = upload_file_to_qiniu(current_app.config['QINIU_ACCESS_KEY'],
                                   current_app.config['QINIU_SECRET_KEY'],
                                   current_app.config['QINIU_BUCKET_NAME'],
                                   file.filename, file.read())
        if not ret['ret']:
            abort(500, ret['msg'])
    else:
        abort(400, 'not allowed file type.')

    url = f"http://{current_app.config['QINIU_BUCKET_URL']}/{ret['key']}"
    file_type = get_file_type(file_extension)

    sessionFactory = getSessionFactory()
    session = sessionFactory.get_session()

    new_resource = Resources(0, file.filename, file_type, url)
    session.add(new_resource)
    session.commit()
    session.close()

    return jsonify({'msg': 'ok'})
Ejemplo n.º 4
0
def get_article(post_id):
    session = getSessionFactory().get_session()
    article = session.query(Articles).filter(Articles.id == post_id).first()
    session.close()
    if not article:
        abort(404)
    return jsonify(article.get_map_data())
Ejemplo n.º 5
0
def create_post():
    title = request.form['title']
    content = request.form['content']
    category = request.form['category']
    tags = request.form['tags']
    if request.form.get('time', None):
        post_time = datetime.datetime.fromtimestamp(request.form.get('time'))
    else:
        post_time = datetime.datetime.now()
    try:
        if not title or not content or not category:
            abort(400, 'invalid request')
        session = getSessionFactory().get_session()
        new_article = Articles(title, content, post_time, 0, int(category))
        session.add(new_article)

        tags = tags.split('|')
        for tag in tags:
            this_tag = session.query(Tags).filter(Tags.name == tag).first()
            if not this_tag:
                this_tag = Tags(tag)
            this_tag.articles.append(new_article)
            session.add(this_tag)

        session.commit()
        session.close()
    except Exception as e:
        print(e)
        return redirect(url_for('admin.create_post'))
    else:
        return redirect(url_for('admin.index'))
Ejemplo n.º 6
0
def create_article():
    data = request.json

    title = data.get('title', None)
    content = data.get('content', None)
    time = data.get('time', None)
    category = data.get('category_id', None)
    tags = data.get('tags', None)

    if not title or not content or not category:
        abort(400, 'invalid request')

    session = getSessionFactory().get_session()
    article = Articles(title, content, time, 0, category)
    session.add(article)

    for tag in tags:
        this_tag = session.query(Tags).filter(Tags.name == tag).first()
        if not this_tag:
            this_tag = Tags(tag)
        this_tag.articles.append(article)
        session.add(this_tag)

    session.commit()
    session.close()

    return jsonify({'msg': 'ok'})
Ejemplo n.º 7
0
def delete_post(post_id):
    sessionFactory = getSessionFactory()
    session = sessionFactory.get_session()
    article = session.query(Articles).filter(Articles.id == post_id).first()

    if not article:
        abort(404, 'article not found')

    session.delete(article)
    session.commit()
    session.close()
    return redirect(url_for('admin.index'))
Ejemplo n.º 8
0
def delete_article(post_id):
    sessionFactory = getSessionFactory()
    session = sessionFactory.get_session()
    article = session.query(Articles).filter(Articles.id == post_id).first()

    if not article:
        abort(404, 'article not found')

    session.delete(article)
    session.commit()
    session.close()

    return jsonify({'msg': 'ok'})
Ejemplo n.º 9
0
def get_simple_about_me():
    try:
        session_factory = getSessionFactory()
        session = session_factory.get_session()
        about = session.query(About).filter(About.type == 0).first()
        if not about:
            return jsonify({})
        data = about.get_map_data()
    except Exception as e:
        abort(500, 'something is wrong')
    finally:
        session.close()

    return jsonify(data)
Ejemplo n.º 10
0
def get_categories():
    try:
        session = getSessionFactory().get_session()
        categories = session.query(Categories).order_by(Categories.id).all()
        session.close()

        datas = []
        for category in categories:
            datas.append(category.get_map_data())
    except Exception as e:
        abort(500, 'something is wrong')
    finally:
        session.close()

    return jsonify({'datas': datas})
Ejemplo n.º 11
0
def resource_manage():
    query_data = request.args

    page = int(query_data.get('page', 1))
    size = int(query_data.get('size', current_app.config['ARTICLE_PER_PAGE']))

    if page <= 0 or size <= 0:
        abort(400)

    offset, limit = get_page(page, size)
    session = getSessionFactory().get_session()
    resources = session.query(Resources) \
                .order_by(Resources.id.desc()).offset(offset).limit(limit).all()
    resources_data = [resource.get_map_data() for resource in resources]
    return render_template('resourceUpload.html', resources = resources_data)
Ejemplo n.º 12
0
def get_edit_post_page(post_id):
    session = getSessionFactory().get_session()
    article = session.query(Articles).filter(Articles.id == post_id).first()
    categories = session.query(Categories).order_by(Categories.id).all()
    if not article:
        abort(404)

    article = article.get_map_data()
    tags = '|'.join([tag['name'] for tag in article['tags']])
    category = article['category']
    article['category'] = category['name']
    article['tags'] = tags
    categories = [category.get_map_data() for category in categories]
    session.close()
    return render_template('post_edit.html', username=flask_session['username'], post=article, categories=categories)
Ejemplo n.º 13
0
def update_post(post_id):
    title = request.form['title']
    content = request.form['content']
    category = request.form['category']
    tags = request.form['tags'].split('|')

    try:
        sessionFactory = getSessionFactory()
        session = sessionFactory.get_session()

        article = session.query(Articles).filter(Articles.id == post_id).first()

        if not article:
            abort(404, 'post not found')

        article.title = title
        article.content = content
        article.category_id = category
        article.tags = []

        for tag in tags:
            this_tag = session.query(Tags).filter(Tags.name == tag).first()
            if not this_tag:
                this_tag = Tags(tag)
            this_tag.articles.append(article)
            session.add(this_tag)
        # already_exists_tags = [tag.name for tag in article.tags]
        # need_remove_tags = list(set(already_exists_tags) - set(tags))
        # for tag in tags:
        #     if tag not in already_exists_tags:
        #         this_tag_model = session.query(
        #             Tags).filter(Tags.name == tag).first()
        #         if not this_tag_model:
        #             this_tag_model = Tags(tag)
        #         this_tag_model.articles.append(article)
        #         session.add(this_tag_model)
        # for tag in need_remove_tags:
        #     this_tag_model = session.query(Tags).filter(Tags.name == tag).first()
        #     article.tags.remove(this_tag_model)

        session.commit()
        session.close()
    except Exception as e:
        print(e)
        # return redirect(url_for('admin.get_edit_post_page', post_id=post_id))
        raise e
    else:
        return redirect(url_for('admin.index'))
Ejemplo n.º 14
0
def get_article(post_id):
    try:
        session = getSessionFactory().get_session()
        article = session.query(Articles).filter(
            Articles.id == post_id).first()
        if not article:
            session.close()
            abort(404)

        data = article.get_map_data()
    except Exception as e:
        abort(500, 'something is wrong')
    finally:
        session.close()

    return jsonify(data)
Ejemplo n.º 15
0
def get_tag_articles(tag_id):
    try:
        session_factory = getSessionFactory()
        session = session_factory.get_session()
        tag = session.query(Tags).filter(Tags.id == tag_id).first()
        if not tag:
            abort(404, 'no such tag')
        datas = []
        for article in tag.articles:
            datas.append(article.get_map_data())
    except Exception as e:
        abort(500, 'something has wrong')
    finally:
        session.close()

    return jsonify({'posts': datas, 'id': tag.id, 'name': tag.name})
Ejemplo n.º 16
0
    def handle_args(*args, **kwargs):
        user_id = flask_session.get('user_id', None)
        username = flask_session.get('username', None)

        if not user_id or not username:
            return redirect(url_for('admin.login_page'))

        sessionFactory = getSessionFactory()
        query_session = sessionFactory.get_session()
        user = query_session.query(Admin).filter(
            Admin.id == int(user_id), Admin.username == username).first()
        query_session.close()

        if user is None:
            return redirect(url_for('admin.login_page'))

        return func(*args, **kwargs)
Ejemplo n.º 17
0
    def handle_args(*args, **kwargs):
        user_id = request.cookies.get('user_id', None)
        username = request.cookies.get('username', None)

        if not user_id or not username:
            abort(401, 'unauthorized')

        sessionFactory = getSessionFactory()
        query_session = sessionFactory.get_session()
        user = query_session.query(Admin).filter(
            Admin.id == int(user_id), Admin.username == username).first()
        query_session.close()

        if user is None:
            abort(401, 'unauthorized')

        return func(*args, **kwargs)
Ejemplo n.º 18
0
def get_login_status():
    user_id = request.cookies.get('user_id', None)
    username = request.cookies.get('username', None)

    if not user_id or not username:
        return jsonify({'status': False})

    sessionFactory = getSessionFactory()
    session = sessionFactory.get_session()
    user = session.query(Admin).filter(Admin.id == int(user_id),
                                       Admin.username == username).first()
    session.close()

    if user is None:
        return jsonify({'status': False})

    return jsonify({'status': True})
Ejemplo n.º 19
0
def get_tags():
    try:
        session_factory = getSessionFactory()
        session = session_factory.get_session()
        sql = '''
        select Tag.tag_id, Tag.name, count(1) as count from tag_article as ta 
        left join Tag on ta.tag_id = Tag.tag_id 
        group by(tag_id) order by count desc, Tag.tag_id
        '''
        tags = session.execute(sql)
        datas = []
        for tag in tags:
            datas.append(dict(id=tag[0], name=tag[1]))
    except Exception as e:
        abort(500, 'something is wrong')
    finally:
        session.close()

    return jsonify({'datas': datas})
Ejemplo n.º 20
0
def index():
    query_data = request.args

    page = int(query_data.get('page', 1))
    size = int(query_data.get('size', current_app.config['ARTICLE_PER_PAGE']))

    if page <= 0 or size <= 0:
        abort(400)

    offset, limit = get_page(page, size)
    session = getSessionFactory().get_session()
    articles = session.query(Articles).order_by(
        Articles.id).offset(offset).limit(limit).all()
    article_datas = [article.get_map_data() for article in articles]
    categories = session.query(Categories).order_by(Categories.id).all()
    category_datas = [category.get_map_data() for category in categories]
    session.close()

    return render_template('index.html', posts=article_datas, 
    username=flask_session['username'], categories=category_datas)
Ejemplo n.º 21
0
def update_article(post_id):
    data = request.json

    title = data.get('title', None)
    content = data.get('content', None)
    time = data.get('time', None)
    category = data.get('category_id', None)
    tags = data.get('tags', None)

    sessionFactory = getSessionFactory()
    session = sessionFactory.get_session()

    article = session.query(Articles).filter(Articles.id == post_id).first()

    if not article:
        abort(404, 'post not found')

    article.title = title
    article.content = content
    if time:
        article.time = time
    article.category_id = category

    already_exists_tags = [tag.name for tag in article.tags]
    need_remove_tags = list(set(already_exists_tags) - set(tags))
    for tag in tags:
        if tag not in already_exists_tags:
            this_tag_model = session.query(Tags).filter(
                Tags.name == tag).first()
            if not this_tag_model:
                this_tag_model = Tags(tag)
            this_tag_model.articles.append(article)
            session.add(this_tag_model)
    for tag in need_remove_tags:
        this_tag_model = session.query(Tags).filter(Tags.name == tag).first()
        article.tags.remove(this_tag_model)

    session.commit()
    session.close()

    return jsonify({'msg': 'ok'})
Ejemplo n.º 22
0
def get_articles():
    query_data = request.args

    page = int(query_data.get('page', 1))
    size = int(query_data.get('size', current_app.config['ARTICLE_PER_PAGE']))

    if page <= 0 or size <= 0:
        abort(400)

    offset, limit = get_page(page, size)

    session = getSessionFactory().get_session()
    articles = session.query(Articles).order_by(
        Articles.id).offset(offset).limit(limit).all()
    session.close()

    datas = []
    for article in articles:
        datas.append(article.get_map_data())

    return jsonify({'datas': datas, 'pager': {'page': page, 'size': size}})
Ejemplo n.º 23
0
def add_post_view(post_id):
    identify = flask_session.get('identify', None)
    add_flag = False

    redis_conn = getRedisConnection()

    if identify:
        if redis_conn.get(
                f"POST_VISIT_HISTORY:{identify}:{post_id}") is not None:
            pass
        else:
            add_flag = True
    else:
        identify = get_random_string()
        add_flag = True

    if add_flag:
        try:
            session_factory = getSessionFactory()
            session = session_factory.get_session()
            article = session.query(Articles).filter(
                Articles.id == post_id).first()
            if not article:
                return jsonify({'ret': False})
            article.views += 1
            session.add(article)
            session.commit()
            redis_conn.setex(f"POST_VISIT_HISTORY:{identify}:{post_id}",
                             current_app.config['PERMANENT_SESSION_LIFETIME'],
                             1)
            flask_session.permanent = True
            flask_session['identify'] = identify
        except Exception as e:
            raise e
            abort(500, 'something is wrong')
        finally:
            session.close()

    return jsonify({'ret': True})
Ejemplo n.º 24
0
def get_articles_by_category(category_id):
    query_data = request.args

    page = int(query_data.get('page', 1))
    size = int(query_data.get('size', current_app.config['ARTICLE_PER_PAGE']))

    if page <= 0 or size <= 0:
        abort(400)

    offset, limit = get_page(page, size)

    try:
        session = getSessionFactory().get_session()
        category = session.query(Categories).filter(
            Categories.id == category_id).first()
        if not category:
            abort(404, 'no such category')

        articles = session.query(Articles).filter(
            Articles.category_id == category_id).order_by(
                Articles.id.desc()).offset(offset).limit(limit).all()

        datas = []
        for article in articles:
            datas.append(article.get_map_data())
    except Exception as e:
        abort(500, 'something is wrong')
    finally:
        session.close()

    return jsonify({
        'posts': datas,
        'id': category.id,
        'name': category.name,
        'pager': {
            'page': page,
            'size': size
        }
    })
Ejemplo n.º 25
0
def login():
    username = request.form['username']
    password = request.form['password']
    try:
        if not username or not password:
            abort(400, 'bad request')

        sessionFactory = getSessionFactory()
        session = sessionFactory.get_session()
        user = session.query(Admin).filter(
            Admin.username == username, Admin.password == password).first()
        session.close()

        if user is None:
            abort(401, 'wrong password')

        flask_session['user_id'] = user.id
        flask_session['username'] = user.username
    except Exception as e:
        print(e)
        return redirect(url_for('admin.login_page'))
    else:
        return redirect(url_for('admin.index'))
Ejemplo n.º 26
0
def get_archives():
    try:
        session_factory = getSessionFactory()
        session = session_factory.get_session()
        sql = '''
        select Article.article_id, Article.title, Article.views,
        DATE_FORMAT(Article.time, '%Y') as post_year, 
        DATE_FORMAT(Article.time, '%Y-%m-%d') as time
        from Article 
        order by post_year desc, article_id desc
        '''
        posts = session.execute(sql)
        datas = []
        temp = {}
        for post in posts:
            year = post[3]
            post_data = {
                'id': post[0],
                'title': post[1],
                'views': post[2],
                'time': post[4]
            }
            if year in temp:
                temp[year].append(post_data)
            else:
                temp[year] = [post_data]

        for year in sorted(temp, reverse=True):
            datas.append(dict(year=year, posts=temp[year]))

    except Exception as e:
        raise e
        abort(500, 'something is wrong')
    finally:
        session.close()

    return jsonify({'archives': datas})
Ejemplo n.º 27
0
def comment_comment(post_id, comment_id):
    data = request.json

    username = data.get('username', None)
    email = data.get('email', None)
    content = data.get('content', None)
    comment_type = 1

    if not username or not content:
        abort(400, 'bad request')

    try:
        session_factory = getSessionFactory()
        session = session_factory.get_session()
        new_comment = Comments(username, email, None, content, post_id,
                               comment_type, comment_id)
        session.add(new_comment)
        session.commit()
    except Exception as e:
        abort(500, 'something is wrong')
    finally:
        session.close()

    return jsonify({'ret': True})