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 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 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 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_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 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 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 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 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 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 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 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_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 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 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 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 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
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 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
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
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 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
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 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
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 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
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 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