예제 #1
0
def get_visits():
    """获取访问量"""
    db_conn = ToMongo()
    col = db_conn.get_col('visits')
    # 获取29天的时间差
    date = (datetime.datetime.now() - datetime.timedelta(days=29))
    # 查询大于时间差的数据
    before_30_day = get_30_day_before_timestamp()
    data = list(col.find({'date': {'$gte': before_30_day}}))
    # https://blog.csdn.net/qq_42184799/article/details/86311804
    # collections.OrderedDict()字典按插入顺序排序
    day_list = collections.OrderedDict()
    # 获取时间列表['04-25', '04-26', '04-27', '04-28']
    for i in range(0, 30):
        day = date.strftime("%m-%d")
        day_list[day] = 0
        date = date + datetime.timedelta(days=1)

    for d in data:
        d_farmat = format_m_d(d['date'])
        if d_farmat in day_list:
            day_list[d_farmat] = len(d['users_id'])

    x = []
    y = []
    for k, v in day_list.items():
        x.append(k)
        y.append(v)
    db_conn.close_conn()
    return x, y
예제 #2
0
def choice_book_type(num=11, all=False):
    my_conn = ToMongo()
    type_list = list(my_conn.get_col('books').distinct('first_type'))
    my_conn.close_conn()
    if all:
        return type_list
    return sample(type_list, num)
예제 #3
0
def get_user_click():
    conn = ToMongo()
    data = conn.get_col('hits_data').find({})
    user_click = {}
    for book in data:
        user_click[book.get('_id')] = book.get('book_ids')

    return user_click
예제 #4
0
def get_keyword():
    """
    获取搜索关键词数据
    :return:
    """
    db_conn = ToMongo()
    kw = db_conn.get_col('keyword').find({}, {'_id': 0})
    key = []
    value = []
    for k, v in list(kw)[0].items():
        key.append(k)
        value.append(v)
    return key, value
예제 #5
0
def item_sim(sim_info, book_id, num):
    conn = ToMongo()

    fixed_itemid = book_id
    result = conn.get_col('books').find_one({'_id': ObjectId(book_id)})
    if not result:
        return
    data = []
    for zuhe in sim_info[fixed_itemid][:num]:
        itemid_sim = zuhe[0]
        # sim_score = zuhe[1]
        book = conn.get_col('books').find_one({'_id': ObjectId(itemid_sim)})
        data.append(book)
    return data
예제 #6
0
def get_sales_data():
    """获取销售量sales的数据"""
    my_conn = ToMongo()
    data = my_conn.get_col('books').find({
        'sales': {
            '$gt': 0
        }
    }).sort('sales', -1).limit(10)
    data_x = []
    data_y = []
    for i in data:
        data_x.append(i['title'])
        data_y.append(i['sales'])
    return data_x, data_y
예제 #7
0
def get_hits_data():
    """获取点击量hits的数据"""
    db_conn = ToMongo()
    data = db_conn.get_col('books').find({
        'hits': {
            '$gt': 0
        }
    }).sort('hits', -1).limit(10)
    data_x = []
    data_y = []
    for i in data:
        print(i)
        data_x.append(i['title'])
        data_y.append(i['hits'])
    return data_x, data_y
예제 #8
0
def get_item_info():
    conn = ToMongo()
    data = conn.get_col('books').find({}, {
        '_id': 1,
        'title': 1,
        'first_type': 1,
        'second_type': 1
    })
    item_info = {}
    for book in data:
        item_info[str(book.get('_id'))] = [
            book.get('title'),
            book.get('first_type') + ',' + book.get('second_type')
        ]

    return item_info
예제 #9
0
def handle_refund(order_no, status, msg):
    """退款"""
    conn = ToMongo()
    # 还原库存
    query = {'order_no': order_no}
    restore_stock(query, conn)
    # 更新订单状态
    result = conn.update('order', {
        'order_no': order_no,
        'orders_status': status
    }, {"$set": {
        'orders_status': 5
    }})
    if result.modified_count:
        pass
    else:
        msg.update({'error': '更新失败'})
    conn.close_conn()
예제 #10
0
def auth_admin_model(role, email, status):
    """
    更改管理员权限
    :param role: 管理员角色
    :param email:  管理员登录邮箱
    :param status:  提交前的状态
    :return:  更过后的状态或结果
    """
    if status == 'on' and role in ADMIN_ROLE:  # status为授权状态‘on’,其操作是撤销权限
        query = {'$pull': {'auth': role}}
        status = 'off'
    elif status == 'off' and role in ADMIN_ROLE:    # status为'off'无权限,接下来将授予权限
        query = {'$push': {'auth': role}}
        status = 'on'
    else:
        return False
    my_db = ToMongo()
    my_db.update('admin', {'email': email}, query)
    result = {'status': status}
    return result
예제 #11
0
def uptate_status_inc(order_no, status, msg):
    conn = ToMongo()
    new = {"$inc": {'orders_status': 1}}
    if status == 0:
        new = {
            "$inc": {
                'orders_status': 1
            },
            "$addToSet": {
                'logistics': {
                    'create_time': get_now(),
                    'info': '商品已经下单'
                }
            }
        }
    elif status == 1:
        new = {
            "$inc": {
                'orders_status': 1
            },
            "$addToSet": {
                'logistics': {
                    'create_time': get_now(),
                    'info': '包裹正在等待揽收'
                }
            }
        }
    result = conn.update('order', {
        'order_no': order_no,
        'orders_status': status
    },
                         new,
                         is_one=False)
    if result.modified_count:
        pass
    else:
        msg.update({'error': '更新失败'})
    conn.close_conn()
예제 #12
0
def get_order(order_no):
    """获取订单详情"""
    conn = ToMongo()
    order = conn.get_col('order').find_one({'order_no': order_no})
    books = order.get('books')
    new_books = []
    for book in books:
        book_info = conn.get_col('books').find_one(
            {'_id': ObjectId(book.get('book_id'))})
        book_num = book.get('book_num')
        new_books.append({'book': book_info, 'book_num': book_num})
    order['create_time'] = format_time_second(order.get('create_time'))
    order['books'] = new_books
    conn.close_conn()
    return order
예제 #13
0
def index_model():
    """主页内容"""
    mydb = ToMongo()
    # 轮播
    random_time = int(str(time.time())[-3:])
    books = get_reader_recommend(mydb, random_time)
    new_books = list(
        mydb.get_col('books').find({
            'is_off_shelf': 0
        }).sort("create_time", -1).sort("hits", -1).limit(12))
    book_top = list(
        mydb.get_col('books').find({
            'is_off_shelf': 0
        }).sort("pub_time", -1).limit(5))
    book_top2 = list(
        mydb.get_col('books').find({
            'is_off_shelf': 0
        }).sort("sales", -1).limit(5))
    mydb.close_conn()
    return books, new_books, book_top, book_top2
예제 #14
0
def get_scales_order_data():
    """获取后台数据可视化的销售量和订单数据"""
    STATUS = [1, 2, 3, 4]
    result = {}
    conn = ToMongo()

    # 今日订单
    day_order = conn.get_col('order').find({
        '$and': [{
            'create_time': {
                '$gte': get_dawn_timestamp()
            }
        }, {
            'create_time': {
                '$lte': get_now()
            }
        }, {
            'orders_status': {
                '$in': STATUS
            }
        }]
    }).count()

    # 累计订单
    total_order = conn.get_col('order').find({
        'orders_status': {
            '$in': STATUS
        }
    }).count()

    # 今日销售额
    pipeline = [
        {
            '$match': {
                'orders_status': {
                    '$in': STATUS
                },
                'create_time': {
                    '$gte': get_dawn_timestamp(),
                    '$lte': get_now()
                },
            }
        },
        {
            '$group': {
                '_id': "",
                'sum': {
                    '$sum': '$amount'
                }
            }
        },
    ]
    day_amount_resp = list(conn.get_col('order').aggregate(pipeline))
    day_amount = .0
    if day_amount_resp:
        day_amount = day_amount_resp[0]['sum']

    # 累计销售额
    pipe = [{
        '$match': {
            'orders_status': {
                '$in': STATUS
            }
        }
    }, {
        '$group': {
            '_id': "",
            'sum': {
                '$sum': '$amount'
            }
        }
    }]
    total_amount = .0
    total_amount_resp = list(conn.get_col('order').aggregate(pipe))
    if total_amount_resp:
        total_amount = total_amount_resp[0]['sum']

    result.update({
        'day_order': day_order,
        'total_order': total_order,
        'day_amount': round(day_amount, 2),
        'total_amount': round(total_amount, 2),
    })

    return result
예제 #15
0
def admin_search_model(page, page_size, word):
    my_db = ToMongo()
    query = [{'email': {'$regex': word}}]
    result = my_db.get_col('admin').find({'$or': query}).skip(page * page_size).limit(page_size)
    total = my_db.get_col('admin').find({'$or': query}).count()
    return {'data': {'user': list(result), 'total': total, 'role': ADMIN_ROLE}}
예제 #16
0
def get_admin_account(page, page_size):
    my_db = ToMongo()
    result = my_db.get_col('admin').find().skip(page * page_size).limit(page_size)
    total = my_db.get_col('admin').find().count()
    return {'data': {'user': list(result), 'total': total, 'role': ADMIN_ROLE}}
예제 #17
0
def get_price():
    """
    # https://cloud.tencent.com/developer/article/1406368
    # 字符串转为数值
    # https://www.jb51.net/article/98385.htm
    # aggregate查询同字段的区间值
    :return:
    """
    pipeline = [
        {
            '$group': {
                '_id': "",
                'max': {
                    '$max': '$price'
                },
                'min': {
                    '$min': '$price'
                }
            }
        },
    ]
    db_conn = ToMongo()
    max_min = list(db_conn.get_col('books').aggregate(pipeline))
    max = float(max_min[0]['max'])
    min = max_min[0]['min']
    list_n = get_n_avg(min, max)
    book_num = []
    sales_num = []
    for i in list_n:
        # print(i[0],i[1])
        if i[1] != max:
            qurey = [{
                '$match': {
                    'price': {
                        '$gte': i[0],
                        '$lt': i[1]
                    }
                }
            }, {
                '$sort': {
                    'price': -1
                }
            }]
            r = db_conn.get_col('books').aggregate(qurey)
        else:
            qurey = [{
                '$match': {
                    'price': {
                        '$gte': i[0],
                        '$lte': i[1]
                    }
                }
            }, {
                '$sort': {
                    'price': -1
                }
            }]
            r = db_conn.get_col('books').aggregate(qurey)
        r = list(r)
        book_num.append(len(r))

        sales = 0
        for i in r:
            try:
                if i['sales']:
                    sales = sales + i['sales']
            except:
                pass
        sales_num.append(sales)
    db_conn.close_conn()
    return book_num, sales_num, list_n
예제 #18
0
def orders_query_model(page, page_size, order_status):
    query = {}
    if order_status == 0:
        # 待付款订单
        query = {
            '$and': [{
                'orders_status': order_status
            }, {
                'is_effective': 1
            }, {
                'create_time': {
                    '$gte': get_before_day()
                }
            }]
        }
    elif order_status == 1:
        query = {
            '$and': [{
                'orders_status': order_status
            }, {
                'is_effective': 1
            }]
        }
    elif order_status == 2:
        query = {
            '$and': [{
                'orders_status': order_status
            }, {
                'is_effective': 1
            }]
        }
    elif order_status == 3:
        query = {
            '$and': [{
                'orders_status': order_status
            }, {
                'is_effective': 1
            }]
        }
    elif order_status == 4:
        query = {
            '$and': [{
                'orders_status': order_status
            }, {
                'is_effective': 1
            }]
        }
    elif order_status == 5:
        # 失效订单
        query = {"$or": [{'orders_status': order_status}]}
    elif order_status == 6:
        query = {
            '$and': [{
                'orders_status': order_status
            }, {
                'is_effective': 1
            }]
        }
    db_conn = ToMongo()
    order = db_conn.get_col('order').find(query).sort('create_time', -1).skip(
        (page - 1) * page_size).limit(page_size)
    total = db_conn.get_col('order').find(query).count()
    order_list = list(order)
    books = []
    for order in order_list:
        order['create_time'] = format_time_second(order.get('create_time'))
        for book in order.get('books'):
            id = book.get('book_id')
            book_num = book.get('book_num')
            book = db_conn.get_col('books').find_one({'_id': ObjectId(id)})
            books.append({'book': book, 'num': book_num})
    db_conn.close_conn()
    return order_list, total, books