Esempio n. 1
0
def delete_post(args, logger):
    """
    Removes post specified by title from posts directory directory and
    from the db
    """
    def delete_from_dir(title):
        post_path = get_post_path(title)
        if os.path.isfile(post_path):
            os.remove(post_path)
            logger.info("Removed {}".format(post_path))
        else:
            logger.info("Error: Could not find {}".format(post_path))

    def delete_from_db(title):
        slug = slugify(title)
        post_model = db.session.query(Post).filter_by(slug=slug).first()
        if post_model:
            db.session.delete(post_model)
            db.session.commit()
            logger.info('Removed "{}" from the db'.format(title))
        else:
            logger.info('Error: Could not find "{}" in the db'.format(title))

    db = get_db()
    delete_from_dir(args.title)
    delete_from_db(args.title)
Esempio n. 2
0
def load_logged_in_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()
Esempio n. 3
0
def get_post(id, check_author=True):
    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
Esempio n. 4
0
def bulk_publish_posts(args, logger):  # pylint: disable=W0613
    " Publish all non-published posts from static posts directory "
    db = get_db()
    unpublished_posts = db.session.query(Post).filter(~Post.published)
    num_unpub = unpublished_posts.count()

    if num_unpub > 0:
        for post in unpublished_posts:
            post.title = title_case(post.title)
            publish_post(post, logger)
        logger.info("Bulk publish complete -- published {} posts!".format(num_unpub))
    else:
        logger.info("Bulk publish complete -- no unpublished posts found!")
Esempio n. 5
0
def fix_img_size():
    '''
    修复数据库中图片尺寸
    :return:
    '''
    session = get_db()['session']
    shares = session.query(Share).all()
    for item in shares:
        if item.img_width is None or item.img_width == '':
            img_path = get_image_save_path(item.img_hash, THUMB_SIZE_ORIGIN, 'jpg')
            image_one = Image.open(img_path)
            if image_one is not None:
                # 图片尺寸处理
                image_w = image_one.size[0]
                image_h = image_one.size[1]
                item.img_width =image_w
                item.img_height=image_h
                session.flush()
    session.commit()
Esempio n. 6
0
def create():
    if request.method == 'POST':
        title = request.form['title']
        body = request.form['body']
        error = None

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

        if error is not None:
            flash(error)
        else:
            db = get_db()
            db.execute(
                'INSERT INTO post (title, body, author_id)'
                ' VALUES (?, ?, ?)', (title, body, g.user['id']))
            db.commit()
            return redirect(url_for('blog.index'))

    return render_template('blog/create.html')
Esempio n. 7
0
def update(id):
    post = get_post(id)

    if request.method == 'POST':
        title = request.form['title']
        body = request.form['body']
        error = None

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

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

    return render_template('blog/update.html', post=post)
Esempio n. 8
0
def list_posts(args, logger):  # pylint: disable=W0613
    " List published and unpublished posts "

    def display_posts(posts):
        for p in posts:
            print p.title

    db = get_db()
    published_posts = db.session.query(Post).filter(Post.published).order_by(Post.published_dt.desc())
    unpublished_posts = db.session.query(Post).filter(~Post.published)

    # Print and format published posts
    div = "=" * 20
    print "\n{}\nPublished Posts:\n{}\n".format(div, div)
    if published_posts:
        display_posts(published_posts)

    # Print and format unpublished posts
    print "\n{}\nUnpublished Posts:\n{}\n".format(div, div)
    if unpublished_posts:
        display_posts(unpublished_posts)
Esempio n. 9
0
def login():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        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:
            session.clear()
            session['user_id'] = user['id']
            return redirect(url_for('index'))

        flash(error)

    return render_template('auth/login.html')
Esempio n. 10
0
def register():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        db = get_db()
        error = None

        if 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 {} is already registered.'.format(username)

        if error is None:
            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')
Esempio n. 11
0
def delete(id):
    get_post(id)
    db = get_db()
    db.execute('DELETE FROM post WHERE id = ?', (id, ))
    db.commit()
    return redirect(url_for('blog.index'))
Esempio n. 12
0
def blog():
    db = get_db()
    posts = 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)
Esempio n. 13
0
def podcasts():
    db = get_db()
    podcasts = get_podcasts(db)

    return render_template('index.html', entries=podcasts)
Esempio n. 14
0
def publish_post(args, logger, force=False):
    """
    Persists post to database based on passed args and metadata from static
    post file. A post can be considered "published" once this function is run.

    There are two types of publishing:

    Normal -- sets published_dt to the current time. This post will be
              listed in the posts index and will be included in previous/next
              links.

     Draft -- sets published_dt to None. This post will not appear in the posts
              index and will not be included in previous/next links. However,
              this post can still be viewed through the slug url. This is
              useful if you want to publish your post for select review
              without displaying a link for everyone to see.

    In both cases the post model will be updated and committed to the db. Also,
    new tag models are created if a post includes tags that do not already exist
    in the db.

    Note: We use the post title and env defined post directory to locate which
    static file to use. This is done for convenience so a user can simply type
    in the name of their post instead of a full file path.
    """
    # Open the file and extract attributes
    post_path = get_post_path(args.title)
    try:
        with open(post_path, 'r') as f:
            author = f.readline().strip('n')
            _ = f.readline() # Title line, don't need
            tags = f.readline().strip('\n')
            _ = f.readline() # Line seperating content, don't need
            content = f.read()
    except IOError:
        logger.info("Error: Could not find {}".format(post_path))
        return

    # Process attributes
    author = parse_attr(author)
    slug = slugify(args.title)
    tags = parse_attr(tags).split(', ')
    if '' in tags:
        tags.remove('')

    # If this is a draft post, don't set the publish date
    published_dt = None if args.draft else func.now()

    # Backup posts in production
    if app_config.ENV == 'prod':
        make_backup(app_config.POSTS_DIR, app_config.BACKUP_POSTS_DIR, logger)

    # Prompt whether to delete post if already exists in db
    db = get_db()
    p = db.session.query(Post).filter_by(title=args.title).first()
    if p:
        if not force:
            resp = raw_input("Post with title '{}' already exists in db! Do you want to overwite (y/n)? "\
                   .format(args.title))
            if resp != 'y':
                logger.info("'{}' was not added to the db".format(args.title))
                return
        db.session.delete(p)
        db.session.commit()

    # Create post
    new_post = Post(author=author, title=args.title, slug=slug,
                    content=content, published_dt=published_dt)
    db.session.add(new_post)
    db.session.commit()

    if tags:
        # Add new tags to db
        new_tags = get_new_tags(db, tags)
        db.session.add_all(new_tags)
        db.session.commit()

        # Assign tags to post
        tags = get_tags(db, tags)
        new_post.tags = tags
        db.session.add(new_post)
        db.session.commit()

    action_msg = "Draft published" if args.draft else "Published"
    logger.info("{} {}!".format(action_msg, args.title))
Esempio n. 15
0
    def all_contacts():
        if request.method == 'GET':
            # agafem les dades de la base de dades fent una consulta
            db = get_db()

            data = db.execute(
                ' SELECT id, nom, cognoms, correu, telf, pais, address, poblacio, codipostal, provincia, NIF '
                ' FROM contacts ').fetchall()

            # amb aquesta linea fem un bucle amb les dades trobades i les pasa a JSON
            cont = [{
                'id': contacts['id'],
                'nom': contacts['nom'],
                'cognoms': contacts['cognoms'],
                'correu': contacts['correu'],
                'telf': contacts['telf'],
                'pais': contacts['pais'],
                'address': contacts['address'],
                'poblacio': contacts['poblacio'],
                'codipostal': contacts['codipostal'],
                'provincia': contacts['provincia'],
                'NIF': contacts['NIF']
            } for contacts in data]

            return jsonify(cont)

        elif request.method == 'POST':
            # ens conectem a la base de dades, i recollim les dades que ens envia el POST
            db = get_db()
            post_data = request.get_json()

            # executem una transacció amb un INSERT amb les dades
            db.execute(' BEGIN TRANSACTION ')

            db.execute(
                'INSERT INTO contacts (nom, cognoms, correu, telf, pais, address, poblacio, codipostal, provincia, NIF) VALUES (?,?,?,?,?,?,?,?,?,?)',
                (post_data.get('nom'), post_data.get('cognoms'),
                 post_data.get('correu'), post_data.get('telf'),
                 post_data.get('pais'), post_data.get('address'),
                 post_data.get('poblacio'), post_data.get('codipostal'),
                 post_data.get('provincia'), post_data.get('NIF')))

            db.execute(' COMMIT ')

            return ("Contact added!")

        elif request.method == 'DELETE':
            # ens conectem a la base de dades, i recollim les dades que ens envia al DELETE
            db = get_db()
            id_contact = request.args.get("index")

            # executem una transacció amb un DELETE de les dades
            db.execute(' BEGIN TRANSACTION ')

            db.execute('DELETE FROM contacts WHERE id = ?', (id_contact))

            db.execute(' COMMIT ')

            return ("Contact deleted!")

        elif request.method == 'PUT':
            # ens conectem a la base de dades
            db = get_db()
            post_data = request.get_json()

            # executem una transacció amb un UPDATE amb les dades
            db.execute(' BEGIN TRANSACTION ')

            db.execute(
                'UPDATE contacts SET nom = ?, cognoms = ?, correu = ?, telf = ?, pais = ?, address = ?, poblacio = ?, codipostal = ?, provincia = ?, NIF = ? WHERE id = ?',
                (post_data.get('nom'), post_data.get('cognoms'),
                 post_data.get('correu'), post_data.get('telf'),
                 post_data.get('pais'), post_data.get('address'),
                 post_data.get('poblacio'), post_data.get('codipostal'),
                 post_data.get('provincia'), post_data.get('NIF'),
                 post_data.get('id')))

            db.execute(' COMMIT ')

            return ("Contact updated!")
        else:
            return ("ok")
Esempio n. 16
0
 def setup_class(cls):
     cls.db = get_db()
     Base.metadata.create_all(cls.db.engine)