コード例 #1
0
ファイル: blog.py プロジェクト: cgjue/cblog.site
def delete(id):
    """Delete a post.

    Ensures that the post exists and that the logged in user is the
    author of the post.
    """
    get_post(id)
    get_db().execute('DELETE FROM post WHERE id = ?', (id,))
    get_db().commit()
    return redirect(url_for('blog.index'))
コード例 #2
0
def admin():
    posts = get_db().execute(
        'SELECT p.id, title, created, updated, author_id, username'
        ' FROM post p JOIN user u ON p.author_id = u.id'
        ' WHERE p.author_id = ?',
        (session['user_id'],)
    ).fetchall()
    uploadfiles = get_db().execute('SELECT id, fpath, created from '
        'uploadfile where user_id = ?', 
        (session['user_id'], )
    ).fetchall()
    return render_template('admin/admin.html', **locals())
コード例 #3
0
def upload_img():
    # check if the post request has the file part
    message = ''
    if 'file' not in request.files:
        message = 'No file part'
    else:
        file = request.files.get('file', default=None)
        # if user does not select file, browser also
        # submit an empty part without filename
        if not file or file.filename == '':
            message = 'No selected file'
        elif not allowed_file(file.filename):
            message = u'禁止上传该类型文件'
        else:
            filename = str(int(time.time())) + secure_filename(file.filename)
            file.save(os.path.join(current_app.config['UPLOAD_FOLDER'], filename))
            filepath = os.path.join(current_app.config['UPLOAD_FOLDER'][len(current_app.root_path):],
             filename)
            db = get_db()
            db.execute('INSERT INTO uploadfile(fpath, user_id) VALUES(?, ?)',
            (filepath, session['user_id']))
            db.commit()
            return jsonify({
                "success" : 1,           # 0 表示上传失败,1 表示上传成功
                "message" : message,
                "url"     : filepath       # 上传成功时才返回
            })
    
    return jsonify({
            "success" : 0,           # 0 表示上传失败,1 表示上传成功
            "message" : message,
            "url"     : None        # 上传成功时才返回
    })
コード例 #4
0
ファイル: blog.py プロジェクト: cgjue/cblog.site
def get_post(id, check_author=True):
    """Get a post and its author by id.

    Checks that the id exists and optionally that the current user is
    the author.

    :param id: id of post to get
    :param check_author: require the current user to be the author
    :return: the post with author information
    :raise 404: if a post with the given id doesn't exist
    :raise 403: if the current user isn't the author
    """
    post = get_db().execute(
        'SELECT p.id, title, body, created, author_id, username'
        ' FROM post p JOIN user u ON p.author_id = u.id'
        ' WHERE p.id = ?',
        (id,)
    ).fetchone()

    if post is None:
        abort(404, "Post id {0} doesn't exist.".format(id))

    if check_author and post['author_id'] != g.user['id']:
        abort(403)

    return post
コード例 #5
0
def register():
    """Register a new user.

    Validates that the username is not already taken. Hashes the
    password for security.
    """
    if request.method == 'POST':
        username = request.form.get('username', default=None)
        password = request.form.get('password', default=None)
        welcode = request.form.get('welcode', default=None)
        db = get_db()
        error = None
        if not welcode or db.execute(
                'SELECT welcode FROM welcode WHERE welcode = ?',
            (welcode, )).fetchone() is None:
            error = u"非受邀用户,Go Out!"
        elif not username:
            error = 'Username is required.'
        elif not password:
            error = 'Password is required.'
        elif db.execute('SELECT id FROM user WHERE username = ?',
                        (username, )).fetchone() is not None:
            error = 'User {0} is already registered.'.format(username)

        if error is None:
            # the name is available, store it in the database and go to
            # the login page
            db.execute('INSERT INTO user (username, password) VALUES (?, ?)',
                       (username, generate_password_hash(password)))
            db.commit()
            return redirect(url_for('auth.login'))

        flash(error)
    return render_template('auth/register.html')
コード例 #6
0
ファイル: blog.py プロジェクト: cgjue/cblog.site
def comment(post_id):
    """
        add comment ,need user login
    """
    if g.user is None:
        return jsonify({'status':False, 'msg': '请先登录' })
    content = request.form.get('content', '')
    
    if not content.strip():
        return jsonify({'status': False, 'msg': '评论内容为空'})
    get_db().execute(
        'INSERT INTO comment(post_id, user_id, content)'
        ' VALUES(?, ?, ?)',
        (post_id, g.user['id'], content))
    get_db().commit()
    
    return jsonify({'status': True, 'msg': 'ok'})
コード例 #7
0
ファイル: blog.py プロジェクト: cgjue/cblog.site
def index():
    """Show all the posts, most recent first."""
    
    posts = get_db().execute(
        'SELECT p.id, title, body, created, author_id, username'
        ' FROM post p JOIN user u ON p.author_id = u.id'
        ' ORDER BY created DESC'
    ).fetchall()
    return render_template('blog/index.html', posts=posts)
コード例 #8
0
ファイル: plugin.py プロジェクト: cgjue/cblog.site
def get_plugin():
    """Connect to the application's configured database. The connection
    is unique for each request and will be reused if this is called
    again.
    """
    if 'plugin_matrix' not in g:
        db = get_db()
        plugin = db.execute('select name,script, id from plugin').fetchall()
        return plugin
コード例 #9
0
def load_logged_in_user():
    """If a user id is stored in the session, load the user object from
    the database into ``g.user``."""
    user_id = session.get('user_id')

    if user_id is None:
        g.user = None
    else:
        g.user = get_db().execute('SELECT * FROM user WHERE id = ?',
                                  (user_id, )).fetchone()
コード例 #10
0
ファイル: blog.py プロジェクト: cgjue/cblog.site
def category(id=None):
    if id is None:
        return redirect(url_for('blog.index'))
    else:
        _id = id.split('_')[0]
        category = get_db().execute(
            'SELECT value FROM category where id = ?',
            (_id, )
        ).fetchone()
        if category is None:
            return render_template('404.html')
        posts = get_db().execute(
        'SELECT p.id, title, body, created, author_id, username'
        ' FROM post p JOIN user u ON p.author_id = u.id'
        ' WHERE p.id in (SELECT post_id from category_post'
        ' WHERE category_id = ? ) ORDER BY created DESC',
        (_id,)
        ).fetchall()
        return render_template('blog/category.html', posts = posts, category = category)
コード例 #11
0
def deleteFile(id):
    db = get_db()
    uploadfile = db.execute('SELECT fpath from uploadfile WHERE id = ? and user_id = ?',
    (id, session['user_id'])).fetchone()
    if uploadfile is None:
        return jsonify({'status':-1, 'msg':u'该文件不存在'})
    db.execute('DELETE FROM uploadfile WHERE id = ? and user_id = ?', (id, session['user_id']))
    db.commit()
    os.remove(current_app.root_path + uploadfile['fpath'])
    return jsonify({'status':0, 'msg':u'删除成功'})
コード例 #12
0
ファイル: plugin.py プロジェクト: cgjue/cblog.site
def set_plugin(plugin_id, post_id, use):
    db = get_db()
    id = db.execute(
        'select id from use_plugin where plugin_id = ? and post_id = ?',
        (plugin_id, post_id)).fetchone()
    if id:
        db.execute('update use_plugin set use=? where id=?', (use, id['id']))
    else:
        db.execute(
            'insert into use_plugin(plugin_id, post_id, use) values(?,?,?)',
            (plugin_id, post_id, use))
    db.commit()
コード例 #13
0
ファイル: plugin.py プロジェクト: cgjue/cblog.site
def add_plugin(name, script):
    db = get_db()
    has = db.execute('select id from plugin where name = ?',
                     (name, )).fetchone()
    if has:
        return has['id']
    else:
        db.execute('INSERT INTO plugin(name, script) VALUES(?, ?)',
                   (name, script))
        db.commit()
        id = db.execute('select id from plugin where name = ?',
                        (name, )).fetchone()
        return id['id']
コード例 #14
0
ファイル: blog.py プロジェクト: cgjue/cblog.site
def update(id):
    """Update a post if the current user is the author."""
    post = get_post(id)

    if request.method == 'POST':
        title = request.form.get('title',default = None)
        body = request.form.get('body', default = None)
        error = None

        if not title:
            error = 'Title is required.'

        if error is not None:
            flash(error)
        else:
            get_db().execute(
                'UPDATE post SET title = ?, body = ? WHERE id = ?',
                (title, body, id)
            )
            get_db().commit()
            return redirect(url_for('blog.index'))

    return render_template('blog/update.html', post=post)
コード例 #15
0
def plugin_query():
    posts = get_db().execute(
        'SELECT p.id, title, author_id'
        ' FROM post p JOIN user u ON p.author_id = u.id'
        ' WHERE p.author_id = ?',
        (session['user_id'],)
    ).fetchall()
    plugin_list = plugin.get_plugin()
    plugin_use = plugin.use_plugin_all()
    return jsonify({
        "posts": posts,
        "plugin_list": plugin_list,
        "plugin_use": plugin_use,
    })
コード例 #16
0
ファイル: blog.py プロジェクト: cgjue/cblog.site
def create():
    """Create a new post for the current user."""
    if request.method == 'POST':
        title = request.form.get('title',default = None)
        body = request.form.get('body', default = None)
        category_ids = request.form.getlist('categories')
        error = None
        if not category_ids:
            error = 'category is required.'
        elif not title:
            error = 'Title is required.'
        elif not body:
            error = 'Content is required.'

        if error is not None:
            flash(error)
        else:
            db = get_db()
            
            post_id = -1
            try:
                db.execute(
                'INSERT INTO post (title, body, author_id)'
                ' VALUES (?, ?, ?)',
                (title, body, g.user['id'])
                )
		
                post_id = db.execute(
                'SELECT max(id) as mid FROM post'
            ).fetchone()['mid']
                print(post_id)
                db.commit()
            except Exception as e:
                print(e)
                traceback.print_exc()
            if post_id != -1: 
                print(category_ids)
                for cid in category_ids:
                    db.execute(
                        'INSERT INTO category_post(category_id, post_id)'
                        'VALUES (?, ?)',
                        (cid, post_id)
                    )
                db.commit()
            else:
                print('insert error')
        return redirect(url_for('blog.index'))

    return render_template('blog/create.html')
コード例 #17
0
def deleteCategory():
    category_ids = request.form.getlist('categories')
    if category_ids:
        db = get_db()
        for category_id in category_ids:
            if db.execute(
                'SELECT value FROM category WHERE id = ? and user_id = ?',
                (category_id, session['user_id'])
            ).fetchone() is not None:
                db.execute(
                'DELETE FROM category where id = ?',
                (category_id, )
                )
                db.commit()
    return redirect(url_for('admin.admin'))
コード例 #18
0
def addCategory():
    category = request.form.get("category", default=None)
    error = None
    if not category:
        error = u"类别不能为空!"
        flash(error)
    else:
        db = get_db()
        if db.execute(
            'SELECT value FROM category WHERE value = ?',
            (category, )
        ).fetchone() is None:
            db.execute(
            'INSERT into category(value, user_id) VALUES(?, ?)',
            (category, session['user_id'] )
            )
            db.commit()
    return redirect(url_for('admin.admin'))
コード例 #19
0
def upload():
    # check if the post request has the file part
    if 'file' not in request.files:
        flash('No file part')
    else:
        file = request.files.get('file', default=None)
        # if user does not select file, browser also
        # submit an empty part without filename
        if not file or file.filename == '':
            flash('No selected file')
        elif not allowed_file(file.filename):
            flash(u'禁止上传该类型文件')
        else:
            filename = str(int(time.time())) + secure_filename(file.filename)
            file.save(os.path.join(current_app.config['UPLOAD_FOLDER'], filename))
            db = get_db()
            db.execute('INSERT INTO uploadfile(fpath, user_id) VALUES(?, ?)',
            (os.path.join(current_app.config['UPLOAD_FOLDER'][len(current_app.root_path):],
            filename), session['user_id']))
            db.commit()
    return redirect(url_for('admin.admin'))
コード例 #20
0
def login():
    """Log in a registered user by adding the user id to the session."""
    if request.method == 'POST':
        username = request.form.get('username', default=None)
        password = request.form.get('password', default=None)
        db = get_db()
        error = None
        user = db.execute('SELECT * FROM user WHERE username = ?',
                          (username, )).fetchone()

        if user is None:
            error = 'Incorrect username.'
        elif not check_password_hash(user['password'], password):
            error = 'Incorrect password.'

        if error is None:
            # store the user id in a new session and return to the index
            session.clear()
            session['user_id'] = user['id']
            return redirect(url_for('index'))

        flash(error)

    return render_template('auth/login.html')
コード例 #21
0
ファイル: __init__.py プロジェクト: cgjue/cblog.site
 def get_categories():
     return db.get_db().execute(
         'SELECT id, value FROM category ORDER BY id DESC').fetchall()
コード例 #22
0
ファイル: plugin.py プロジェクト: cgjue/cblog.site
def update_plugin(plugin_id, name, script):
    db = get_db()
    db.execute('update plugin set name=?, script=? where id=?',
               (name, script, plugin_id))
    db.commit()
コード例 #23
0
ファイル: plugin.py プロジェクト: cgjue/cblog.site
def use_plugin(post_id):
    db = get_db()
    return db.execute("select * from use_plugin where post_id=?",
                      (post_id, )).fetchall()
コード例 #24
0
ファイル: plugin.py プロジェクト: cgjue/cblog.site
def use_plugin_all():
    db = get_db()
    return db.execute("select * from use_plugin").fetchall()