def getObject(cls, obj_type, error, objects=None, return_type='QuerySet', include_deleted=False, **args): if objects is None: objects = obj_type.objects.all() # 如果是获取 object: if return_type == 'object': query_set = cls.getObject(obj_type, error, objects, 'QuerySet', include_deleted, **args) if query_set.exists(): return query_set[0] else: raise ErrorException(error) # 如果是获取 字典 数据(通过 converToDict): if return_type == 'dict': object = cls.getObject(obj_type, error, objects, 'object', include_deleted, **args) return object.convertToDict() # 实际上执行查询的部分: try: if not include_deleted and hasattr(obj_type, 'is_deleted'): return objects.filter(is_deleted=False, **args) else: return objects.filter(**args) except: raise ErrorException(ErrorType.ParameterError)
def getRequestDict(request, POST=[], GET=[], FILES=[]): data = dict() for item in POST: value = request.POST.get(item[0]) if value: data[item[0]] = convertDataType(value, item[1]) else: raise ErrorException(ErrorType.ParameterError) for item in GET: value = request.GET.get(item[0]) if value: data[item[0]] = convertDataType(value, item[1]) else: raise ErrorException(ErrorType.ParameterError) for key in FILES: value = request.FILES.get(key) if value: data[key] = value else: raise ErrorException(ErrorType.ParameterError) print(data) return data
def getRequestDict(cls, request, method='POST', params=[], files=[]): data = dict() if method.upper() != request.META['REQUEST_METHOD']: raise ErrorException(ErrorType.InvalidRequest) body = request.body.decode() if body: raw = json.loads(body) else: raw = {} for item in params: if item[0] in raw: data[item[0]] = cls.convertDataType(raw[item[0]], item[1]) elif item[1] != 'var': # 如果该参数是必选的 raise ErrorException(ErrorType.ParameterError) for key in files: value = request.FILES.get(key) if value: data[key] = value else: raise ErrorException(ErrorType.ParameterError) print(data) return data
def getObject(obj_type, error, objects=None, id=None, name=None, return_type='QuerySet', include_deleted=False): if objects is None: objects = obj_type.objects.all() if return_type == 'object': query_set = getObject(obj_type, error, objects, id, name, 'QuerySet', include_deleted) if query_set.exists(): return query_set[0] else: raise ErrorException(error) if return_type == 'dict': object = getObject(obj_type, error, objects, id, name, 'object', include_deleted) return object.convertToDict() if id: if not include_deleted and hasattr(obj_type, 'is_deleted'): return objects.filter(id=id, is_deleted=False) else: return objects.filter(id=id) if name: if not include_deleted and hasattr(obj_type, 'is_deleted'): return objects.filter(name=name, is_deleted=False) else: return objects.filter(name=name) return None
def deleteFriend(cls, user: User, fid): friends = user.getFriends() for friend in friends: if friend.id == fid: friend.delete() else: raise ErrorException(ErrorType.NotAFriend)
def addFriend(cls, user: User, fuid): friend = user.getFriends() for i in friend: if i.id==fuid: raise ErrorException(ErrorType.AlreadyAFriend) user.addFriend(fuid) user.save()
def operFriendReq(cls, user: User, fuid, accept): friends = user.getFriends() for friend in friends: if friend.id == fuid: friend.oper(accept) else: raise ErrorException(ErrorType.NotAFriend)
def convertDataType(value, type='str'): try: if type == 'int': value = int(value) elif type == 'int[]': if not isinstance(value, list): value = json.loads(value) for i in range(len(value)): value[i] = int(value[i]) elif type == 'int[][]': if not isinstance(value, list): value = json.loads(value) for i in range(len(value)): for j in range(len(value[i])): value[i][j] = int(value[i][j]) elif type == 'date': value = datetime.datetime.strptime(value, '%Y-%m-%d') elif type == 'datetime': value = datetime.datetime.strptime(value, '%Y-%m-%d %H:%M:%S') # 其他类型判断 return value except: raise ErrorException(ErrorType.ParameterError)
def resetPwd(cls, user: User, old, new): cls.Check.ensurePasswordFormat(old) cls.Check.ensurePasswordFormat(new) if not user.password == old: raise ErrorException(ErrorType.InvalidPassword) user.password = new user.save()
def getProgressReqs(cls, user: User, pid=None, tid=None): # 如果提供了 pid 和 tid if pid is not None and tid is not None: raise ErrorException(ErrorType.ParameterError) # 如果提供 pid if pid is not None: proj = ProjectView.Common.getProject(id=pid) return proj.convertToDict('pr') # 如果提供 tid if tid is not None: task = cls.Common.getTask(id=tid) return task.convertToDict('pr') raise ErrorException(ErrorType.ParameterError)
def refreshToken(cls, user: User): auth = AuthorizationManager.getAuth(user) if auth is None: raise ErrorException(ErrorType.InvalidToken) auth.refresh() return {'auth': auth.convertToDict()}
def ensureObjectNotExist(cls, obj_type, error, objects=None, include_deleted=False, **args): if cls.hasObjects(obj_type, objects, include_deleted, **args): raise ErrorException(error)
def getObjectRelated(cls, objects, key, unique=False): result = [] for obj in objects: try: result.append(getattr(obj, key)) except: raise ErrorException(ErrorType.AttrNotExist) if unique: result = list(set(result)) return result
def sendCode(cls, un, email, type): conf = settings.CODE_TEXT[type] code = CodeManager.generateCode(un, email, type) if not (type == 'register' or type == 'forget'): raise ErrorException(ErrorType.ParameterError) print("sendCode to %s [%s]: %s" % (email, type, code)) cls._doSendCode(un, email, code, conf)
def _doSendCode(cls, un, email, code, conf): try: from django.core.mail import send_mail send_mail(conf[0], conf[1] % (un, code, CodeDatum.CODE_SECOND), conf[2], [email]) except smtplib.SMTPException as exception: print("ERROR in sendEmailCode: " + str(exception)) raise ErrorException(ErrorType.EmailSendError)
def hasObjects(cls, obj_type, objects=None, include_deleted=False, **args): if objects is None: objects = obj_type.objects.all() # 实际上执行查询的部分: try: if not include_deleted and hasattr(obj_type, 'is_deleted'): return objects.filter(is_deleted=False, **args).exists() else: return objects.filter(**args).exists() except: raise ErrorException(ErrorType.ParameterError)
def processWebsocketRequest(request, key_data=[]): res_data = dict() for data in key_data: key = data[0] type = data[1] if key in request: res_data[key] = convertDataType(request[key], type) else: raise ErrorException(ErrorType.ParameterError) print('request: ' + str(res_data)) return res_data
def ensureAvatar(cls, avatar): if not avatar: raise ErrorException(ErrorType.InvalidAvatar) if not type(avatar)== models.ImageField: raise ErrorException(ErrorType.InvalidAvatar)
def ensureDutyFormat(cls, val: str): if not val: raise ErrorException(ErrorType.InvalidDuty) if not len(val)<16: raise ErrorException(ErrorType.InvalidDuty)
def ensureContactFormat(cls, val: str): if not val: raise ErrorException(ErrorType.InvalidConnact) if not len(val)<16: raise ErrorException(ErrorType.InvalidConnact)
def ensureDescFormat(cls, val: str): if not val: raise ErrorException(ErrorType.InvalidDesc) if not len(val) < 100: raise ErrorException(ErrorType.InvalidDesc)
def ensureNameFormat(cls, val: str): if not val: raise ErrorException(ErrorType.InvalidTaskName) if len(val) > Task.NAME_LEN: raise ErrorException(ErrorType.InvalidTaskName)
def ensureStatusFormat(cls, val: int): if val not in [ TaskStatus.Failed.value, TaskStatus.Cancelled.value, TaskStatus.Paused.value ]: raise ErrorException(ErrorType.InvalidTaskStatusId)
def ensureDurationFormat(cls, val: int): if val < 0: raise ErrorException(ErrorType.InvalidTaskDuration)
def ensureDescFormat(cls, val: str): if len(val) > Task.DESC_LEN: raise ErrorException(ErrorType.InvalidTaskDesc)
def ensurePasswordCorrect(cls, user, pw): pw = UserView.cryptoPassword(pw) if user.password != pw: raise ErrorException(ErrorType.IncorrectPassword)
def ensureEndDateFormat(cls, start: datetime.datetime, end: datetime.datetime): if start > end: raise ErrorException(ErrorType.InvalidTaskEndDate)
def deleteAuth(cls, user: User): if user in cls.authorizations: cls.authorizations.pop(user) else: raise ErrorException(ErrorType.InvalidUser)
def ensureProgressFormat(cls, val: int): if not (0 <= val <= 100): raise ErrorException(ErrorType.InvalidTaskProgress)
def getUser(cls, token): for user in cls.authorizations: if cls.authorizations[user].token==token: if datetime.datetime.now() > token.out_time: raise ErrorException(ErrorType.InvalidToken) return user