Exemple #1
0
def get_history_model(user_id):
    """获取浏览记录"""
    result = []
    conn = ToMongo()
    ret = conn.get_col('history').find_one({'_id': str(user_id)})
    if not ret:
        return result
    book_ids = ret.get('book_ids')
    for id in book_ids[-HISTORY:]:
        book = conn.get_col('books').find_one({'_id': ObjectId(id)})
        result.append(book)
    conn.close_conn()
    return result
Exemple #2
0
def get_user_collections(user_id):
    conn = ToMongo()
    ret = conn.get_col('favorites').find_one({'_id': str(user_id)})
    result = []
    if ret:
        for info in ret.get('book_ids'):
            id = info.get('book_id')
            book = conn.get_col('books').find_one({'_id': ObjectId(id)})
            collection_time = info.get('create_time')
            book.update(
                {'collection_time': format_time_second(collection_time)})
            result.append(book)
        conn.close_conn()
    return result
Exemple #3
0
def get_evaluate(book_id, page=0, page_size=10):
    """获取评论信息"""
    mydb = ToMongo()
    evaluates = mydb.get_col('evaluate').find_one({'_id': ObjectId(book_id)})
    lit = []
    star_dict = {'praise': 0, 'negative': 0, 'mid': 0}
    try:
        eval_comment = evaluates.get('comment')
        if page:
            page = page - 1
            eval_comment = eval_comment[page * page_size:page * page_size +
                                        page_size]
        else:
            eval_comment = eval_comment[page * page_size:page * page_size +
                                        page_size]
    except AttributeError:
        return [], 0, star_dict
    for evaluate in eval_comment:
        dit = {}
        # dit['order_no'] = evaluate['order_no']
        dit['star'] = evaluate['star']
        dit['context'] = evaluate['context']
        user_avatar = get_user_avatar(evaluate['user_id'])
        if user_avatar:
            avatar_path = './static/images/avatar/' + user_avatar
        else:
            avatar_path = ''
        dit['avatar'] = avatar_path
        dit['user_name'] = evaluate['user_name']
        dit['img_path'] = evaluate['img_path']
        dit['create_time'] = format_time_second(evaluate['create_time'])
        lit.append(dit)
    evaluates_details = get_evaluates_details(mydb, book_id, star_dict)
    mydb.close_conn()
    return lit, len(evaluates.get('comment')), star_dict
Exemple #4
0
def get_like_books(word, book_id):
    """MongoDB搜索功能的模糊查询"""
    mydb = ToMongo()
    mycol = mydb.get_col('books')
    query = [
        {
            'title': {
                "$regex": word
            }
        },
        {
            'subheading': {
                "$regex": word
            }
        },
        {
            'author': {
                "$regex": word
            }
        },
    ]
    books = mycol.find_one({
        '$or': query,
        '$and': [{
            '_id': {
                '$ne': ObjectId(book_id)
            }
        }]
    })
    mydb.close_conn()
    return books
Exemple #5
0
def add_visits(user_id):
    """访问量加1函数"""
    db_conn = ToMongo()
    dawn_timestamp = get_dawn_timestamp()
    last_date = db_conn.get_col('visits').aggregate([{
        '$group': {
            '_id': '$_id',
            'day': {
                '$last': '$date'
            }
        }
    }])
    date_list = list(last_date)
    # 不为空
    if date_list:
        # 同一天加入
        if date_list[0]['day'] == get_dawn_timestamp():
            db_conn.update('visits', {'_id': date_list[0]['_id']},
                           {'$addToSet': {
                               'users_id': user_id
                           }})
        else:
            # 不是同一天,插入新的文档
            db_conn.insert('visits', {
                'date': dawn_timestamp,
                'users_id': [user_id]
            })
    else:
        # 为空也插入
        db_conn.insert('visits', {
            'date': dawn_timestamp,
            'users_id': [user_id]
        })
def admin_login_model(email, password):
    result = {}
    conn = ToMongo()
    admin = conn.get_col('admin').find_one({'email': email, 'is_effective': 1})
    if admin:
        # 用户名正确
        if admin['sign_count'] >= 5 and get_now() - admin['last_signIn_time'] < FROZEN_TIME:
            result['error'] = '请 {}秒 后再重试'.format(FROZEN_TIME - (get_now() - admin['last_signIn_time']))
            conn.close_conn()
            return result
        else:
            if check_password_hash(admin['password'], password):  # 成功
                conn.update('admin',
                            {'email': admin.get('email')},
                            {'$set': {'sign_count': 0, 'last_signIn_time': get_now()}})
                result['admin'] = admin
                conn.close_conn()
                return result
            else:  # 失败
                conn.update('admin',
                            {'email': admin.get('email')},
                            {'$inc': {'sign_count': 1}})
                conn.update('admin',
                            {'email': admin.get('email')},
                            {'$set': {'last_signIn_time': get_now()}})
                error = '邮箱地址或密码错误!剩余 {} 次'.format(5 - (admin['sign_count'] + 1))
                result['error'] = error
                conn.close_conn()
                return result
    else:  # 用户名错误
        result['error'] = '邮箱地址或密码错误!'
        conn.close_conn()
        return result
Exemple #7
0
def get_book_id(order_no):
    """获取订单的图书id"""
    mydb = ToMongo()
    books = mydb.get_col('order').find_one({'order_no': order_no})
    book_ids = []
    for book in books.get('books'):
        book_ids.append(book.get('book_id'))
    mydb.close_conn()
    return book_ids
Exemple #8
0
def get_book_text(id):
    conn = ToMongo()
    book = conn.get_col('books').find_one({'_id': ObjectId(id)}, NOT_LIST)
    conn.close_conn()
    text = ''
    for k, b in book.items():
        if isinstance(b, str):
            text = text + '。' + b
    return text
Exemple #9
0
def get_book(id, query_off_shelf=True):
    """获取图书信息"""
    mydb = ToMongo()
    mycol = mydb.get_col('books')
    if query_off_shelf:
        book = mycol.find_one({'_id': ObjectId(id), 'is_off_shelf': 0})
    else:
        book = mycol.find_one({'_id': ObjectId(id)})
    # 添加点击量
    mydb.update('books', {'_id': ObjectId(id)}, {'$inc': {'hits': 1}})
    mydb.close_conn()
    return book
Exemple #10
0
def get_order_info(user_id, order_no):
    """获取订单信息"""
    mydb = ToMongo()
    myorder = mydb.get_col('order').find_one({
        'order_no': order_no,
        'user_id': user_id
    })
    data = {
        'order_no': myorder.get('order_no'),
        'amount': myorder.get('amount'),
        'create_time': format_time_second(myorder.get('create_time'))
    }
    mydb.close_conn()
    return data
Exemple #11
0
def is_collection_model(user_id, book_id):
    """获取用户是否收藏该商品"""
    result = False
    conn = ToMongo()
    ret = conn.get_col('favorites').find_one({
        '_id': str(user_id),
        'book_ids.book_id': {
            '$in': [book_id]
        }
    })
    conn.close_conn()
    if ret:
        result = True
    return result
Exemple #12
0
def search_book_model(word, page, page_size):
    """搜索图书"""
    db_conn = ToMongo()
    # 如果输入不为空
    if word:
        first_type = db_conn.get_col('books').find().distinct('first_type')
        if word in first_type:
            books, count = get_like_books(word,
                                          page,
                                          page_size,
                                          book_type=True)
        else:
            # 添加关键字数据到数据库,用与绘制词云图
            db_conn.update('keyword', {'_id': 'keyword'}, {'$inc': {word: 1}})
            books, count = get_like_books(word, page, page_size)
    # 如果输入为空,则显示点击量前十的
    else:
        books = db_conn.get_col('books').find({
            'is_off_shelf': 0
        }).sort('hits', -1).skip((page - 1) * page_size).limit(page_size)
        count = db_conn.get_col('books').find({'is_off_shelf': 0}).count()
    db_conn.close_conn()
    return books, count
Exemple #13
0
def pay_model(order_no):
    """订单支付"""
    mydb = ToMongo()
    images = []
    weixin_image = base64.b64encode(mydb.get_img('weixin.gif')).decode('utf-8')
    zhifubao_image = base64.b64encode(
        mydb.get_img('zhifubao.gif')).decode('utf-8')
    images.append({'data': weixin_image, 'name': '微信支付'})
    images.append({'data': zhifubao_image, 'name': '支付宝支付'})
    my_orders = mydb.get_col('order').find({
        "is_effective": 1,
        'order_no': order_no
    })
    my_orders = list(my_orders)
    mydb.close_conn()
    return my_orders, images
Exemple #14
0
def get_recommend_cart_book_model(user_id):
    try:
        book = getRecommendations(transformPrefs(get_data()), user_id)
        # print(book + 'aassa')
    except Exception as e:
        pass
        # print(str(e) + '22222222222222')
    skip = str(time.time()).split('.')[-1][:4]
    conn = ToMongo()
    result = conn.get_col('books').find().skip(int(skip)).limit(2)
    book = []
    for b in result:
        id = str(b.get('_id'))
        img = b.get('img_url')
        title = b.get('title')
        author = b.get('author')
        book.append({'img': img, 'id': id, 'title': title, 'author': author})
    return book
Exemple #15
0
def update_status_to_5():
    """将过期订单,状态更新为失效"""
    mydb = ToMongo()
    query = {
        'orders_status': 0,
        'create_time': {
            '$lt': get_now() - ORDER_EFFECTIVE_TIME
        },
    }
    # 恢复库存
    orders = mydb.get_col('order').find(query)
    for order in orders:
        order_no = order.get('order_no')
        query = {'order_no': order_no}
        restore_stock(query, mydb)
    # 更新订单状态
    new = {'$set': {'orders_status': 5}}
    result = mydb.update('order', query, new, is_one=False)
    mydb.close_conn()
    return result.modified_count
Exemple #16
0
def get_order_details_model(order_no, user_id):
    """获取订单详情"""
    update_status_to_5()  # 更新订单状态
    db_conn = ToMongo()
    cur = db_conn.get_col('order').find_one({
        'user_id': user_id,
        'order_no': order_no
    })
    create_time = cur['create_time']
    effective_time = create_time + ORDER_EFFECTIVE_TIME
    is_processed = cur['is_processed']
    amount = cur['amount']
    order_id = cur['_id']
    order_no = cur['order_no']
    is_effective = cur['is_effective']
    address = cur['address']
    status = cur['orders_status']
    logistics = format_logistics(cur['logistics'])
    book_list = []
    for book in cur['books']:
        book_dict = {}
        book_dict['num'] = book['book_num']
        book_id = book['book_id']
        book_dict['book'] = get_book_for_id(book_id)
        book_list.append(book_dict)

    order_dict = {}
    order_dict['books'] = book_list
    order_dict['_id'] = order_id
    order_dict['create_time'] = format_time_second(create_time)
    order_dict['effective_time'] = format_time_second(effective_time)
    order_dict['is_processed'] = is_processed
    order_dict['amount'] = amount
    order_dict['order_no'] = order_no
    order_dict['is_effective'] = is_effective
    order_dict['address'] = address
    order_dict['status'] = status
    order_dict['logistics'] = logistics
    db_conn.close_conn()
    return order_dict
Exemple #17
0
def get_data():
    try:
        my_conn = ToMongo()
        evaluates = my_conn.get_col('evaluate').find()
        results = {}
        for evaluate in evaluates:
            book_dist = {}
            evaluate_id = str(evaluate.get('_id'))
            # print(evaluate.get('_id'))
            comment_dist = {}
            for comment in evaluate.get('comment'):
                # print(comment)
                user_id = str(comment.get('user_id'))
                comment_dist[user_id] = comment.get('star')
                # print(comment.get('user_id'), comment.get('star'))
            results[evaluate_id] = comment_dist
            # results.append(book_dist)
        # print(results)
        return results
    except Exception as e:
        print(e)
        return
Exemple #18
0
def edit_addr_model(user_id, request):
    rel = False
    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.update('address', {'_id': ObjectId(_id)}, {
        "$set": {
            'name': name,
            'tel': tel,
            'province': address_list[0],
            'city': address_list[1],
            'district': address_list[2],
            'details': details
        }
    })
    if result.modified_count:
        rel = True
        result = db_conn.get_col('address').find({'user_id': user_id})
    db_conn.close_conn()
    return rel, result
Exemple #19
0
def get_orders(user_id, status):
    """获取用户订单信息"""
    query = format_query(user_id, status)
    db_conn = ToMongo()
    result = db_conn.get_col('order').find(query).sort('order_no', -1)
    orders = []
    result = list(result)
    for order in result:
        status = order['orders_status']
        amount = order['amount']
        order_no = order['order_no']
        create_time = order['create_time']
        effective_time = order['create_time'] + ORDER_EFFECTIVE_TIME
        books = order['books']
        book_info = []
        # 15天自动确认收货
        if status == 2 and create_time + AUTO_RECEIVE < get_now():
            rel = update_status_user_id(order_no, user_id)
            if rel.modified_count:
                status = 3
        for book in books:
            book_num = book['book_num']
            # 图书下架后get_book查询不到信息,会抛出错误
            book_info.append({
                'book_num': book_num,
                'books': get_book_for_id(book['book_id'])
            })
        orders.append({
            'status': status,
            'amount': amount,
            'order_no': order_no,
            'create_time': format_time_second(create_time),
            'book_info': book_info,
            'effective_time': format_time_second(effective_time),
        })
    db_conn.close_conn()
    return orders
Exemple #20
0
def evaluate_model(user_id, user_name, request):
    """用户评论模型"""
    rlt = {}
    order_no = request.form.get('order_no')
    if int(get_order_status(order_no)) == 4:
        rlt['error'] = '已评论!'
        return rlt
    star = int(request.form.get('star'))
    context = request.form.get('context')
    anonymous = request.form.get('anonymous')
    img = request.files.get('img')
    if not star:
        rlt['error'] = '评分不能为空'
        return rlt
    if img:
        img_path = save_img(order_no, img)
    else:
        img_path = ''
    create_time = get_now()
    book_ids = get_book_id(order_no)
    if anonymous:
        user_name = user_name[0] + '**'
    elif user_name is None:
        user_name = '***'
    else:
        user_name = user_name[0] + '*' + user_name[-1]
    id_list = []
    mydb = ToMongo()
    for book_id in book_ids:
        evaluates = mydb.get_col('evaluate').find_one(
            {'_id': ObjectId(book_id)})
        if evaluates:
            value = {
                '$addToSet': {
                    'comment': {
                        'order_no': order_no,
                        'star': star,
                        'context': context,
                        'user_id': user_id,
                        'user_name': user_name,
                        'img_path': img_path,
                        'create_time': create_time
                    }
                }
            }
            result = mydb.update('evaluate', {'_id': ObjectId(book_id)}, value)
            if result and result.modified_count:
                id_list.append(result.modified_count)
        else:
            # 无评论时,直接插入
            rel = mydb.insert(
                'evaluate', {
                    '_id':
                    ObjectId(book_id),
                    'comment': [{
                        'order_no': order_no,
                        'star': star,
                        'context': context,
                        'user_id': user_id,
                        'user_name': user_name,
                        'img_path': img_path,
                        'create_time': create_time
                    }]
                })
            if rel:
                id_list.append(rel.inserted_id)
    if len(id_list) != len(book_ids):
        # print(id_list)
        rlt['error'] = '评论失败,请重试!'
    mydb.close_conn()
    return rlt
Exemple #21
0
def get_order_status(order_no):
    mydb = ToMongo()
    order = mydb.get_col('order').find_one({'order_no': order_no})
    order_status = order.get('orders_status')
    return order_status
Exemple #22
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)
Exemple #23
0
def get_addr_list_model(user_id):
    db_conn = ToMongo()
    rel = db_conn.get_col('address').find({'user_id': user_id})
    rel_list = list(rel)
    db_conn.close_conn()
    return rel_list
Exemple #24
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
Exemple #25
0
def get_addr_info(id):
    db_conn = ToMongo()
    rel = db_conn.get_col('address').find({'_id': ObjectId(id)})
    rel_list = list(rel)
    db_conn.close_conn()
    return rel_list