def post(self, request): data = {'code': 0, 'data': '', 'msg': '成功'} user_id = request.POST.get('id', None) is_superuser = request.POST.get('is_superuser', None) is_active = request.POST.get('is_active', None) if user_id is None: data['code'] = 1 data['msg'] = 'id is not None' return JsonResponse(data=data) try: user_obj = DctUser.objects.get(id=user_id) except Exception as e: logs.error(e) data['code'] = 1 data['msg'] = '内部错误,请联系管理员!' return JsonResponse(data=data) if is_superuser is None and is_active is None: data['code'] = 1 data['msg'] = '参数错误' elif is_superuser: if is_superuser == 'true': user_obj.is_superuser = True elif is_superuser == 'false': user_obj.is_superuser = False user_obj.save() elif is_active: if is_active == 'true': user_obj.is_active = True elif is_active == 'false': user_obj.is_active = False user_obj.save() return JsonResponse(data=data)
def get_client(*args, **kwargs): global server_ip global db_index global unix_socket if args or kwargs: if (server_ip is not None and db_index is not None) or (unix_socket is not None): if (kwargs['host'] == server_ip and kwargs['db'] == db_index) \ or unix_socket == kwargs['unix_socket_path'] is not None: pass else: if kwargs['unix_socket_path'] is not None: unix_socket = kwargs['unix_socket_path'] elif kwargs['host'] is not None and kwargs['port'] is not None: server_ip = kwargs['host'] db_index = kwargs['db'] connect(*args, **kwargs) else: connect(*args, **kwargs) try: server_ip = kwargs['host'] db_index = kwargs['db'] unix_socket = kwargs['unix_socket_path'] except Exception as e: logs.error(e) global client if client: return client else: # connect(host='127.0.0.1', port=6379) connect(args, kwargs) return client
def check_redis_connect(name): redis_conf = get_redis_conf(name) if isinstance(redis_conf, list): try: conn = cluster_connect(conf=redis_conf) logs.debug('check redis connect: {0}'.format(redis_conf)) conn.ping() return True except Exception as e: logs.error(e) error = dict( redis=name, message=e, ) return error else: try: logs.debug("host:{0},port:{1},password:{2},timeout:{3}".format( redis_conf.host, redis_conf.port, redis_conf.password, socket_timeout)) conn = Connection(host=redis_conf.host, port=redis_conf.port, password=redis_conf.password, socket_timeout=socket_timeout) conn.connect() return True except Exception as e: logs.error(e) error = dict( redis=name, message=e, ) return error
def get(self, request, redis_name, value_db_id, key): from public.redis_api import get_cl from public.data_view import get_value logs.info('get value: redis_name={0}, db={1}, key={2}'.format( redis_name, value_db_id, key)) cl = get_cl(redis_name, int(value_db_id)) value_dict = {'code': 0, 'msg': '', 'data': ''} if cl.exists(key): value = '' if request.GET.get("type", None) == 'ttl': value = cl.ttl(key) if value is None: value = -1 logs.info( 'get key ttl: redis_name={0}, db={1}, key={2}, ttl={3}'. format(redis_name, value_db_id, key, value)) else: try: value = get_value(key, int(value_db_id), cl) except Exception as e: logs.error( 'get value is error: redis_name:{0}, key:{1}, db:{2}, cl:{3}, error_info:{4}' .format(redis_name, key, value_db_id, cl, e)) value_dict['code'] = 1 value_dict['data'] = value else: logs.warning( 'key is not exists: redis_name={0}, db={1}, key={2}'.format( redis_name, value_db_id, key)) value_dict['code'] = 1 return JsonResponse(value_dict, safe=False)
def check_connect(host, port, password=None, socket_timeout=socket_timeout): # from redis import Connection try: conn = Connection(host=host, port=port, password=password, socket_timeout=socket_timeout) conn.connect() return True except Exception as e: logs.error(e) return e
def authenticate(self, username=None, password=None, **kwargs): try: user = DctUser.objects.get( Q(username=username) | Q(email=username)) if user.check_password(password): return user except Exception as e: logs.error(e) return None
def get_redis_conf(name=None, user=None): if name is None and user is not None: return user.auths.all() else: try: return RedisConf.objects.get(name=name) except Exception as e: logs.error(e) return False
def post(self, request): redis_id = request.POST.get('id', None) data = {'code': 0, 'data': '', 'msg': '成功'} try: RedisConf.objects.get(id=redis_id).delete() except Exception as e: logs.error(e) data['code'] = 1 data['msg'] = '失败,请查看日志' return JsonResponse(data=data)
def post(self, request): data = {"code": 0, "msg": "successful", "data": ""} redis_name = request.POST.get("redis_name", None) db_id = request.POST.get("db_id", None) try: cl = get_cl(redis_name=redis_name, db_id=db_id) cl.flushdb() except Exception as e: logs.error(e) data["code"] = 1 data["msg"] = "failed" return JsonResponse(data=data, safe=False)
def get(self, request): #redis = RedisConf.objects.all() #return render(request, 'add_user.html', { # 'rediss': redis, #}) try: redis = RedisConf.objects.filter(type=0) cluster = get_all_cluster_redis() return render(request, 'add_user.html', { 'rediss': redis, 'clusters': cluster }) except Exception as e: logs.error(u"新增用户信息: msg:{0}".format(e)) return render(request, 'add_user.html', {'user_error': e})
def check_connect(host, port, password=None, unix_socket_path=None, socket_timeout=30): # from redis import Connection try: redisconn = redis.Redis(host=host, port=port, password=password, socket_timeout=socket_timeout) return redisconn.ping() except Exception as e: logs.error(e) return e
def post(self, request, redis_name, value_db_id, key): """ 修改TTL """ from public.redis_api import get_cl cl = get_cl(redis_name, int(value_db_id)) value_dict = {'code': 0, 'msg': '', 'data': ''} ttl = request.POST.get("ttl", None) if cl.exists(key) and ttl: try: cl.expire(key, ttl) value_dict['msg'] = "修改成功" except Exception as e: logs.error(e) value_dict['msg'] = '修改失败,请联系管理员' return JsonResponse(value_dict)
def on_connect(self): "Initialize the connection, authenticate and select a database" self._parser.on_connect(self) # if a password is specified, authenticate if self.password: self.send_command('AUTH', self.password) if nativestr(self.read_response()) != 'OK': logs.error("Invalid Password") raise AuthenticationError('Invalid Password') # if a database is specified, switch to it if self.db >= 0: # 密码为空,切换db判断是否需要认证 self.send_command('SELECT', self.db) if nativestr(self.read_response()) != 'OK': raise ConnectionError('Invalid Database')
def get(self, request): menu = Menu(user=request.user) id = request.GET.get('id', None) try: user = DctUser.objects.get(id=id) auth = get_redis_conf(name=None, user=user) redis = RedisConf.objects.all() return render(request, 'change_user.html', { 'menu': menu, 'user_info': user, 'auth': auth, 'rediss': redis, }) except Exception as e: logs.error(u"修改用户信息: id:{0},msg:{1}".format(id, e)) return render(request, 'change_user.html', {'error': e})
def get(self, request): id = request.GET.get('id', None) try: user = DctUser.objects.get(id=id) auth = get_redis_conf(name=None, user=user) redis = RedisConf.objects.filter(type=0) cluster = get_all_cluster_redis() return render( request, 'change_user.html', { 'user_info': user, 'auth': auth, 'rediss': redis, 'clusters': cluster }) except Exception as e: logs.error(u"修改用户信息: id:{0},msg:{1}".format(id, e)) return render(request, 'change_user.html', {'error': e})
def post(self, request): return JsonResponse({ "code": 1, "msg": "this operation not allow!", "data": "" }) data = {"code": 0, "msg": "successful", "data": ""} redis_name = request.POST.get("redis_name", None) db_id = request.POST.get("db_id", None) try: cl, cur_server_index, cur_db_index = get_cl(redis_name=redis_name, db_id=db_id) cl.flushdb() except Exception as e: logs.error(e) data["code"] = 1 data["msg"] = "failed" return JsonResponse(data=data, safe=False)
def send_email(subject, text=None, files=None, receivers=None, is_html=False): """ subject=邮件测试 files=[file1,file2] text=内容 mail=[[email protected],[email protected]] """ logs.debug("mail info: [user:{0},password:{1},host:{2},receivers:{3}]".format( mail_user, mail_pass, mail_host, receivers)) message = MIMEMultipart() if is_html: message.attach(MIMEText(text, 'html', 'utf-8')) else: message.attach(MIMEText(text, 'plain', 'utf-8')) message['Subject'] = subject message['From'] = Header(mail_user) message['To'] = ','.join(receivers) if files is not None: for filename in files: if filename != '': with open(filename, 'rb') as f: mime = MIMEBase('text', 'txt', filename=filename) mime.add_header('Content-Disposition', 'attachment', filename=filename.split('/')[-1]) mime.set_payload(f.read()) encoders.encode_base64(mime) message.attach(mime) try: smtpObj = smtplib.SMTP_SSL(timeout=5) smtpObj.connect(mail_host, 465) smtpObj.login(mail_user, mail_pass) smtpObj.sendmail(mail_user, receivers, message.as_string()) smtpObj.quit() smtpObj.close() return True except smtplib.SMTPException as e: smtpObj.quit() smtpObj.close() logs.error(e) return False
def get_redis_conf(name=None, user=None): if name is None and user is not None: return user.auths.all() else: try: return RedisConf.objects.get(name=name) except MultipleObjectsReturned: cluster_confs = RedisConf.objects.filter(name=name) cluster_conf_list = list() for cluster in cluster_confs: cluster_conf_dict = dict() cluster_conf_dict['id'] = cluster.id cluster_conf_dict['host'] = cluster.host cluster_conf_dict['port'] = cluster.port cluster_conf_dict['password'] = cluster.password cluster_conf_dict['name'] = cluster.name cluster_conf_list.append(cluster_conf_dict) del cluster_conf_dict return cluster_conf_list except Exception as e: logs.error(e) return False
def redis_conf_save(request): redis_id = request.POST.get("id", None) if redis_id is not None: try: redis_obj = RedisConf.objects.get(id=redis_id) redis_form = RedisForm(request.POST, instance=redis_obj) if redis_form.is_valid(): redis_form.save() return True return False except Exception as e: logs.error(e) return False else: name = request.POST.get('name', None) if RedisConf.objects.filter(name__iexact=name).count() == 0: redis_form = RedisForm(request.POST) if redis_form.is_valid(): redis_form.save() return True logs.error(redis_form.errors) return False
def post(self, request): data = dict( code=0, msg=u"登录成功,即将跳转...", data="", ) login_form = LoginForms(request.POST) nexts = request.get_full_path(force_append_slash=True) if login_form.is_valid(): user_name = request.POST.get("username", "") pass_word = request.POST.get("password", "") user = authenticate(username=user_name, password=pass_word) if user is not None: if user.is_active: login(request, user) servers = get_redis_conf(name=None, user=user) user_premission = dict() for ser in servers: try: redis_name = RedisConf.objects.get(id=ser.redis) user_premission[redis_name.name] = ser.pre_auth except Exception as e: logs.error(e) raise e data["data"] = user_premission data["menu"] = Menu(user=user) left_menu = [] for i in data['menu']: left_menu.append(i['name']) data['left_menu'] = left_menu return JsonResponse(data) else: data["code"] = 1 data["msg"] = u"用户未激活" return JsonResponse(data) data["code"] = 2 data["msg"] = u"用户名或密码错误" return JsonResponse(data)
def get(self, request, redis_name, value_db_id, key): from public.redis_api import get_cl from public.data_view import get_value cl, cur_server_index, cur_db_index = get_cl(redis_name, int(value_db_id)) value_dict = {'code': 0, 'msg': '', 'data': ''} if cl.exists(key): value = '' if request.GET.get("type", None) == 'ttl': value = cl.ttl(key) if value is None: value = -1 else: try: value = get_value(key, cur_server_index, cur_db_index, cl) except Exception as e: logs.error(e) value_dict['code'] = 1 value_dict['data'] = value else: value_dict['code'] = 1 return JsonResponse(value_dict, safe=False)
def post(self, request, redis_name, value_db_id): """ 修改TTL """ from public.redis_api import get_cl cl = get_cl(redis_name, int(value_db_id)) value_dict = {'code': 0, 'msg': '', 'data': ''} key = request.POST.get('key', None) ttl = request.POST.get("ttl", None) if cl.exists(key) and ttl != None: try: if long(ttl) < 0: cl.persist(key) else: cl.expire(key, ttl) logs.info( 'change key tll: redis_name={0}, db={1}, key={2}, ttl={3}'. format(redis_name, value_db_id, key, ttl)) value_dict['msg'] = "修改成功" except Exception as e: logs.error(e) value_dict['msg'] = '修改失败,请联系管理员' return JsonResponse(value_dict)
def check_redis_connect(name): redis_conf = get_redis_conf(name) try: logs.info( "host:{0},port:{1},password:{2},timeout:{3}, socket: {4}".format( redis_conf.host, redis_conf.port, redis_conf.password, socket_timeout, redis_conf.socket)) if redis_conf.socket is not None and redis_conf.socket != "": redisconn = redis.Redis(host=redis_conf.host, port=redis_conf.port, password=redis_conf.password, unix_socket_path=redis_conf.socket) else: redisconn = redis.Redis(host=redis_conf.host, port=redis_conf.port, password=redis_conf.password) return redisconn.ping() except Exception as e: logs.error(e) error = dict( redis=redis_conf, message=e, ) return error
def redis_conf_save(request): redis_id = request.POST.get("id", None) # 编辑 if redis_id is not None: try: redis_obj = RedisConf.objects.get(id=redis_id) redis_form = RedisForm(request.POST, instance=redis_obj) if redis_form.is_valid(): redis_form.save() return True return False except Exception as e: logs.error(e) return False # 添加 else: redis_form = RedisForm(request.POST) if not redis_form.is_valid(): logs.error(redis_form.errors) return False name = request.POST.get('name', None) redis_type = request.POST.get('type', None) # 单机redis添加 if redis_type is None or int(redis_type) == 0: if RedisConf.objects.filter(name__iexact=name).count() == 0: redis_form.save() return True else: logs.error('单机redis添加错误: 名称重复, data:{0}'.format(request.POST)) return False # cluster添加 elif int(redis_type) == 1: if RedisConf.objects.filter(Q(type=0) & Q(name__iexact=name)).count() == 0: redis_form.save() return True else: logs.error('cluster redis添加错误: 名称与单机重复, data:{0}'.format( request.POST)) return False return False
def get(self, request, redis_name, value_db_id): from public.redis_api import get_cl from public.data_view import get_value key = request.GET.get('key', None) logs.info('get value: redis_name={0}, db={1}, key={2}'.format( redis_name, value_db_id, key)) cl = get_cl(redis_name, int(value_db_id)) value_dict = {'code': 0, 'msg': '', 'data': ''} keyobj = None isCmd = False try: keyobj = json.loads(key) if keyobj.has_key('cmd'): isCmd = True except Exception as e: pass finally: pass if isCmd: cmdList = keyobj.get('cmd').split() cmdList[0] = cmdList[0].upper() logs.info('execute: cmd={0}'.format(" ".join(cmdList))) try: res = cl.execute_command(*cmdList) except Exception as e: res = str(e) logs.info('execute response={0}'.format(res)) if isinstance(res, basestring): res = res.replace("\r\n", "\n").strip("\n").split("\n") resinfo = { "db": int(value_db_id), "key": " ".join(cmdList), "value": json.dumps(res), "ttl": -1, "type": "string" } #{'$response':res} #{"encoding":"","db":0,"value":"aa","key":"a a","ttl":-1,"type":"string","size":2} value_dict['data'] = resinfo return JsonResponse(value_dict, safe=False) if cl.exists(key): value = {} if request.GET.get("type", None) == 'ttl': ttl = cl.ttl(key) if ttl is None: ttl = -1 logs.info( 'get key ttl: redis_name={0}, db={1}, key={2}, ttl={3}'. format(redis_name, value_db_id, key, ttl)) value = { "db": value_db_id, "key": key, "value": ttl, "ttl": ttl, "type": "long" } else: try: value = get_value(key, int(value_db_id), cl) except Exception as e: logs.error( 'get value is error: redis_name:{0}, key:{1}, db:{2}, cl:{3}, error_info:{4}' .format(redis_name, key, value_db_id, cl, e)) value_dict['code'] = 1 if value.has_key('value'): value['value'] = json.dumps(value.get('value')) value_dict['data'] = value else: logs.warning( 'key is not exists: redis_name={0}, db={1}, key={2}'.format( redis_name, value_db_id, key)) value_dict['code'] = 1 return JsonResponse(value_dict, safe=False)
def post(self, request): id = request.POST.get('id', None) password1 = request.POST.get('password1', None) password2 = request.POST.get('password2', None) email = request.POST.get('email', None) is_superuser = request.POST.get('is_superuser', None) rediss = list(RedisConf.objects.all()) redissimple = RedisConf.objects.filter(type=0) cluster = get_all_cluster_redis() name_list = [] redis_list = [] for i in rediss: if i.name not in name_list: name_list.append(i.name) redis_list.append(i) del name_list user = DctUser.objects.get(id=id) for re in redis_list: re_id = request.POST.get(re.name, None) # 判断是否获取到值 if re_id is None: continue # 值是否为空 elif re_id == '': try: # ''为删除权限 user.auths.get(redis=re.id).delete() except Exception as e: logs.error(u"删除权限失败:user_id:{0},redis:{1},msg:{2}".format( id, re.id, e)) continue pre_auth = int(re_id) # 权限数 # 用户所有权限 user_redis = [] for i in user.auths.all(): user_redis.append(i.redis) # 判断用户是否拥有该redis的权限,没有就创建,有及更新 if re.id not in user_redis: try: pre_obj = Auth.objects.get(redis=re.id, pre_auth=pre_auth) except Exception as e: pre_obj = Auth.objects.create(redis=re.id, pre_auth=pre_auth) user.auths.add(pre_obj) user.save() else: if user.auths.get(redis=re.id).pre_auth != pre_auth: try: pre_obj = Auth.objects.get(redis=re.id, pre_auth=pre_auth) except Exception as e: pre_obj = Auth.objects.create(redis=re.id, pre_auth=pre_auth) finally: user_pre = user.auths.remove( user.auths.get(redis=re.id)) user.auths.add(pre_obj) user.save() error = '' try: user = DctUser.objects.get(id=id) # 是否超级用户 if is_superuser is not None: user.is_staff = True user.is_superuser = True else: user.is_staff = False user.is_superuser = False # 修改密码 if password1 and password2: if password1 == password2: user.set_password(password1) else: error = '密码不一致' user.email = email user.save() except Exception as e: error = e auth = get_redis_conf(name=None, user=user) return render( request, 'change_user.html', { 'user_info': user, 'rediss': redissimple, 'clusters': cluster, 'auth': auth, 'error': error })