def permissionReload(request): interfaceData = TbAdminInterfacePermissionRelation.objects.all() for index in interfaceData: try: RedisCache().del_data( "%s_%s" % (PermissionConst.urlDefaultPermission, index.url)) RedisCache().del_data( "%s_%s" % (PermissionConst.urlAllPermission, index.url)) except: pass teamData = TbAdminTeam.objects.all() for teamIndex in teamData: try: RedisCache().del_data("%s_%s_%s" % (PermissionConst.team_url_permission, teamIndex.teamName, index.url)) print("%s_%s_%s" % (PermissionConst.team_url_permission, teamIndex.teamName, index.url)) except: pass userData = TbUser.objects.all() for userIndex in userData: try: RedisCache().del_data( "%s_%s" % (PermissionConst.user_permission, userIndex.loginName)) except: pass return HttpResponse(ApiReturn().toJson())
def get_url_all_permissions(url): # 先去缓存拿 try: urlAllPermission = json.loads(RedisCache().get_data("urlAllPermission_%s" % url)) except: # 缓存没拿到 去数据库拿再写入缓存 modList = TbAdminInterfacePermissionRelation.objects.filter(url=url,state=1) urlAllPermission = [] for index in modList: urlAllPermission.append(index.permission) RedisCache().set_data("%s_%s" % (PermissionConst.urlAllPermission,url), json.dumps(urlAllPermission)) return urlAllPermission
def getCacheManage(request): context = {} checkArr = parse.unquote(request.POST.get("checkArr", None)) if "t" in (json.dumps(checkArr)).lower(): try: checkArrDict = json.loads(checkArr) if checkArrDict["cachekey"] != "": try: value = RedisCache().get_data(checkArrDict["cachekey"]) context["pageDatas"] = [{ "key": checkArrDict["cachekey"], "values": value }] except ValueError: context = {} response = render( request, "myadmin/cacheManage/subPages/cacheManage_sub_page.html", context) return response except Exception: return render( request, "myadmin/cacheManage/subPages/cacheManage_sub_page.html", context) try: allKeys, allDatas = RedisCache().getAllDatas() except ValueError: print(traceback.format_exc()) return render( request, "myadmin/cacheManage/subPages/cacheManage_sub_page.html", context) allDatasDict = dict(zip(allKeys, allDatas)) valuesList = [] for key in allDatasDict: valuesDict = {} valuesDict["key"] = key valuesDict["values"] = allDatasDict[key] valuesList.append(valuesDict) context["pageDatas"] = valuesList response = render( request, "myadmin/cacheManage/subPages/cacheManage_sub_page.html", context) return response
def getTeamPermission(request): teamKey = request.POST.get("teamKey") allUrl = TbAdminInterfacePermissionRelation.objects.filter(state=1) for urlIndex in allUrl: try: #先删缓存 RedisCache().del_data( "%s_%s_%s" % (PermissionConst.team_url_permission, teamKey, urlIndex.url)) except: pass teamPermission = TbAdminTeamPermissionRelation.objects.filter( teamKey=teamKey, state=1) teamPermissionList = [] for index in teamPermission: tmpDict = {} tmpDict["permissionKey"] = index.permissionKey try: tmpDict[ "permissionName"] = TbAdminInterfacePermissionRelation.objects.get( permissionKey=index.permissionKey).permissionName except: tmpDict["permissionName"] = "" teamPermissionList.append(tmpDict) return HttpResponse(ApiReturn(body=teamPermissionList).toJson())
def addPermissionsToTeam(teamKey): #清空有关本小组的缓存 allUrlData = TbAdminInterfacePermissionRelation.objects.filter(state=1) for index in allUrlData: try: RedisCache().del_data("team_url_%s_%s" % (teamKey, index.url)) except: continue permissionResult = TbAdminInterfacePermissionRelation.objects.filter( state=1) permissionResultList = dbModelListToListDict(permissionResult) for permission in permissionResultList: teamPermissionList = TbAdminTeamPermissionRelation.objects.filter( teamKey=teamKey, permissionKey=permission["permissionKey"]) if len(teamPermissionList) == 0: permissionKey = permission["permissionKey"] relationResult = TbAdminTeamPermissionRelation() relationResult.permissionKey = permissionKey relationResult.teamKey = teamKey relationResult.state = 1 relationResult.save() else: for permissionIndex in teamPermissionList: if permissionIndex.state == 0: permissionIndex.state = 1 permissionIndex.save()
def delRedisKey(request): redisKey = request.POST.get("key","") if redisKey == "": return HttpResponse(ApiReturn(ApiReturn.CODE_WARNING,message="必须有key参数!").toJson()) try: RedisCache().del_data(redisKey) except Exception as e: return HttpResponse(ApiReturn(ApiReturn.CODE_WARNING,message="KEY[%s]查询错误 %s" % (redisKey,e)).toJson()) return HttpResponse(ApiReturn().toJson())
def editCacheData(request): cacheData = json.loads(request.POST.get("cacheData")) try: RedisCache().set_data(cacheData["cacheKey"], cacheData["cacheValue"]) return HttpResponse(ApiReturn().toJson()) except ValueError: return HttpResponse( ApiReturn(code=ApiReturn.CODE_WARNING, message="编辑缓存出错,请联系管理员").toJson())
def flushAllDatas(request): try: RedisCache().flushall() return HttpResponse(ApiReturn().toJson()) except ValueError as e: print(traceback.format_exc()) message = "清空所有数据出错,请联系管理员 %s" % e logger.error(message) return HttpResponse( ApiReturn(code=ApiReturn.CODE_WARNING, message=message).toJson())
def get_user_default_permission(loginName): try: userPermission = json.loads(RedisCache().get_data("%s_%s" % (PermissionConst.user_permission, loginName))) return True, userPermission except: # 从redis拿不到 从数据拿 然后将信息写入redis try: userDefaultPermission = int(TbUser.objects.get(state=1, loginName=loginName).defaultPermission) userPermission = {} userPermission["defaultPermission"] = userDefaultPermission if len(TbUserPermissionRelation.objects.filter(state=1, loginName=loginName)) > 0: userPermission["otherPermission"] = 1 else: userPermission["otherPermission"] = 0 RedisCache().set_data("%s_%s" % (PermissionConst.user_permission, loginName), json.dumps(userPermission), 60 * 60 * 24 * 15) return True, userPermission except: return False, {}
def deleteCacheData(request): cacheDataKey = request.POST.get("cacheDataKey", None) if cacheDataKey: try: RedisCache().del_data(cacheDataKey) return HttpResponse(ApiReturn().toJson()) except ValueError as e: print(traceback.format_exc()) message = "删除数据错误,请联系管理员 %s" % e logger.error(message) return HttpResponse( ApiReturn(code=ApiReturn.CODE_WARNING, message=message).toJson())
def addPermissionsToUser(request): userRequest = json.loads(request.POST.get("userPermissionsData")) logger.info("addPermission %s" % request.POST.get("userPermissionsData")) loginName = userRequest["loginName"] try: RedisCache().del_data("%s_%s" % (PermissionConst.user_permission, loginName)) except: pass # loginName = dbModelListToListDict(TbUser.objects.filter(id=userId))[0]["loginName"] permissionKeys = userRequest["permissionKeys"] userPermissionsData = {} # relationData = TbAdminUserPermissionRelation.objects.filter(loginName=loginName) relationData = TbUserPermissionRelation.objects.filter(loginName=loginName) relationDataList = dbModelListToListDict(relationData) for relation in relationDataList: '''判断loginName已经插入到数据库中的权限,是否在这次需要插入的permission列表中''' relationPermissionKey = relation["permissionKey"] '''如果在列表中,说明该permission是这次需要增加的;并且state=0,那么需要更新''' if relationPermissionKey in permissionKeys: if relation["state"] == 0: relation["state"] = 1 UserPermissionRelationService.updateUserPermission(relation) else: '''如果不在列表中,说明该permission是这次需要删除的;并且state=1,将state置为0''' if relation["state"] == 1: relation["state"] = 0 UserPermissionRelationService.updateUserPermission(relation) '''判断loginName是否已经有授权permissionKey,如果没有授权,新增;如果有授权,判断该授权是否已经删除,如果已经删除了,进行更新''' for permissionKey in permissionKeys: userPermissionsData["loginName"] = loginName userPermissionsData["permissionKey"] = permissionKey data = TbUserPermissionRelation.objects.filter( loginName=loginName, permissionKey=permissionKey) '''没有授权,新增''' if len(data) == 0: result = TbUserPermissionRelation() result.loginName = userPermissionsData["loginName"] result.permissionKey = userPermissionsData["permissionKey"] result.save() else: '''有授权,判断授权是否被删除了''' permissionList = dbModelListToListDict(data) for permissionIndex in permissionList: if permissionIndex["state"] == 0: UserPermissionRelationService.updateUserPermission( userPermissionsData) return HttpResponse(ApiReturn().toJson())
def getCacheValueForCacheKey(request): cacheDataKey = request.POST.get("cacheDataKey", None) dataDict = {} if cacheDataKey: try: value = RedisCache().get_data(cacheDataKey) dataDict["cacheKey"] = cacheDataKey dataDict["cacheValue"] = value return HttpResponse(ApiReturn(body=dataDict).toJson()) except ValueError: return HttpResponse( ApiReturn(code=ApiReturn.CODE_WARNING, message="查询缓存出错,请联系管理员").toJson()) else: return HttpResponse( ApiReturn(code=ApiReturn.CODE_WARNING, message="查询缓存出错,请联系管理员").toJson())
def editUser(request): try: requestDict = json.loads(request.POST.get("userData")) try: RedisCache().del_data( "%s_%s" % (PermissionConst.user_permission, requestDict["loginName"])) except: pass if requestDict["pwd"] != requestDict["pwd1"]: return HttpResponse( ApiReturn(code=ApiReturn.CODE_ERROR, message="两次密码输入不一致,请检查重新输入").toJson()) if requestDict["token"] != "" and len( TbUser.objects.filter( token=requestDict["token"], state=1, ).filter(~Q(loginName=requestDict["loginName"]))) > 0: return HttpResponse( ApiReturn(code=ApiReturn.CODE_WARNING, message="用户创建失败,请检查token是否重复").toJson()) '''如果编辑时,用户没有输入密码,那么就给密码赋值默认值''' if requestDict["pwd"] == "" and requestDict["pwd1"] == "": del requestDict["pwd1"] pwdMd5 = hashlib.md5() pwdMd5.update("123456".encode("utf-8")) requestDict["pwd"] = pwdMd5.hexdigest() UserService.updateUser(requestDict) return HttpResponse(ApiReturn().toJson()) del requestDict["pwd1"] pwdMd5 = hashlib.md5() pwdMd5.update(requestDict["pwd"].encode("utf-8")) requestDict["pwd"] = pwdMd5.hexdigest() UserService.updateUser(requestDict) except Exception as e: print(traceback.format_exc()) message = "编辑用户数据发生异常 %s" % e logger.info(message) return HttpResponse( ApiReturn(code=ApiReturn.CODE_WARNING, message=message).toJson()) return HttpResponse(ApiReturn().toJson())
from apps.common.func.CommonFunc import executeSqlGetDict, isInt from apps.common.model.RedisDBConfig import RedisCache serviceRedis = RedisCache() def getPythonThirdLib(): importStr = "" if not serviceRedis.existsKey("python_third_libs"): res = executeSqlGetDict( "select execPythonValue from tb_exec_python_attrs where execPythonAttr = 'importString' " ) if res: importStr = res[0]['execPythonValue'] serviceRedis.set_data("python_third_libs", importStr) print("INIT KEY[python_third_libs] to redis!!!") return serviceRedis.get_data("python_third_libs") def getKeywordExecPythonTimeout(key="timeoutString"): timeout = 10 currentKey = "python_timeout_%s" % key if not serviceRedis.existsKey(currentKey): res2 = executeSqlGetDict( "select execPythonValue from tb_exec_python_attrs where execPythonAttr = '%s' " % key) if res2: timeoutStr = res2[0]['execPythonValue'] if isInt(timeoutStr): timeout = int(timeoutStr) serviceRedis.set_data(currentKey, timeout)
def get_user_url_permissions(url,loginName,otherLoginNameList): userPermissionDict = {"permissions":{},"isSuccess":True} for otherLoginName in otherLoginNameList: userPermissionDict["permissions"][otherLoginName] = [] otherLoginNamePermission = userPermissionDict["permissions"][otherLoginName] #如果用户是超级管理员 则有所有权限 if len(TbAdminUser.objects.filter(loginName=loginName, state=1, superManager=1)) > 0: tmpPermissions = TbAdminInterfacePermissionRelation.objects.filter(url=url,state=1) for index in tmpPermissions: otherLoginNamePermission.append(index.permission) continue if otherLoginName == loginName or otherLoginName == "None" or otherLoginName == "" or otherLoginName == None: tmpPermissions = TbAdminInterfacePermissionRelation.objects.filter(url=url, state=1) for index in tmpPermissions: otherLoginNamePermission.append(index.permission) continue userPermissionResult,userPermission = UserPermissionService.get_user_default_permission(loginName) if userPermissionResult: userDefaultPermission = int(userPermission["defaultPermission"]) userOtherPermission = int(userPermission["otherPermission"]) else: userPermissionDict["permissions"][otherLoginName] = [] continue if userDefaultPermission == 1: tmpDefaultPermission = UserPermissionService.get_url_default_permissions(url) for index in tmpDefaultPermission: if index not in otherLoginNamePermission: otherLoginNamePermission.append(index) #查询用户是否有其他权限 if userOtherPermission == 1: allPermission = TbAdminInterfacePermissionRelation.objects.filter(state=1,url=url) for index in allPermission: if len(TbUserPermissionRelation.objects.filter(state=1,loginName=loginName,permissionKey=index.permissionKey)) > 0: otherLoginNamePermission.append(index.permission) #查我和此人同在哪些小组 loginNameTeamList = TbAdminUserTeamRelation.objects.filter(loginName=loginName,state=1) for teamIndex in loginNameTeamList: togetherTeam = TbAdminUserTeamRelation.objects.filter(loginName=otherLoginName,teamKey=teamIndex.teamKey,state=1) for togetherTeamIndex in togetherTeam: try: tmpTeamPermission = json.loads(RedisCache().get_data("%s_%s_%s" % (PermissionConst.team_url_permission,togetherTeamIndex.teamKey, url))) for tmpIndex in tmpTeamPermission: if tmpIndex not in otherLoginNamePermission: otherLoginNamePermission.append(tmpIndex) except: tmpTeamPermission = [] tmpTeamPermissionList = TbAdminTeamPermissionRelation.objects.filter(state=1,teamKey=togetherTeamIndex.teamKey) for tmpIndex in tmpTeamPermissionList: tmpPermission = TbAdminInterfacePermissionRelation.objects.filter(state=1,url=url,permissionKey=tmpIndex.permissionKey) for tmpPermissionIndex in tmpPermission: if tmpPermissionIndex.permission not in otherLoginNamePermission: otherLoginNamePermission.append(tmpPermissionIndex.permission) if tmpPermissionIndex.permission not in tmpTeamPermission: tmpTeamPermission.append(tmpPermissionIndex.permission) RedisCache().set_data("%s_%s_%s" % (PermissionConst.team_url_permission,togetherTeamIndex.teamKey, url),json.dumps(tmpTeamPermission)) return userPermissionDict
import os import sys rootpath = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))).replace("\\","/") print(rootpath) syspath=sys.path sys.path=[] sys.path.append(rootpath) #指定搜索路径绝对目录 sys.path.extend([rootpath+i for i in os.listdir(rootpath) if i[0]!="."])#将工程目录下的一级目录添加到python搜索路径中 sys.path.extend(syspath) from apps.common.model.RedisDBConfig import RedisCache if __name__ == "__main__": #清除python引用的所有缓存,下次加载重新刷新 RedisCache().del_data("python_mode_functions") RedisCache().del_data("python_third_libs") RedisCache().del_data("python_timeout_timeoutString") RedisCache().del_data("python_timeout_timoutForMockAdvancedMode") RedisCache().del_data("python_timeout_timoutForSelfKeyword") RedisCache().del_data("python_timeout_timoutForPythonMode")