Esempio n. 1
0
def edit_userinfo_model(user_id, request):
    rel = True
    name = request.form.get('name')
    gender = request.form.get('gender')
    age = request.form.get('age')
    birthday = request.form.get('birthday')
    email = request.form.get('email')
    tel = request.form.get('tel')
    identity_select = request.form.get('identity_')
    hobbies = request.form.get('hobbies')
    introduce = request.form.get('introduce')
    conn = ToConn()
    to_exec = conn.to_execute()
    cur = to_exec.cursor()
    sql = 'update users set name=%s,gender=%s,age=%s,birthday=%s,email=%s,tel=%s,identity=%s,hobbies=%s,' \
          'introduce=%s where id=%s'
    try:
        result = cur.execute(sql,
                             (name, gender, age, birthday, email, tel,
                              identity_select, hobbies, introduce, user_id))
    except pymysql.err.IntegrityError:
        result = False
    if result:
        to_exec.commit()
        # to_exec.close()
    else:
        rel = False
        to_exec.rollback()
        # to_exec.close()
    conn.to_close()
    return rel
Esempio n. 2
0
def upload_avatar_model(user_id, img):
    rel = True
    s_img = secure_filename(img.filename)
    img_suffix = s_img.split('.')[-1]
    # 随机文件名+后缀
    if check_img_suffix(img_suffix):
        filepath = './static/images/avatar/' + str(user_id) + '.' + str(
            img_suffix)
        filename = filepath.split('/')[-1]
        img.save(filepath)
        conn = ToConn()
        to_exec = conn.to_execute()
        cur = to_exec.cursor()
        result = cur.execute('update users set avatar=%s where id=%s',
                             (filename, user_id))
        if result:
            to_exec.commit()
            to_exec.close()
        else:
            rel = False
            to_exec.rollback()
            to_exec.close()
        conn.to_close()
        return rel
    else:
        return False
Esempio n. 3
0
def get_user_addr_info(user_id, request):
    name = request.form.get('name')
    tel = request.form.get('tel')
    address_list = request.form.get('address').strip().split(' ')
    details = request.form.get('details')
    _id = request.form.get('_id')
    db_conn = ToMongo()
    result = db_conn.insert(
        'address', {
            'name': name,
            'tel': tel,
            'province': address_list[0],
            'city': address_list[1],
            'district': address_list[2],
            'details': details,
            'user_id': user_id
        })
    if result.inserted_id:
        conn = ToConn()
        to_exec = conn.to_execute()
        cur = to_exec.cursor()
        r = cur.execute('update users set address_default=%s where id=%s',
                        (str(result.inserted_id), user_id))
        if r:
            to_exec.commit()
            to_exec.close()
        else:
            to_exec.rollback()
            to_exec.close()
        conn.to_close()
    db_conn.close_conn()
    return r
Esempio n. 4
0
def get_user_text(id):
    user = ToConn().get_db(
        'select hobbies,introduce,identity,age from users where id=%s',
        (id, )).fetchone()
    text = ''
    for k, u in user.items():
        text = text + '。' + str(u)

    return text
Esempio n. 5
0
def get_user_avatar(user_id):
    """获取评论用户的头像"""
    mydb = ToConn()
    user_info = mydb.get_db('select avatar from users where id=%s',
                            (user_id, )).fetchone()
    try:
        avatar = user_info.get('avatar', '')
    except AttributeError:
        avatar = ''
    return avatar
Esempio n. 6
0
def from_cart_buy(books, user_id):
    """购物车"""
    book_list = []
    for book_id in books:
        db = ToConn()
        sql = 'select book_num from cart where user_id=%s and book_id=%s and is_effe=1'
        book_num = db.get_db(sql, (user_id, book_id)).fetchone()
        mydb = get_book(book_id)
        mydb['_id'] = book_id
        mydb['book_num'] = book_num['book_num']
        mydb['sum_price'] = round(
            float(mydb['price']) * float(book_num['book_num']), 2)
        book_list.append(mydb)
    return book_list
Esempio n. 7
0
def user_login_model(username, password):
    db = ToConn()
    error = None
    user = db.get_db('select * from users where tel = %s and is_delete = 0',
                     (username, )).fetchone()
    if user is None:
        error = 'Incorrect username or password'
    elif username != str(user['tel']):
        error = 'Incorrect username or password'
    elif not check_password_hash(user['password'], password):
        error = 'Incorrect username or password'
    elif user['is_freezing']:
        error = 'The User Freezing, Please Contact Administrator'
    return user, error
Esempio n. 8
0
def set_default_addr_model(user_id, addr_id):
    rel = True
    conn = ToConn()
    to_exec = conn.to_execute()
    cur = to_exec.cursor()
    result = cur.execute('update users set address_default=%s where id=%s',
                         (addr_id, user_id))
    if result:
        to_exec.commit()
        to_exec.close()
    else:
        rel = False
        to_exec.rollback()
        to_exec.close()
    conn.to_close()
    return rel
Esempio n. 9
0
def get_user_cart(user_id):
    """获取购物物品信息"""
    db = ToConn()
    sql = 'select book_id, book_num from cart where user_id=%s and is_effe=1'
    result = db.get_db(sql, (user_id, )).fetchall()
    books = []
    for book_id in result:
        book_num = book_id.get('book_num')
        b1 = get_book(book_id.get('book_id'), False)
        try:
            # 下架图书{'hits': 14, '_id': ObjectId('5e927b251771c616ff7455ad')}抛出异常
            b1['book_num'] = book_num
            b1['sum_price'] = round((int(book_num) * b1.get('price')), 2)
        except TypeError:
            pass
        books.append(b1)
    return books
Esempio n. 10
0
def change_pwd_model(user_id, new_pw):
    rel = True
    conn = ToConn()
    to_exec = conn.to_execute()
    cur = to_exec.cursor()
    sql = 'update users set password=%s where id=%s'
    result = cur.execute(sql, (generate_password_hash(new_pw), user_id))
    if result:
        # 修改成功,提交
        to_exec.commit()
        to_exec.close()
    else:
        # 失败,回滚
        rel = False
        to_exec.rollback()
        to_exec.close()
    conn.to_close()
    return rel
Esempio n. 11
0
def delete_addr_model(user_id, _id):
    rel = True
    if _id == get_user(user_id)['address_default']:
        # 如果是默认地址,删除默认地址
        conn = ToConn()
        to_exec = conn.to_execute()
        cur = to_exec.cursor()
        result = cur.execute(
            'update users set address_default=null where id=%s', (user_id, ))
        if result:
            to_exec.commit()
            to_exec.close()
        else:
            to_exec.rollback()
            to_exec.close()
            return False
    # 如果不是默认地址,直接删除默认地址
    db = ToMongo()
    count = db.delete('address', {'_id': ObjectId(_id)}).deleted_count
    if not count:
        rel = False
    db.close_conn()
    return rel
Esempio n. 12
0
def delete_addr(user_id, _id):
    """删除收货地址"""
    conn = ToConn().to_execute()
    cur = conn.cursor()
    db_conn = ToMongo()
    cur.execute(
        'update users set address_default=null where id=%s and address_default = %s',
        (user_id, _id))
    result = db_conn.delete(col='address', doc={
        '_id': ObjectId(_id)
    }).raw_result
    if result['ok'] == 1:
        conn.commit()
    else:
        conn.rollback()
    db_conn.close_conn()
Esempio n. 13
0
def user_register_model(username, password, password_again):
    db = ToConn()
    error = None
    if not username:
        error = 'Username or Password is Required'
    elif not password:
        error = 'Username or Password is Required'
    elif password != password_again:
        error = 'Username or Password is Required'
    elif db.get_db('select id from users where tel = %s',
                   (username, )).fetchone() is not None:
        error = 'User {} is Already Registered'.format(username)
    if error is None:
        db = ToConn()
        comm = db.to_db('insert into users(tel,password) values (%s,%s)',
                        (username, generate_password_hash(password)))
        comm.commit()
        comm.close()
    return error
Esempio n. 14
0
def edit_cart_num(user_id, book_id, count=0, method='delete'):
    """编辑购物车数量"""
    db = ToConn()
    query = (count, user_id, book_id)
    sql = 'delete from cart  where book_num=%s and user_id=%s and book_id=%s and is_effe=1'
    if method == 'adds':
        sql = 'update cart set book_num=%s where user_id=%s and book_id=%s and is_effe=1'
        if count + 1 >= get_book(book_id).get('stock'):
            count = count
        else:
            count = count + 1
    elif method == 'reduces':
        sql = 'update  cart set book_num=%s where user_id=%s and book_id=%s and is_effe=1'
        count = count - 1
    elif method == 'deletes':
        sql = 'delete from cart where user_id=%s and is_effe=1 and book_id in %s'
        query = (user_id, book_id)
        count = 1
    db.to_db(sql, query).commit()
    db.to_close()
    logging.info('sql:[%s]', sql)
    return count
Esempio n. 15
0
def get_user(id):
    """获取用户信息"""
    db = ToConn()
    user = db.get_db('select * from users where id=%s', (id, )).fetchone()
    return user
Esempio n. 16
0
def update_addr(user_id, request):
    """更换收货地址"""
    name = request.form.get('name')
    tel = request.form.get('tel')
    address_list = request.form.get('address').strip().split(' ')
    details = request.form.get('details')
    mydb = ToMongo()
    value = {
        'user_id': user_id,
        'name': name,
        'tel': tel,
        'province': address_list[0],
        'city': address_list[1],
        'district': address_list[2],
        'details': details,
    }
    conn = ToConn().to_execute()
    cur = conn.cursor()
    address_default = mydb.insert('address', value).inserted_id
    cur.execute('update users set address_default=%s where id=%s',
                (str(address_default), user_id))
    if address_default:
        conn.commit()
        conn.close()
    else:
        conn.rollback()
        conn.close()
    mydb.close_conn()
Esempio n. 17
0
def to_buy_model(user_id, books_id, is_list=True):
    """结算"""
    db_conn = ToMongo()
    if is_list:
        book_id_list = list(books_id.split(','))
        book_list = []
        sum_price = 0.0
        freight = 0.0
        package = 1
        discount = 1.01
        sum_book = 0
        addr = {}
        try:
            user = get_user(user_id)
            logging.info('userinfo:%s', user)
            if user['address_default'] is None or user['address_default'] is '':
                addr = {}
            else:
                address = db_conn.get_col('address').find(
                    {'_id': ObjectId(user['address_default'])})
                for a in address:
                    addr['name'] = a.get('name')
                    addr['tel'] = a.get('tel')
                    addr['province'] = a.get('province')
                    addr['city'] = a.get('city')
                    addr['district'] = a.get('district', '')
                    addr['details'] = a.get('details', '')
                    addr['_id'] = user['address_default']
            for book_id in book_id_list:
                db = ToConn()
                sql = 'select book_num from cart where user_id=%s and book_id=%s and is_effe=1'
                book_num = db.get_db(sql, (user_id, book_id)).fetchone()
                book = get_book(book_id)
                book['_id'] = book_id
                book['book_num'] = int(book_num['book_num'])
                book['sum_price'] = round(
                    float(book['price']) * float(book_num['book_num']), 2)
                if int(book_num.get('book_num')) > book.get('stock'):
                    return {'error': '{} 没有这么多库存啦~'.format(book.get('title'))}
                book_list.append(book)
                sum_price = sum_price + round(
                    float(book['price']) * float(book_num['book_num']), 2)
                sum_book = sum_book + int(book_num['book_num'])
            books_price = {
                'sum_price': sum_price,
                'freight': freight,
                'package': package,
                'sum': round(sum_price + freight - discount, 2),
                'discount': discount
            }
            pay = {
                'amount_pay': round(sum_price + freight - discount, 2),
                'sum_book': sum_book,
                'freight': freight
            }
            shipping_time = datetime.now() + timedelta(days=3)
            db_conn.close_conn()
            return {
                'book_list': book_list,
                'books_price': books_price,
                'pay': pay,
                'shipping_time': shipping_time,
                'addr': addr
            }
        except Exception as e:
            db_conn.close_conn()
            logging.exception(e)
    else:
        try:
            book_num = 1
            book_list = []
            sum_price = 0.0
            freight = 0.0
            package = 1
            discount = 1.01
            sum_book = 0
            book = get_book(books_id)
            book['_id'] = books_id
            book['book_num'] = book_num
            book['sum_price'] = round(float(book['price']) * book_num, 2)
            if book_num > book.get('stock'):
                return {'error': '{} 没有这么多库存啦~'.format(book.get('title'))}
            book_list.append(book)
            sum_price = sum_price + round(float(book['price']) * book_num, 2)
            sum_book = sum_book + book_num
            user = get_user(user_id)
            addr = {}
            if user['address_default'] is None or user['address_default'] is '':
                addr = {}
            else:
                address = db_conn.get_col('address').find(
                    {'_id': ObjectId(user['address_default'])})
                for a in address:
                    addr['name'] = a.get('name')
                    addr['tel'] = a.get('tel')
                    addr['province'] = a.get('province')
                    addr['city'] = a.get('city')
                    addr['district'] = a.get('district', '')
                    addr['details'] = a.get('details', '')
                    addr['_id'] = user['address_default']
            books_price = {
                'sum_price': sum_price,
                'freight': freight,
                'package': package,
                'sum': round(sum_price + freight - discount, 2),
                'discount': discount
            }
            pay = {
                'amount_pay': round(sum_price + freight - discount, 2),
                'sum_book': sum_book,
                'freight': freight
            }
            shipping_time = datetime.now() + timedelta(days=3)
            db_conn.close_conn()
            return {
                'book_list': book_list,
                'books_price': books_price,
                'pay': pay,
                'shipping_time': shipping_time,
                'addr': addr
            }
        except Exception as e:
            db_conn.close_conn()
            print('========get_buy=========:', e)
Esempio n. 18
0
def to_pay_model(user_id, book_ids, addr_id, is_buy_now):
    """去支付"""
    DISCOUNT = 1.01
    create_time = int(time.time())
    order_no = create_orders()
    books = []
    amount = .0
    # 获取收货地址,写入订单号详情
    db_conn = ToMongo()
    address = db_conn.get_col('address').find_one({
        'user_id': user_id,
        '_id': ObjectId(addr_id)
    })
    for book_id in book_ids:
        book = get_book(book_id, False)
        if not is_buy_now:
            db = ToConn()
            sql = 'select book_num from cart where user_id=%s and book_id=%s and is_effe=1'
            book_num = db.get_db(sql, (user_id, book_id)).fetchone()
            if book_num:
                books.append({
                    'book_num': int(book_num['book_num']),
                    'book_id': book_id
                })
                amount += (float(book.get('price')) *
                           int(book_num['book_num']))
            else:
                books.append({'book_num': 1, 'book_id': book_id})
                amount += (float(book.get('price')) * 1)
        else:
            books.append({'book_num': 1, 'book_id': book_id})
            amount += (float(book.get('price')) * 1)

    v = {
        "amount": amount - DISCOUNT,
        "books": books,
        "order_no": order_no,
        "is_processed": 0,
        "user_id": user_id,
        "create_time": create_time,
        "is_effective": 1,
        "address": address,
        "orders_status": 0,
        "pay_status": 0,
        "exp_status": 0,
        "logistics": [],  # 物流信息
    }
    result = db_conn.insert('order', v)
    if result and not is_buy_now:
        db = ToConn()
        conn = db.to_execute()
        cursor = conn.cursor()
        try:
            for book_id in book_ids:
                sql = 'delete from cart where user_id=%s and book_id=%s'
                cursor.execute(sql, (user_id, book_id))
        except Exception as e:
            print('========to_pay=========事务处理失败:', e)
            conn.rollback()  # 事务回滚
        else:
            conn.commit()  # 事务提交

            for book in books:
                # 销量加
                db_conn.update('books', {'_id': ObjectId(book.get('book_id'))},
                               {'$inc': {
                                   'sales': book.get('book_num')
                               }})
                # 库存减
                db_conn.update('books', {'_id': ObjectId(book.get('book_id'))},
                               {'$inc': {
                                   'stock': -book.get('book_num')
                               }})
        db.to_close()
    elif is_buy_now:
        for book in books:
            # 销量加
            db_conn.update('books', {'_id': ObjectId(book.get('book_id'))},
                           {'$inc': {
                               'sales': book.get('book_num')
                           }})
            # 库存减
            db_conn.update('books', {'_id': ObjectId(book.get('book_id'))},
                           {'$inc': {
                               'stock': -book.get('book_num')
                           }})

    db_conn.close_conn()
    return order_no
Esempio n. 19
0
def add_card_model(user_id, book_id, num):
    """添加到购物车"""
    try:
        stock = int(get_book(book_id).get('stock'))  # 获取库存
        db = ToConn()
        # 查处用户的购物车是否有添加的物品
        sql = 'select * from cart where book_id=%s and user_id=%s and is_effe=1'
        get_db = db.get_db(sql, (book_id, user_id)).fetchone()
        # 执行完查询后链接自动关闭了,所以要重新创建一个新的链接
        db2 = ToConn()
        if get_db:
            if int(get_db.get('book_num')) + num > stock:
                return {'error': '没有这么多库存啦~'}
            # 购物车已有则将数量加入数据库
            sql = 'update cart set book_num=book_num+%s where book_id=%s and user_id=%s'
            to_db = db2.to_db(sql, (int(num), book_id, user_id))
            to_db.commit()
            db2.to_close()
        else:
            if num > stock:
                return {'error': '没有这么多库存啦~'}
            # 否则添加新的物品
            sql = 'insert into cart(user_id, book_id, book_num) values (%s,%s,%s)'
            to_db = db2.to_db(sql, (user_id, book_id, num))
            to_db.commit()
            db2.to_close()
            logging.info('%s:添加[%s:%s]到购物车', user_id, book_id, num)
    except Exception as e:
        print('===============', e)
        # 发生错误回滚
        to_db.rollback()
        db2.to_close()