Пример #1
0
def delete_config(config_id):
    if request.method == 'POST':
        error = None
        if error is None:
            get_db().execute('delete from config where id=?', (config_id, ))
            get_db().commit()
            return redirect(url_for('mine.config'))
Пример #2
0
def diary(page, page_size):
    if g.baby:
        baby_diary = get_db().execute(
            'select * from manage_diary where baby_id = ? '
            ' and is_deleted=0 order by record_date desc '
            ' limit ?,?',
            (g.baby['id'], (page - 1) * page_size, page_size)).fetchall()
        count = get_db().execute(
            'select count(1) as count from manage_diary where baby_id=?',
            (g.baby['id'], )).fetchone()
        page = {
            'page': page,
            'page_size': page_size,
            'all_page': math.ceil(count['count'] / page_size),
            'page_count': len(baby_diary),
            'count': count['count']
        }
        return render_template('diary/diary.html',
                               baby_diary=baby_diary,
                               page=page)
    else:
        page = {
            'page': 1,
            'page_size': 1,
            'all_page': 1,
            'page_count': 0,
            'count': 0
        }
        return render_template('diary/diary.html', page=page)
Пример #3
0
def album(page=1, page_size=6):
    if g.baby:
        photo = get_db().execute(
            'select * from manage_album where is_deleted=0 '
            ' and baby_id=? order by id desc limit ?,?',
            (g.baby['id'], (page - 1) * page_size, page_size)).fetchall()
        count = get_db().execute('select count(1) as count from manage_album '
                                 ' where is_deleted=0').fetchone()
        page = {
            'page': page,
            'page_size': page_size,
            'all_page': math.ceil(count['count'] / page_size),
            'page_count': len(photo),
            'count': count['count']
        }
        return render_template('album/album.html', photo=photo, page=page)
    else:
        page = {
            'page': 1,
            'page_size': 1,
            'all_page': 1,
            'page_count': 0,
            'count': 0
        }
        return render_template('album/album.html', page=page)
Пример #4
0
def update_footprint(footprint_id):
    file_model = FileModel(g.config['upload_path'])
    footprint_info = get_db().execute(
        'select * from manage_footprint where id=?',
        (footprint_id, )).fetchone()
    if request.method == 'POST':
        record_date = request.form['record_date']
        footprint_name = request.form['footprint_name']
        footprint_desc = request.form['footprint_desc']
        footprint_img = request.files['inputFile']
        error = None
        if footprint_img:
            # upload_path = os.path.join(g.config['upload_path'], 'upload')
            results = file_model.upload_file(footprint_img,
                                             g.config['img_extensions'],
                                             g.config['video_extensions'])
            if results['status'] == 'success':
                footprint_img = '{}/{}'.format('upload/small/',
                                               results['filename'])
            else:
                error = results['msg']
                flash(error)
        else:
            footprint_img = footprint_info['footprint_img']

        if error is None:
            db = get_db()
            baby_model.update_footprint(db, footprint_id, record_date,
                                        footprint_name, footprint_desc,
                                        footprint_img)
            return redirect(url_for('footprint.footprint'))
    return render_template('footprint/footprint_update.html',
                           footprint_info=footprint_info)
Пример #5
0
def test_get_close_db(app):
    with app.app_context():
        db = get_db()
        assert db is get_db()

    with pytest.raises(sqlite3.ProgrammingError) as e:
        db.execute('SELECT 1')

    assert 'closed' in str(e.value)
Пример #6
0
def album_detail(album_id):
    photo = get_db().execute('select * from manage_album  where id=?',
                             (album_id, )).fetchone()
    footprint = get_db().execute(
        'select * from manage_footprint where id = '
        '(select footprint from manage_album where id=?)',
        (album_id, )).fetchone()
    return render_template('album/album_detail.html',
                           photo=photo,
                           footprint=footprint)
Пример #7
0
def load_config():
    g.config = {}
    configs = get_db().execute('select * from config').fetchall()
    for config in configs:
        g.config[config['key']] = config['value']
    new_upload_path = os.path.join(get_current_path(), 'static')
    if new_upload_path != g.config['upload_path']:
        get_db().execute("update config set value=? where key='upload_path'",
                         (new_upload_path, ))
        get_db().commit()
        load_config()
Пример #8
0
def add_config():
    if request.method == 'POST':
        config_key = request.form['configKey']
        config_value = request.form['configValue']
        remarks = request.form['remarks']
        error = None
        if error is None:
            get_db().execute(
                'insert into config(key,value,remarks) values(?,?,?)',
                (config_key, config_value, remarks))
            get_db().commit()
        return redirect(url_for('mine.config'))
Пример #9
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()
        g.baby = get_db().execute(
            'select * from baby_info where user_id=? and is_default=1',
            (user_id, )).fetchone()
        if not g.baby:
            g.baby = get_db().execute(
                'select * from baby_info where user_id=? ',
                (user_id, )).fetchone()
Пример #10
0
def update_diary(diary_id):
    diary = get_db().execute('select * from manage_diary where id=?',
                             (diary_id, )).fetchone()
    if request.method == 'POST':
        record_date = request.form['record_date']
        diary = request.form['diary']
        error = None
        if error is None:
            db = get_db()
            db.execute(
                'update manage_diary set record_date=?, diary=? where id=?',
                (record_date, diary, diary_id))
            db.commit()
            return redirect(url_for('diary.diary', page=1, page_size=5))
    return render_template('diary/diary_detail.html', diary=diary)
Пример #11
0
def register():
    if request.method == 'POST':
        username = request.form['username']
        email = request.form['email']
        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 user_name = ? or email= ?',
                        (username, email)).fetchone() is not None:
            error = 'User {} is already registered.'.format(username)

        if error is None:
            db.execute(
                'INSERT INTO user (user_name, email, password) VALUES (?, ?, ?)',
                (username, email, generate_password_hash(password)))
            db.commit()
            return redirect(url_for('auth.login'))

        flash(error)

    return render_template('auth/register.html')
Пример #12
0
def login():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        print('user_name:{},password:{}'.format(username, password))
        db = get_db()
        error = None
        user = db.execute(
            'SELECT * FROM user WHERE user_name = ? or email = ?',
            (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']
            session['user_name'] = user['user_name']
            return redirect(url_for('baby.home'))

        flash(error)

    return render_template('auth/index.html')
def week_update(id):
    ''' food type update '''

    row = fetch_food_week_one_with_id(id)

    if not row:
        return fail_json('详情数据不存在')

    formData = request.form

    if 'content' not in formData or not formData['content']:
        return fail_json(u'参数异常')

    content = formData['content']

    db = get_db()

    db.execute(
        'UPDATE food_week_list'
        ' SET content=:content'
        ' WHERE autokid = :id', {
            'content': content,
            'id': id
        })

    db.commit()

    return success_json()
Пример #14
0
def type_create():
    ''' food type create'''
    current_app.logger.info(request.form)

    formData = request.form
    if 'name' not in formData or not formData['name']:
        return fail_json(u'参数异常')

    db = get_db()
    name = formData['name']

    row = db.execute('SELECT autokid FROM food_type'
                     ' WHERE name = :name', {
                         'name': name
                     }).fetchone()
    if row:
        return fail_json(u'此类已存在')

    timestamp = int(time.time())
    sort = 0
    if 'sort' in formData:
        sort = int(formData['sort'])

    db.execute(
        'INSERT INTO '
        'food_type (name, sort, ctime, mtime)'
        ' VALUES (?, ?, ?, ?)', (name, sort, timestamp, timestamp))
    db.commit()

    return success_json()
Пример #15
0
def register_activate():
    code = request.args.get('code')

    db = get_db()
    row = db.execute(
        'SELECT * FROM user_email_verify WHERE code=?',
        (code,)
    ).fetchone()

    if row is None:
        return render_template(
            'auth/email_verify_erorr.j2',
            msg='验证失败'
        )
    else:
        row = dict(row)
        ctime = int(time.time())
        if ctime > row['expired']:
            return render_template(
                'auth/email_verify_erorr.j2',
                msg='验证链接已过期'
            )

        db.execute(
            'UPDATE user SET status=1 WHERE email=?',
            (row['email'],)
        )
        db.execute(
            'UPDATE user_email_verify SET expired=0 WHERE id=?',
            (row['id'],)
        )
        db.commit()

        return redirect(url_for('auth.login'))
Пример #16
0
def get_posts(page, pagesize):
    db = get_db()
    posts = db.execute(
        'SELECT p.id, pc.category_id, c.name AS category_name,'
        ' p.title, p.body, p.created, p.author_id, u.username'
        ' FROM post p'
        ' JOIN user u ON p.author_id = u.id'
        ' JOIN post_category pc ON pc.post_id = p.id'
        ' JOIN category c ON c.id = pc.category_id'
        ' ORDER BY p.created DESC'
        ' LIMIT ?, ?', ((page - 1) * pagesize, pagesize)).fetchall()

    for n, p in enumerate(posts):
        o = dict(p)

        o['tag'] = db.execute('SELECT name FROM tag WHERE post_id = ?',
                              (o['id'], )).fetchall()

        current_app.logger.info(o)
        posts[n] = o

    prev_page = (page - 1) if (page - 1) else ''
    next_page = (page + 1) if len(posts) >= pagesize else ''

    return posts, page, prev_page, next_page, pagesize
Пример #17
0
def get_post(id, check_author=True):
    db = get_db()

    post = db.execute(
        'SELECT p.id, pc.category_id,'
        ' the_date, title, body, p.created, author_id, username'
        ' FROM post p'
        ' JOIN user u ON p.author_id = u.id'
        ' JOIN post_category pc ON pc.post_id = p.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)

    post = dict(post)

    tags = db.execute('SELECT name FROM tag WHERE post_id = ?',
                      (post['id'], )).fetchall()

    post['tag'] = ','.join((x['name'] for x in tags))

    current_app.logger.info(post)
    return post
Пример #18
0
def send_register_email(domain, username, email):
    db = get_db()
    code = urlsafe_b64encode(urandom(64)).decode('utf-8')

    # 过期时间30分钟
    delta = timedelta(minutes=30)
    ctime = int(time.time())
    expired = ctime + delta.seconds

    db.execute(
        'INSERT INTO user_email_verify'
        ' (email, code, expired, ctime) VALUES (?,?,?,?)',
        (email, code, expired, ctime)
    )
    db.commit()

    celery = create_celery(current_app)
    celery.send_task(name='tasks.send_register_email',
                     args=[
                         domain,
                         username,
                         email,
                         code
                     ])

    return 'test'
Пример #19
0
def add_footprint():
    file_model = FileModel(g.config['upload_path'])
    if request.method == 'POST':
        record_date = request.form['record_date']
        footprint_name = request.form['footprint_name']
        footprint_desc = request.form['footprint_desc']
        footprint_img = request.files['inputFile']
        error = None
        # upload_path = os.path.join(g.config['upload_path'], 'upload')
        results = file_model.upload_file(footprint_img,
                                         g.config['img_extensions'],
                                         g.config['video_extensions'])
        if results['status'] == 'success':
            footprint_img = '{}/{}'.format('upload/small/',
                                           results['filename'])
        else:
            error = results['msg']
            flash(error)

        if error is None:
            db = get_db()
            baby_model.add_footprint(db, g.user['id'], g.baby['id'],
                                     record_date, footprint_name,
                                     footprint_desc, footprint_img)
            return redirect(url_for('footprint.footprint'))
Пример #20
0
def update_config(config_id):
    this_config = get_db().execute('select * from config where id=?',
                                   (config_id, )).fetchone()
    if request.method == 'POST':
        config_key = request.form['configKey']
        config_value = request.form['configValue']
        remarks = request.form['remarks']

        error = None
        if error is None:
            get_db().execute(
                'update config set key=?,value=?,remarks=? where id=?',
                (config_key, config_value, remarks, config_id))
            get_db().commit()
        return redirect(url_for('mine.config'))
    return render_template('mine/config_detail.html', this_config=this_config)
Пример #21
0
def app():
    db_fd, db_path = tempfile.mkstemp()

    app = create_app({
        'TESTING': True,
        'DATABASE': db_path,
    })

    with app.app_context():
        init_db()
        get_db().executescript(_data_sql)

    yield app

    os.close(db_fd)
    os.unlink(db_path)
Пример #22
0
def history():
    user_id = g.user['id']
    page = request.args.get('page', 1)
    page_size = 10
    offset = (int(page) - 1) * page_size

    db = get_db()

    rows = db.execute(
        'SELECT fl.autokid,'
        ' fl.week, fl.type_id,'
        ' fl.content, fl.ctime,'
        ' ft.name as type_name'
        ' FROM food_list as fl'
        ' LEFT JOIN food_type ft ON ft.autokid = fl.type_id'
        ' WHERE fl.user_id=?'
        ' ORDER BY fl.autokid DESC'
        ' LIMIT ?, ?',
        (user_id, offset, page_size)
    ).fetchall()

    foods = []
    if len(rows) > 0:
        for row in rows:
            tmp = dict(zip(row.keys(), row))
            tmp['week_name'] = WEEK[str(tmp['week'])]['name']
            tmp['timeStr'] = date.fromtimestamp(
                tmp['ctime']).strftime('%Y.%m.%d')
            foods.append(tmp)

    return render_template('food/history.j2',
                           foods=foods,
                           page=page,
                           page_size=page_size
                           )
Пример #23
0
def update(id):
    ''' update '''
    user_id = g.user['id']

    food = fetch_food_one(id, user_id)
    types = get_food_type()

    if food is None:
        flash('修改的数据不存在')
        return redirect(url_for('food.history'))

    if request.method == 'POST':
        formData = request.form
        if 'content' in formData:

            content = formData['content']

            db = get_db()

            db.execute(
                'UPDATE food_list SET content=:content WHERE autokid = :id',
                {'content': content, 'id': id}
            )

            db.commit()

            return redirect(request.referer)
        else:
            flash('更新的内容不存在')

    return render_template('food/update.j2', food=food, types=types)
Пример #24
0
def update_relative(relative_id):
    my_relative = get_db().execute('select * from relative where id=?',
                                   (relative_id, )).fetchone()
    if request.method == 'POST':
        call_name = request.form['call_name']
        really_name = request.form['really_name']
        birthday = request.form['birthday']
        error = None
        if error is None:
            db = get_db()
            db.execute(
                'update relative set call_name=?, really_name=?, birthday=? where id=?',
                (call_name, really_name, birthday, relative_id))
            db.commit()
            return redirect(url_for('mine.relative'))
    return render_template('mine/mine_relative_detail.html',
                           relative=my_relative)
Пример #25
0
def delete(id):
    ''' food delete'''
    db = get_db()

    db.execute('DELETE FROM food_list WHERE autokid = :id', {'id': id})
    db.commit()

    return success_json()
Пример #26
0
def register():
    if request.method == 'POST':
        username = request.form[
            'username'] if 'username' in request.form else ''
        password = request.form[
            'password'] if 'password' in request.form else ''
        email = request.form['email'] if 'email' in request.form else ''
        code = request.form[
            'verification-code'] if 'verification-code' in request.form else ''

        db = get_db()
        error = None

        if not username:
            error = 'Username is required.'
        elif username and registered_username(username):
            error = 'Username has been registered.'
        elif username and not check_username_safe(username):
            error = 'Username is invalidate.'
        elif not password:
            error = 'Password is required.'
        elif password and not check_password_safe(password):
            error = 'Password is not safety.'
        elif not email:
            error = 'Email is required.'
        elif email and registered_email(email):
            error = 'Email has been registered.'
        elif email and not check_email_safe(email):
            error = 'Email address is invalidate.'
        elif not code:
            error = 'Verification code is required'
        elif code and not Captcha.captcha_validate(code):
            error = 'Verification code is wrong'
        elif db.execute(
            'SELECT id FROM user WHERE username = ?', (username,)
        ).fetchone() is not None:
            error = 'user {} is already registered.'.format(username)

        ctime = int(time.time())
        if error is None:
            db.execute(
                'INSERT INTO user (username, email, password, ctime) '
                'VALUES (?, ?, ?, ?)',
                (username, email, generate_password_hash(password), ctime)
            )
            db.commit()

            send_register_email(get_http_domain(), username, email)

            return render_template(
                'auth/register_success.j2',
                email=email
            )
            # return redirect(url_for('auth.login'))

        flash(error)

    return render_template('auth/register.j2')
Пример #27
0
def set_default_baby():
    if request.method == 'POST':
        baby_id = request.form['baby']
        get_db().execute('update baby_info set is_default=1 where id=?',
                         (baby_id, ))
        get_db().commit()
        another_baby = get_db().execute('select * from baby_info where id<>?',
                                        (baby_id, )).fetchone()
        if another_baby:
            get_db().execute(
                'update baby_info set is_default=0 '
                ' where id<>? and user_id=?', (baby_id, g.user['id']))
            get_db().commit()
        return redirect(url_for('baby.home'))
Пример #28
0
def test_delete(app, client, auth):
    auth.login()
    response = client.post('/post/1/delete')
    assert response.headers['Location'] == 'http://localhost/post/'

    with app.app_context():
        db = get_db()
        post = db.execute('SELECT * FROM post WHERE id = 1').fetchone()
        assert post is None
Пример #29
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()
Пример #30
0
def update_healthy(healthy_id):
    healthy = get_db().execute('select * from manage_healthy where id=?',
                               (healthy_id, )).fetchone()
    if request.method == 'POST':
        record_date = request.form['record_date']
        my_weight = request.form['weight']
        my_height = request.form['height']
        remarks = request.form['remarks']
        error = None
        if error is None:
            db = get_db()
            db.execute(
                'update manage_healthy set record_date=?, weight=?, '
                'height=?, remarks=? where id=?',
                (record_date, my_weight, my_height, remarks, healthy_id))
            db.commit()
            return redirect(url_for('baby.home'))
    return render_template('baby/baby_healthy_update.html', healthy=healthy)