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
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
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()
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
def add_history(user_id, book_id): """添加浏览历史""" conn = ToMongo() query = {'_id': str(user_id), 'book_ids': {'$nin': [book_id]}} ret = conn.update('history', query, {'$push': {'book_ids': book_id}}) conn.close_conn() if ret: return ret.modified_count
def refund_model(order_no, user_id): """用户申请退款""" mydb = ToMongo() query = {'order_no': order_no, 'user_id': user_id} new = {'$set': {'orders_status': 6}} rel = mydb.update('order', query, new) mydb.close_conn() if rel and rel.modified_count: return rel.modified_count
def update_status(order_no): """更新订单状态为交易完成""" mydb = ToMongo() result = mydb.update('order', {'order_no': order_no}, {'$set': { 'orders_status': 4 }}) mydb.close_conn() return result.modified_count
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
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
def clear_history_model(user_id): """清除浏览记录""" conn = ToMongo() result = False query = {'_id': str(user_id)} ret = conn.update('history', query, {'$set': {'book_ids': []}}) if ret.modified_count: result = True conn.close_conn() return result
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 update_status_user_id(order_no, user_id): """更新订单状态为待评论""" mydb = ToMongo() result = mydb.update('order', { 'order_no': order_no, 'user_id': user_id }, {'$set': { 'orders_status': 3 }}) mydb.close_conn() return result.modified_count
def add_hits_cf(user_id, book_id): conn = ToMongo() result = conn.update('hits_data', { '_id': str(user_id), 'book_ids': { '$nin': [book_id] } }, {'$push': { 'book_ids': book_id }}) conn.close_conn()
def cancel_model(order_no, user_id): """用户取消订单""" mydb = ToMongo() # 还原物品库存 query = {'order_no': order_no, 'user_id': user_id} restore_stock(query, mydb) # 更改订单状态 query = {'order_no': order_no, 'user_id': user_id} new = {'$set': {'orders_status': 5}} rel = mydb.update('order', query, new) mydb.close_conn() return rel.modified_count
def admin_register(email, password, auth_list): user = { 'email': email, 'password': generate_password_hash(password), 'is_effective': 1, 'last_signIn_time': 0, 'create_time': get_now(), 'sign_count': 0, 'auth': auth_list } my_db = ToMongo() result = my_db.insert('admin', user) return result.inserted_id
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
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
def user_delete_order(user_id, order_no): """用户删除单个订单""" rel = False db_conn = ToMongo() result = db_conn.update('order', { 'order_no': order_no, 'user_id': user_id }, {'$set': { 'is_effective': 0 }}) if result.modified_count: # 删除成功 rel = True db_conn.close_conn() return rel
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()
def to_delete_collection(user_id, ids): conn = ToMongo() result = False query = {'_id': str(user_id)} ret = conn.update('favorites', query, {'$pull': { 'book_ids': { 'book_id': { '$in': ids } } }}) if ret.modified_count: result = True conn.close_conn() return result
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
def to_collection_model(user_id, book_id, is_clear=False): """添加、取消收藏""" conn = ToMongo() if is_clear: result = False query = {'_id': str(user_id), 'book_ids.book_id': {'$in': [book_id]}} ret = conn.update('favorites', query, {'$pull': { 'book_ids': { 'book_id': book_id } }}) if ret.modified_count: result = True else: result = False query = {'_id': str(user_id), 'book_ids.book_id': {'$nin': [book_id]}} ret = conn.update('favorites', query, { '$push': { 'book_ids': { 'book_id': book_id, 'create_time': get_now() } } }) if ret.modified_count: result = True conn.close_conn() return result
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
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
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
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
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
def evaluate_model(user_id, user_name, request, book_ids): """用户评论模型""" rlt = {} order_no = request.get('order_no') star = int(request.get('star')) context = request.get('context') anonymous = request.get('anonymous') if not star: rlt['error'] = '评分不能为空' return rlt img_path = '' create_time = get_now() if anonymous: user_name = user_name[0] + '**' else: user_name = user_name[0] + '*' + user_name[-1] id_list = [] mydb = ToMongo() for book_id in book_ids: 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.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 } ] }) id_list.append(rel.inserted_id) # print(id_list) if len(id_list) != len(book_ids): # print(id_list) rlt['error'] = '评论失败,请重试!' mydb.close_conn() return rlt
def get_address(self): url = 'https://www.xzqy.net/451102000000.htm' province = self.get_province(url) address = {} for key, value in province.items(): province_key = key city = self.get_city(value) for key, value in city.items(): city_key = key district = self.get_city(value) for key, value in district.items(): district_key = key address[province_key] = city_key address[city_key] = district_key address[district_key] = self.get_village(value) ToMongo().insert('address', address) return address
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