Ejemplo n.º 1
0
class GreetingService:
    name = "greeting_service"
    log = LoggingDependency()

    @rpc
    def hello(self, name):
        return "Hello, {}!".format(name)

    @rpc
    def computation_bound(self):
        start = time.time()
        while True:
            if time.time() - start > 300:
                break

    @rpc
    def computation_bound_sleep(self):
        start = time.time()
        while True:
            if int(time.time() - start) % 5 == 0:
                time.sleep(0.1)

            if time.time() - start > 300:
                break

    @rpc
    def computation_bound_tpool(self):
        return tpool.execute(some_fun_you_can_not_control)

    @rpc
    def raise_exception(self):
        raise Exception()
Ejemplo n.º 2
0
class WantService:
    name = 'want'
    log = LoggingDependency()

    def __init__(self):
        self.dbhelper = DBHelper()
        self.want = self.dbhelper.db.want

    @rpc
    def get_want_user(self, uid):
        if not uid:
            return {'code': -1, 'msg': 'id不能为空'}
        result = self.want.insert_one({'uid': uid})
        return {'code': 0, 'msg': '', 'data': result, 'count': len(result)}

    @rpc
    def get_want_movie(self, mid):
        if not mid:
            return {'code': -1, 'msg': 'id不能为空'}
        result = self.want.insert_one({'mid': mid})
        return {'code': 0, 'msg': '', 'data': result, 'count': len(result)}

    @rpc
    def add_want(self, want):
        uid = want['uid']
        mid = want['movie']['id']
        result = self.want.update_one({
            'uid': uid,
            'movie.id': mid
        }, {'$set': want},
                                      update=True)
        if result.inserted_id:
            return {'code': 0, 'msg': '添加成功'}
        else:
            return {'code': -1, 'msg': '添加失败'}
Ejemplo n.º 3
0
class Service2:
    name = "service2"
    log = LoggingDependency()
    other_rpc = RpcProxy("greeting_service")

    @rpc
    def hello_service2(self, name):
        return self.other_rpc.hello(name)
Ejemplo n.º 4
0
class RoomService:
    name = "room"
    log = LoggingDependency()

    def __init__(self):
        self.dbhelper = DBHelper()
        self.room = self.dbhelper.db.room

    @rpc
    def add_room(self, room):
        if not room.get('name', None):
            return {'code': -1, "msg": "名称不能为空"}
        try:
            result = self.room.insert_one(room)
            if result.inserted_id:
                return {'code': 0, "msg": "添加成功"}
            else:
                return {'code': -1, "msg": "添加失败"}
        except DuplicateKeyError:
            return {'code': -1, "msg": "影厅已存在"}

    @rpc
    def del_rooms(self, rids):
        result = self.room.delete_many(
            {"_id": {
                '$in': [ObjectId(rid) for rid in rids]
            }})
        if result.deleted_count > 0:
            return {'code': 0, "msg": "删除成功", 'count': result.deleted_count}
        elif result.matched_count == 0:
            return {'code': -1, "msg": "删除失败,影厅不存在!"}

    @rpc
    def update_room(self, rid, room):
        result = self.room.update_one({"_id": ObjectId(rid)}, {"$set": room})
        if result.matched_count and result.modified_count > 0:
            return {'code': 0, "msg": "更新成功"}
        elif result.matched_count == 0:
            return {'code': -1, "msg": "更新失败,影厅不存在!"}

    @rpc
    def get_room(self, rid):
        result = self.room.find_one({"_id": ObjectId(rid)})
        result['id'] = str(result['_id'])
        del result['_id']
        return {'code': 0, 'msg': '', 'count': 1, 'data': result}

    @rpc
    def get_rooms(self, skip=0, limit=20):
        result = self.room.find()
        data = []
        for r in result:
            r['id'] = str(r['_id'])
            del r['_id']
            data.append(r)
        return {'code': 0, 'msg': '', 'count': len(data), 'data': data}
Ejemplo n.º 5
0
class SearchService:
    name = 'search'
    movie = RpcProxy('movie')
    log = LoggingDependency()

    def __init__(self):
        self.dbhelper = DBHelper()
        self.db = self.dbhelper.db.tag

    @rpc
    def search(self, name):
        pass
Ejemplo n.º 6
0
class AdminService:
    name = 'admin'
    log = LoggingDependency()

    def __init__(self):
        self.dbhelper = DBHelper()
        self.admin = self.dbhelper.db.admin

    @rpc
    def login(self, username, passwd):
        result = self.admin.find_one({'username': username})
        if result and result.pop("password") == passwd:
            return {"code": 0, "data": result['username'], "msg": "登录成功"}
        else:
            return {"code": -1, "msg": "账号或者密码错误"}

    @rpc
    def raise_exception(self):
        raise Exception()
Ejemplo n.º 7
0
class UserService:
    name = 'user_service'
    log = LoggingDependency()

    def __init__(self):
        self.dbhelper = DBHelper()
        self.user = self.dbhelper.db

    @rpc
    def query(self, name, password):
        try:
            admin = self.user['admin']
            result = admin.find_one()
            if name == result['name'] and password == result['password']:
                return {'code': 1}
            else:
                return {'code': 0}
        except:
            return {'code': 0}
Ejemplo n.º 8
0
class MovieService():
    name = 'movie'
    log = LoggingDependency()

    def __init__(self):
        self.dbhelper = DBHelper()
        self.movie = self.dbhelper.db.movie

    @rpc
    def add_movie(self, movie):
        if not movie.get('name', None):
            return {"code": -1, "msg": "名称不能为空"}
        try:
            result = self.movie.insert_one(movie)
            if result.inserted_id:
                return {
                    "code": 0,
                    "msg": "添加成功",
                    'id': str(result.inserted_id)
                }
            else:
                return {"code": -1, "msg": "添加失败"}
        except DuplicateKeyError:
            return {"code": -1, "msg": "添加失败,电影已存在"}

    @rpc
    def del_movie(self, mids):
        if not mids: return {'code': -1, "msg": "id不能为空"}
        result = self.movie.delete_many(
            {"_id": {
                '$in': [ObjectId(mid) for mid in mids]
            }})
        if result.deleted_count > 0:
            return {"code": 0, "msg": "删除成功", 'count': result.deleted_count}
        else:
            return {"code": -1, "msg": "删除失败,电影不存在"}

    @rpc
    def update_movie(self, mid, movie):
        if not mid:
            return {"code": -1, "msg": "id不能为空"}
        result = self.movie.update_one({'_id': ObjectId(mid)}, {'$set': movie})
        if result.matched_count > 0:
            if result.modified_count == 1:
                return {"code": 0, "msg": "更新成功"}
            else:
                return {"code": 0, "msg": "数据未修改"}
        else:
            return {"code": -1, "msg": "更新失败,电影不存在"}

    # 批量更新标签状态
    @rpc
    def update_status(self, mids, status):
        if not mids:
            return {"code": -1, "msg": "id不能为空"}
        result = self.movie.update_many(
            {"_id": {
                '$in': [ObjectId(mid) for mid in mids]
            }}, {"$set": {
                'status': status
            }})
        if result.matched_count > 0:
            if result.modified_count > 0:
                return {
                    "code": 0,
                    "msg": "更新成功",
                    'count': result.modified_count
                }
            else:
                return {"code": -1, "msg": "更新失败"}
        elif result.matched_count == 0:
            return {"code": -1, "msg": "更新失败,电影不存在"}

    @rpc
    def get_movie(self, mid):
        result = self.movie.find_one({'_id': ObjectId(mid)})
        if result:
            result['id'] = str(result['_id'])
            result.pop('_id')
            return {"code": 0, "msg": "", 'data': result}
        else:
            return {'code': -1, 'msg': '电影不存在'}

    @rpc
    def search_movie(self, name):
        result = self.movie.find(
            {
                'name': {
                    "$regex": name
                },
                'status': {
                    '$in': [1, 2, 3]
                }
            }, {
                'ctime': 0,
                'status': 0
            })
        data = []
        for r in result:
            r['id'] = str(r['_id'])
            del r['_id']
            data.append(r)
        return {"code": 0, "msg": "", 'count': len(data), 'data': data}

    @rpc
    def get_movies(self, status=None, skip=None, limit=None):
        Q = {}
        if status:
            Q['status'] = int(status)
        if isinstance(skip, int) and isinstance(limit, int):
            result = self.movie.find(Q).skip(skip).limit(limit)
        else:
            result = self.movie.find(Q)
        count = self.movie.count(Q)
        data = []
        for r in result:
            r['id'] = str(r['_id'])
            del r['_id']
            data.append(r)
        return {"code": 0, "msg": "", 'count': count, 'data': data}

    @rpc
    def get_names(self, skip=0, limit=20):
        if limit > 20: limit = 20
        result = self.movie.find().skip(skip).limit(limit)
        count = self.movie.count()
        data = []
        for r in result:
            data.append(r['name'])
        return {"code": 0, "msg": "", 'count': count, 'data': data}
Ejemplo n.º 9
0
class TagService():
    name = 'tag'
    log = LoggingDependency()

    def __init__(self):
        self.dbhelper = DBHelper()
        self.tag = self.dbhelper.db.tag

    @rpc
    def add_tag(self, tag):
        try:
            result = self.tag.insert_one(tag)
            if result.inserted_id:
                return {"code": 0, "msg": "添加成功"}
            else:
                return {"code": -1, "msg": "添加失败"}
        except DuplicateKeyError as e:
            return {"code": -1, "msg": "添加失败,标签已存在"}

    @rpc
    def del_tag(self, tids):
        if not tids: return {'code': -1, "msg": "id不能为空"}
        result = self.tag.delete_many(
            {"_id": {
                '$in': [ObjectId(tid) for tid in tids]
            }})
        if result.deleted_count > 0:
            return {"code": 0, "msg": "删除成功"}
        else:
            return {"code": -1, "msg": "删除失败"}

    @rpc
    def update_tag(self, tid, tag):
        if not tid:
            return {"code": -3, "msg": "id不能为空"}
        result = self.tag.update_one({"_id": ObjectId(tid)}, {"$set": tag})
        if result.matched_count == 1:
            if result.modified_count == 1:
                return {"code": 0, "msg": "更新成功"}
            else:
                return {"code": -1, "msg": "更新失败"}
        elif result.matched_count == 0:
            return {"code": -1, "msg": "更新失败,标签不存在"}

    # 批量更新标签状态
    @rpc
    def update_status(self, tids, status):
        if not tids:
            return {"code": -3, "msg": "id不能为空"}
        result = self.tag.update_many(
            {"_id": {
                '$in': [ObjectId(tid) for tid in tids]
            }}, {"$set": {
                'status': status
            }})
        if result.matched_count > 0:
            if result.modified_count > 0:
                return {
                    "code": 0,
                    "msg": "更新成功",
                    'count': result.modified_count
                }
            else:
                return {"code": -1, "msg": "更新失败"}
        elif result.matched_count == 0:
            return {"code": -1, "msg": "更新失败,标签不存在"}

    # 根据 获取标签
    @rpc
    def get_tag(self, tid):
        result = self.tag.find()
        data = []
        for r in result:
            r['id'] = str(r['_id'])
            del r['_id']
            data.append(r)
        return data

    @rpc
    def get_tags(self, status=None, skip=0, limit=10):
        if limit > 10 or limit <= 0: limit = 10
        Q = {}
        if status != None:
            Q['status'] = status
        result = self.tag.find(Q)
        data = []
        for r in result:
            r['id'] = str(r['_id'])
            r['ctime'] = str(r['ctime'])[:19]
            del r['_id']
            data.append(r)
        return {'code': 0, 'msg': '', 'count': len(data), 'data': data}
Ejemplo n.º 10
0
class PosterService:
    name = 'poster'
    log = LoggingDependency()

    def __init__(self):
        self.dbhelper = DBHelper()
        self.poster = self.dbhelper.db.poster

    @rpc
    def add_poster(self, poster):
        result = self.poster.insert_one(poster)
        if result.inserted_id:
            return {"code": 0, "msg": "添加成功"}
        else:
            return {"code": -1, "msg": "添加失败"}

    @rpc
    def update_status(self, pids, status=0):
        result = self.poster.update_many(
            {"_id": {
                '$in': [ObjectId(pid) for pid in pids]
            }}, {"$set": {
                'status': status
            }})
        if result.modified_count > 1:
            return {"code": 0, "msg": "更新成功"}
        else:
            return {"code": -1, "msg": "更新失败"}

    @rpc
    def update_poster(self, pid, poster):
        result = self.poster.update_one({"_id": ObjectId(pid)},
                                        {"$set": poster})
        if result.matched_count > 0:
            if result.modified_count > 0:
                return {"code": 0, "msg": "更新成功"}
            else:
                return {"code": -1, "msg": "未修改数据"}
        else:
            return {"code": -1, "msg": "更新失败,海报不存在"}

    @rpc
    def del_posters(self, pid):
        result = self.poster.delete_one({"_id": ObjectId(pid)})
        if result.deleted_count == 1:
            return {"code": 0, "msg": "删除成功"}
        else:
            return {"code": -1, "msg": "删除失败,海报不存在"}

    @rpc
    def get_poster(self, pid):
        result = self.poster.find({'_id': ObjectId(pid)})
        result['id'] = str(result['_id'])
        del result['_id']
        return {'code': 0, 'msg': '', 'data': result}

    @rpc
    def get_posters(self, status=None, skip=0, limit=10):
        Q = {}
        if status:
            Q['status'] = status
        if skip and limit:
            result = self.poster.find(Q).skip(skip).limit(limit)
        else:
            result = self.poster.find(Q)
        data = []
        for r in result:
            r['id'] = str(r['_id'])
            del r['_id']
            data.append(r)
        return {'code': 0, 'msg': '', 'data': data}
Ejemplo n.º 11
0
class ScheduleService:
    name = "schedule"
    log = LoggingDependency()

    def __init__(self):
        self.dbhelper = DBHelper()
        self.schedule = self.dbhelper.db.schedule

    @rpc
    def add_schedule(self, schedule):
        try:
            result = self.schedule.insert_one(schedule)
            if result.inserted_id:
                return {'code': 0, "msg": "添加成功"}
            else:
                return {'code': -1, "msg": "添加失败"}

        except DuplicateKeyError as e:
            return {'code': -1, "msg": "添加失败,排期已存在"}

    @rpc
    def del_schedule(self, sids):
        if not sids:
            return {'code': -1, 'msg': 'id不能为空'}
        result = self.schedule.delete_many(
            {"_id": {
                '$in': [ObjectId(sid) for sid in sids]
            }})
        if result.deleted_count > 0:
            return {'code': 0, "msg": "删除成功"}
        else:
            return {'code': -1, "msg": "删除失败,排期不存在"}

    @rpc
    def update_schedule(self, new_data):
        sid = new_data.pop('id')
        result = self.schedule.update_one({"_id": ObjectId(sid)},
                                          {"$set": new_data})
        if result.modified_count == 1:
            return {'code': 0, "msg": "更新成功"}
        else:
            return {'code': -1, "msg": "更新失败,排期不存在"}

    @rpc
    def update_status(self, sids, status):
        status = int(status)
        result = self.schedule.update_many(
            {"_id": {
                '$in': [ObjectId(sid) for sid in sids]
            }}, {"$set": {
                'status': status
            }})
        if result.modified_count > 0:
            return {'code': 0, "msg": "更新成功", 'count': result.modified_count}
        else:
            return {'code': -1, "msg": "更新失败,排期不存在"}

    @rpc
    def get_schedule(self, sid):
        result = self.schedule.find_one({"_id": ObjectId(sid), 'status': 1})
        if result:
            result['id'] = str(result['_id'])
            del result['_id']
            return {'code': 0, 'msg': '', 'data': result}
        else:
            return {'code': -1, 'msg': '该排期不存在'}

    @rpc
    def get_schedules(self, skip=None, limit=None):
        if isinstance(skip, int) and isinstance(limit, int):
            result = self.schedule.find().skip(skip).limit(limit)
        else:
            result = self.schedule.find()
        count = self.schedule.count()
        data = []
        for r in result:
            r['id'] = str(r['_id'])
            del r['_id']
            data.append(r)
        return {'code': 0, 'msg': '', 'count': count, 'data': data}

    @rpc
    def get_schedules_mid(self, mid=None):
        Q = {'status': 1, 'date': {"$gte": str(datetime.date.today())}}
        if mid != None:
            Q['movie.id'] = mid
        result = self.schedule.find(Q, {"movie": 0})
        data = []
        for r in result:
            r['id'] = str(r['_id'])
            del r['_id']
            data.append(r)
        return {'code': 0, 'msg': '', 'data': {'schedule': data}}
Ejemplo n.º 12
0
class OrderService:
    name = 'order'
    log = LoggingDependency()

    def __init__(self):
        self.dbhelper = DBHelper()
        self.order = self.dbhelper.db.order

    # 生成新订单
    @rpc
    def add_order(self, order):
        try:
            result = self.order.insert_one(order)
            return {'code': 0, "msg": "订单生成成功", "oid": str(result.inserted_id)}
        except DuplicateKeyError as e:
            msg = e.details['errmsg']
            m = re.search(r'(\d+):(\d+)', msg)
            return {'code': -1, "msg": "生成订单失败,座位<" + str(m.group(1)) + "排" + str(m.group(2)) + "座>已售出!"}

    # 取消订单
    @rpc
    def cancel_order(self, oid):
        result = self.order.update_one({'_id': ObjectId(oid)}, {"$set": {'status': 3}})
        if result.matched_count == 1:
            if result.modified_count == 1:
                return {'code': 0, "msg": "订单取消成功"}
            else:
                return {'code': -1, "msg": "取消订单失败,订单已经取消了"}
        else:
            return {'code': -1, "msg": "订单不存在"}

    # 支付成功后,更新订单
    @rpc
    def update_order(self, oid):
        if not oid:
            return {'code': -1, "msg": "id不能为空"}
        result = self.order.update_one({'_id': ObjectId(oid)}, {"$set": {'status': 1}})
        if result.matched_count == 1:
            if result.modified_count == 1:
                return {'code': 0, "msg": "支付成功"}
            else:
                return {'code': -1, "msg": "支付失败,订单已经支付过了"}
        else:
            return {'code': -1, "msg": "订单不存在"}

    @rpc
    def get_order(self, oid, uid=None):
        Q = {'_id': ObjectId(oid)}
        if uid:
            Q['uid'] = uid
        result = self.order.find_one(Q)
        result['id'] = str(result['_id'])
        del result['_id']
        return {
            'code': 0,
            'msg': '',
            'data': result
        }

    @rpc
    def get_orders(self, uid, status=None):
        Q = {'uid': uid}
        if status:
            Q['status'] = status
        result = self.order.find(Q)
        count = self.order.count(Q)
        data = []
        for r in result:
            r['id'] = str(r['_id'])
            del r['_id']
            data.append(r)
        return {'code': 0, 'msg': '', 'count': count, 'data': data}

    @rpc
    def get_seen(self, uid):
        Q = {'uid': uid, 'status': 2}
        result = self.order.find(Q)
        count = self.order.count(Q)
        data = []
        mids = []  # 暂时这样写吧,有时间再优化,dict无法hash,无法使用set去重
        for r in result:
            if r['schedule']['movie']['id'] in mids:
                continue
            mids.append(r['schedule']['movie']['id'])
            data.append(r['schedule']['movie'])
        return {'code': 0, 'msg': '', 'count': count, 'data': data}

    @rpc
    def get_orders_all(self, skip=None, limit=None):
        if isinstance(skip, int) and isinstance(limit, int):
            result = self.order.find().skip(skip).limit(limit)
        else:
            result = self.order.find()
        count = self.order.count()
        data = []
        for r in result:
            r['id'] = str(r['_id'])
            del r['_id']
            data.append(r)
        return {
            'code': 0,
            'msg': '',
            'count': count,
            'data': data
        }

    @rpc
    def get_sold_seats(self, sid):
        result = self.order.find({'schedule.id': sid, 'status': {'$in': [0, 1, 2]}}, {'seats': 1})
        data = set()
        if result:
            for _ in result:
                for __ in _['seats']:
                    data.add(__)
        return {'code': 0, 'msg': '', 'data': list(data)}
Ejemplo n.º 13
0
class ModelService:
    name = 'model_service'
    log = LoggingDependency()

    def __init__(self):
        self.dbhelper = DBHelper()
        self.model = self.dbhelper.db
    
    @rpc
    def save(self, data, type):
        try:
            if type == 'stl':
                stl_model = self.model['stl']
                stl_model.insert_one(data)
                return {'code': 1}
            elif type == 'obj':
                obj_model = self.model['obj']
                obj_model.insert_one(data)
                return {'code': 1}
            else:
                return {'code': 0}
        except:
            return {'code': 0}

    @rpc
    def read(self, name):
        pass
    
    @rpc
    def reads(self):
        try:
            data = []
            stl_model = self.model['stl']
            if stl_model != None:
                for m in stl_model.find():
                    data.append(m['name'])
            obj_model = self.model['obj']
            if obj_model != None:
                for m in obj_model.find():
                    data.append(m['name'])
            
            return {'code':1,'data':data}
        except Exception as e:
            return {'code':0,'data':str(e)}

    @rpc
    def delete(self, data, type):
        try:
            if type == 'stl':
                stl_model = self.model['stl']
                stl_model.delete_one(data)
                return {'code': 1}
            elif type == 'obj':
                obj_model = self.model['obj']
                obj_model.delete_one(data)
                return {'code': 1}
            else:
                return {'code': 0}
        except:
            return {'code': 0}
            
Ejemplo n.º 14
0
class CommentService:
    name = 'comment'
    log = LoggingDependency()

    def __init__(self):
        self.dbhelper = DBHelper()
        self.comment = self.dbhelper.db.comment
        self.supported = self.dbhelper.db.supported

    @rpc
    def add_comment(self, comment):
        uid = comment['user']['id']
        mid = comment['movie']['id']
        result = self.comment.update_one({
            'user.id': uid,
            'movie.id': mid
        }, {
            '$set': comment,
            '$setOnInsert': {
                'support': 0,
                'ctime': str(datetime.datetime.now())[:19],
                'status': 1
            }
        },
                                         upsert=True)
        if result.upserted_id:
            return {'code': 0, "msg": "评论成功"}
        if result.matched_count > 0:
            if result.modified_count > 0:
                return {'code': 0, "msg": "评论成功"}
            else:
                return {'code': 0, "msg": "评论未修改"}
        else:
            return {'code': -1, "msg": "评论失败"}

    @rpc
    def support(self, uid, cid):
        # 点过赞再次点击取消赞
        count = self.supported.count({'uid': uid, 'cid': cid})
        if count > 0:  # 已经点过赞了
            result = self.comment.update_one({"_id": ObjectId(cid)},
                                             {"$inc": {
                                                 'support': -1
                                             }})
            self.supported.find_one_and_delete({'uid': uid, 'cid': cid})
            msg = "取消点赞"
        else:  # 未点过赞
            result = self.comment.update_one({"_id": ObjectId(cid)},
                                             {"$inc": {
                                                 'support': 1
                                             }})
            self.supported.insert_one({
                'uid':
                uid,
                'cid':
                cid,
                'ctime':
                str(datetime.datetime.now())[:19]
            })
            msg = "点赞成功"
        if result.matched_count > 0:
            if result.modified_count > 0:
                return {'code': 0, "msg": msg}
            else:
                return {'code': -1, "msg": "点赞失败"}
        else:
            return {'code': -1, "msg": "点赞失败,评论不存在"}

    @rpc
    def update_comments(self, cids, status):
        result = self.comment.update_many(
            {"_id": {
                '$in': [ObjectId(cid) for cid in cids]
            }}, {"$set": {
                'status': int(status)
            }})
        if result.modified_count > 0:
            return {'code': 0, "msg": "删除成功", 'count': result.deleted_count}
        else:
            return {'code': -1, "msg": "删除失败"}

    @rpc
    def del_comments(self, cids):
        result = self.comment.delete_many(
            {"_id": {
                '$in': [ObjectId(cid) for cid in cids]
            }})
        if result.deleted_count > 0:
            return {'code': 0, "msg": "删除成功", 'count': result.deleted_count}
        else:
            return {'code': -1, "msg": "删除失败"}

    @rpc
    def del_comment(self, uid, mid):
        result = self.comment.delete_one({'user.id': uid, 'movie.id': mid})
        if result.deleted_count > 0:
            return {'code': 0, "msg": "评论已删除"}
        else:
            return {'code': -1, "msg": ""}

    @rpc
    def get_comments(self, skip=None, limit=None):
        if isinstance(skip, int) and isinstance(limit, int):
            result = self.comment.find().skip(skip).limit(limit)
        else:
            result = self.comment.find()
        count = self.comment.count()
        data = []
        for r in result:
            r['id'] = str(r['_id'])
            del r['_id']
            data.append(r)
        return {'code': 0, 'msg': '', 'count': count, 'data': data}

    @rpc
    def get_comment_id(self, cid):
        Q = {'_id': ObjectId(cid)}
        result = self.comment.find_one(Q)
        result['id'] = str(result['_id'])
        del result['_id']
        return {'code': 0, 'msg': '', 'data': result}

    @rpc
    def get_comment(self, uid, mid):
        Q = {'user.id': uid, 'movie.id': mid}
        result = self.comment.find_one(Q)
        if result:
            result['id'] = str(result['_id'])
            del result['_id']
            return {'code': 0, 'msg': '', 'data': result}
        else:
            return {'code': -1, 'msg': '评论不存在'}

    @rpc
    def get_comments_by_user(self, uid):
        Q = {'user.id': uid}
        result = self.comment.find(Q)
        count = self.comment.count(Q)
        data = []
        for r in result:
            r['id'] = str(r['_id'])
            del r['_id']
            data.append(r)
        return {'code': 0, 'msg': '', 'count': count, 'data': data}

    @rpc
    def get_comments_by_movie(self, mid, skip=None, limit=None):
        Q = {'movie.id': mid}
        if isinstance(skip, int) and isinstance(limit, int):
            result = self.comment.find(Q).skip(skip).limit(limit)
        else:
            result = self.comment.find(Q)
        count = self.comment.count(Q)
        data = []
        for r in result:
            r['id'] = str(r['_id'])
            del r['_id']
            data.append(r)
        return {
            'code': 0,
            'msg': '',
            'page': int(count // limit),
            'data': data
        }

    @rpc
    def get_newest(self, skip=0, limit=20):
        result = self.comment.find().sort(
            'support', pymongo.DESCENDING).skip(skip).limit(limit)
        data = []
        for _ in result:
            _['id'] = str(_['_id'])
            del _['_id']
            data.append(_)
        return {'code': 0, 'msg': '', 'data': data}
Ejemplo n.º 15
0
class UserService:
    name = 'user'
    log = LoggingDependency()

    def __init__(self):
        self.dbhelper = DBHelper()
        self.user = self.dbhelper.db.user
        self.want = self.dbhelper.db.want

    @rpc
    def get_want_by_user(self, uid):
        result = self.want.find({'uid': uid})
        data = []
        for _ in result:
            _['movie']['wid'] = str(_['_id'])
            data.append(_['movie'])
        return {"code": 0, "msg": "", 'data': data}

    @rpc
    def get_want_by_mid(self, uid, mid):
        result = self.want.find_one({'uid': uid, 'movie.id': mid})
        if result:
            return {"code": 0, "msg": "已添加到想看列表"}
        else:
            return {"code": -1, "msg": "未添加到想看列表"}

    @rpc
    def get_want_count_movie(self, mid):
        result = self.want.count({'mid': mid})
        return result

    @rpc
    def add_or_del_want(self, want):
        uid = want['uid']
        mid = want['movie']['id']
        result = self.want.find_one({'uid': uid, 'movie.id': mid})
        if result:
            self.want.remove({'_id': result['_id']})
            data = {'code': 0, 'msg': '已从想看电影列表移除'}
        else:
            self.want.insert_one(want)
            data = {'code': 0, 'msg': '成功添加到想看电影列表'}
        return data

    @rpc
    def get_user(self, uid):
        result = self.user.find_one({'_id': ObjectId(uid)}, {'nickname': 1, '_id': 1})
        result['id'] = str(result['_id'])
        del result['_id']
        return result

    @rpc
    def get_users(self, skip=None, limit=None):
        if isinstance(skip, int) and isinstance(limit, int):
            result = self.user.find({}, {'password': 0}).skip(skip).limit(limit)
        else:
            result = self.user.find({}, {'password': 0})
        count = self.user.count()
        data = []
        for _ in result:
            _['id'] = str(_['_id'])
            _['phone'] = _['phone'][:3] + '*****' + _['phone'][8:]
            del _['_id']
            data.append(_)
        return {
            'code': 0,
            'msg': '',
            'count': count,
            'data': data
        }

    @rpc
    def update_users(self, uids, status):
        result = self.user.update_many({'_id': {'$in': [ObjectId(uid) for uid in uids]}}, {'$set': {'status': status}})
        if result.matched_count > 0:
            if result.modified_count > 0:
                return {'code': 0, 'msg': '更新成功'}
            else:
                return {'code': 0, 'msg': '状态未更改'}
        else:
            return {'code': -1, 'msg': '用户不存在'}

    @rpc
    def login(self, phone, passwd):
        result = self.user.find_one({'phone': phone})
        if not result:
            return {"code": -1, "msg": "账号不存在!"}
        if int(result['status']) == 0:
            return {"code": -1, "msg": "账号被冻结,请联系管理员解除冻结"}
        if result and result.get("password", None) == self.crypto(passwd):
            data = {
                'uid': str(result['_id']),
                "phone": result['phone'],
                "nickname": result['nickname'],
                "admin": False,
                "super": False,
            }
            token = self.encode_auth_token(data)
            return {"code": 0, "token": token.decode(), "msg": "登录成功"}
        else:
            return {"code": -1, "msg": "账号或者密码错误"}

    @rpc
    def register(self, user):
        user["password"] = self.crypto(user["password"])
        try:
            result = self.user.insert_one(user)
            if result.inserted_id:
                return {"code": 0, "msg": "注册成功"}
        except DuplicateKeyError as e:
            return {"code": -1, "msg": "该手机号已注册,请登录"}
        except Exception as e:
            return {"code": -1, "msg": "注册失败"}

    @rpc
    def lock(self, uid):
        result = self.user.update_one({'_id': uid}, {"$set": {"status": 0}})
        if result.matched_count == 1:
            if result.midified_count == 1:
                return {"code": 0, "msg": "禁用成功"}
            else:
                return {"code": -1, "msg": "禁用失败"}
        else:
            return {"code": -1, "msg": "启用成功"}

    @rpc
    def update(self, user):
        uid = user['id']
        del user['id']
        upgradable = ['password', 'nick', 'status']  # 允许更新的值
        for k, v in user:
            if not k in upgradable:
                del upgradable[k]
        result = self.user.update_one({"_id", uid}, {"$set": user})
        if result.matched_count == 1:
            if result.midified_count == 1:
                return {"code": 0, "msg": "更新成功"}
            else:
                return {"code": -1, "msg": "更新失败"}
        else:
            return {"code": -1, "msg": "更新失败"}

    def crypto(self, src):
        import hashlib
        m = hashlib.md5()
        m.update(src.encode('utf-8'))
        return m.hexdigest()

    def encode_auth_token(self, data):
        """
        生成认证Token
        :param user_id: int
        :param login_time: int(timestamp)
        :return: string
        """
        from UserService.settings import SECRET_KEY
        try:
            payload = {
                'exp': datetime.datetime.utcnow() + datetime.timedelta(days=1),
                'iat': datetime.datetime.utcnow(),
            }
            payload.update(data)
            return jwt.encode(
                payload,
                SECRET_KEY,
                algorithm='HS256'
            )
        except Exception as e:
            return e