How to use smart_get method in autotest

Best Python code snippet using autotest_python

views.py

Source:views.py Github

copy

Full Screen

...35 初始化网段36 """37 msg_prefix = u"初始化网段 "38 req_dict = post_data_to_dict(request.data)39 network = smart_get(req_dict, 'network', str)40 try:41 # 初始化网段42 build_init_net(net=network)43 except Exception, e:44 msg = msg_prefix + u"失败, 错误信息: " + unicode(e)45 logger.error(format_exc())46 return Response({"status": -1, "msg": msg, "data": {}}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)47 else:48 msg = msg_prefix + u"成功!"49 return Response({"status": 1, "msg": msg, "data": {}})50 @action(detail=False, methods=['post'], url_path='recommend-ip')51 def recommend_ip(self, request, *args, **kwargs):52 """53 推荐可用ip54 """55 msg_prefix = u"推荐ip "56 req_dict = post_data_to_dict(request.data)57 network = smart_get(req_dict, 'network', str)58 try:59 if not network:60 raise Exception(u"请输入网段")61 build_init_net(network)62 avaliable_ipaddr = avaliable_ip(network)63 ping_status = ping(host=avaliable_ipaddr)64 if ping_status:65 avaliable_ipaddr = None66 unlock_ip.delay(avaliable_ipaddr, time.time(), 1 * 30) # 锁定30秒67 except Exception, e:68 msg = msg_prefix + u"失败, 错误信息: " + unicode(e)69 logger.error(format_exc())70 return Response({"status": -1, "msg": msg, "data": {}}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)71 else:72 msg = msg_prefix + u"成功!"73 return Response({"status": 1, "msg": msg, "data": {"avaliable_ipaddr": avaliable_ipaddr}})74class IPUsageViewSet(ModelViewSet):75 """76 ip池操作77 """78 queryset = IPUsage.objects.all()79 serializer_class = IPUsageSerializer80@api_view(['POST'])81# @permission_classes((require_menu(["I00301"]),))82@post_validated_fields(require=['param_id', 'matching_param_value_id', 'param_matching_pattern'])83def get_params_http(request):84 """85 参数推荐86 - 获取参数推荐列表(vc, network, template ...)87 *参数88 ** param_id, 查询参数id, str89 ** matching_param, 匹配项, str90 ** param_matching_pattern, 匹配条件, str91 *返回值92 ** resp, 返回的请求数据, json93 """94 msg_prefix = u"获取参数推荐列表 "95 token = request.META.get('HTTP_AUTHORIZATION')96 try:97 resp = http_get_params(data=request.data, token=token)98 except Exception, e:99 msg = msg_prefix + u"失败, 错误信息: " + unicode(e)100 logger.error(format_exc())101 response = Response({"status": -1, "msg": msg, "data": {}}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)102 return response103 else:104 msg = msg_prefix + u"成功!"105 return Response({"status": 1, "msg": msg, "data": resp})106@api_view(['POST'])107# @permission_classes((require_menu(["I00301"]),))108@post_validated_fields(require=['vc_ip', 'vc_user', 'vc_passwd'])109def get_datacenter(request):110 """111 & 数据中心112 - 获取数据中心列表113 *参数114 ** vc_ip, vcenter ip, str115 ** vc_user, vcenter用户名, str116 ** vc_passwd, vcenter用户密码, str117 ** detail, 是否显示详细信息, bool118 *返回值119 ***datacenter_moid, 数据中心moid列表, str120 """121 msg_prefix = u"获取数据中心列表 "122 req_dict = post_data_to_dict(request.data)123 vc_ip = smart_get(req_dict, 'vc_ip', str)124 vc_user = smart_get(req_dict, 'vc_user', str)125 vc_port = smart_get(req_dict, 'vc_port', int, 443)126 vc_passwd = smart_get(req_dict, 'vc_passwd', str)127 detail = smart_get(req_dict, 'detail', bool, True)128 try:129 vim_api = VimTasks(vc_ip, vc_port, vc_user, vc_passwd)130 datacenter = vim_api.all_datacenter()131 serializer = DatacenterSerializer(datacenter, detail=detail)132 except Exception, e:133 msg = msg_prefix + u"失败, 错误信息: " + unicode(e)134 logger.error(format_exc())135 response = Response({"status": -1, "msg": msg, "data": {}}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)136 return response137 else:138 msg = msg_prefix + u"成功!"139 return Response({"status": 1, "msg": msg, "data": serializer.data})140@api_view(['POST'])141# @permission_classes((require_menu(["I00301"]),))142@post_validated_fields(require=['vc_ip', 'vc_user', 'vc_passwd', 'datacenter_name'])143def get_cluster(request):144 """145 & 数据中心所有集群146 - 获取数据中心集群列表147 *参数148 ** vc_ip, vcenter ip, str149 ** vc_user, vcenter用户名, str150 ** vc_passwd, vcenter用户密码, str151 ** datacenter_name, 数据中心名, str152 ** detail, 显示详细信息, bool153 *返回值154 *** cluster, 集群列表, list155 """156 msg_prefix = u"获取集群列表 "157 req_dict = post_data_to_dict(request.data)158 vc_ip = smart_get(req_dict, 'vc_ip', str)159 vc_user = smart_get(req_dict, 'vc_user', str)160 vc_port = smart_get(req_dict, 'vc_port', int, 443)161 vc_passwd = smart_get(req_dict, 'vc_passwd', str)162 datacenter_name = smart_get(req_dict, 'datacenter_name', str)163 detail = smart_get(req_dict, 'detail', bool, False)164 try:165 data = list()166 vim_api = VimTasks(vc_ip, vc_port, vc_user, vc_passwd)167 datacenter = vim_api.get_obj(name=datacenter_name)168 if datacenter:169 clusters = vim_api.cluster_of_datacenter(datacenter)170 serializer = ClusterSerializer(clusters, detail=detail)171 data = serializer.data172 except Exception, e:173 msg = msg_prefix + u"失败, 错误信息: " + unicode(e)174 logger.error(format_exc())175 return Response({"status": -1, "msg": msg, "data": {}}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)176 else:177 msg = msg_prefix + u"成功!"178 return Response({"status": 1, "msg": msg, "data": data})179@api_view(['POST'])180# @permission_classes((require_menu(["I00301"]),))181@post_validated_fields(require=['vc_ip', 'vc_user', 'vc_passwd', 'cluster_name'])182def get_cluster_hosts(request):183 """184 & 集群中主机185 - 获取集群中主机列表186 *参数187 ** vc_ip, vcenter ip, str188 ** vc_user, vcenter用户名, str189 ** vc_passwd, vcenter用户密码, str190 ** cluster_name, 集群名, str191 ** detail, 显示详细信息, bool192 """193 msg_prefix = u"获取集群主机列表 "194 req_dict = post_data_to_dict(request.data)195 vc_ip = smart_get(req_dict, 'vc_ip', str)196 vc_user = smart_get(req_dict, 'vc_user', str)197 vc_port = smart_get(req_dict, 'vc_port', int, 443)198 vc_passwd = smart_get(req_dict, 'vc_passwd', str)199 cluster_name = smart_get(req_dict, 'cluster_name', str)200 detail = smart_get(req_dict, 'detail', bool, False)201 try:202 data = list()203 vim_api = VimTasks(vc_ip, vc_port, vc_user, vc_passwd)204 cluster = vim_api.get_obj(name=cluster_name)205 if cluster:206 hostsystems = vim_api.host_of_cluster(cluster)207 serializer = HostSystemSerializer(hostsystems, detail=detail)208 data = serializer.data209 except Exception, e:210 msg = msg_prefix + u"失败, 错误信息: " + unicode(e)211 logger.error(format_exc())212 return Response({"status": -1, "msg": msg, "data": {}}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)213 else:214 msg = msg_prefix + u"成功!"215 return Response({"status": 1, "msg": msg, "data": data})216@api_view(['POST'])217# @permission_classes((require_menu(["I00301"]),))218@post_validated_fields(require=['vc_ip', 'vc_user', 'vc_passwd', 'hostsystem_name'])219def get_host_network(request):220 """221 获取主机网络列表(匹配环境)222 *参数223 ** vc_ip, vcenter ip, str224 ** vc_user, vcenter用户名, str225 ** vc_passwd, vcenter用户密码, str226 ** hostsystem_name, 主机名, str227 ** detail, 显示详细信息, bool228 """229 msg_prefix = u"获取主机网络列表 "230 req_dict = post_data_to_dict(request.data)231 vc_ip = smart_get(req_dict, 'vc_ip', str)232 vc_user = smart_get(req_dict, 'vc_user', str)233 vc_port = smart_get(req_dict, 'vc_port', int, 443)234 vc_passwd = smart_get(req_dict, 'vc_passwd', str)235 hostsystem_name = smart_get(req_dict, 'hostsystem_name', str)236 detail = smart_get(req_dict, 'detail', bool, False)237 try:238 data = list()239 vim_api = VimTasks(vc_ip, vc_port, vc_user, vc_passwd)240 hostsystem = vim_api.get_obj(name=hostsystem_name)241 if hostsystem:242 networks = vim_api.network_of_host(hostsystem)243 serializer = NetworkSerializer(networks, detail=detail)244 data = serializer.data245 except Exception, e:246 msg = msg_prefix + u"失败, 错误信息: " + unicode(e)247 logger.error(format_exc())248 return Response({"status": -1, "msg": msg, "data": {}}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)249 else:250 msg = msg_prefix + u"成功!"251 return Response({"status": 1, "msg": msg, "data": data})252@api_view(['POST'])253# @permission_classes((require_menu(["I00301"]),))254@post_validated_fields(require=['vc_ip', 'vc_user', 'vc_passwd', 'hostsystem_name'])255def get_host_datastore(request):256 """257 获取主机存储列表258 *参数259 ** vc_ip, vcenter ip, str260 ** vc_user, vcenter用户名, str261 ** vc_passwd, vcenter用户密码, str262 ** hostsystem_name, 主机名, str263 ** detail, 显示详细信息, bool264 """265 msg_prefix = u"获取主机存储列表 "266 req_dict = post_data_to_dict(request.data)267 vc_ip = smart_get(req_dict, 'vc_ip', str)268 vc_user = smart_get(req_dict, 'vc_user', str)269 vc_port = smart_get(req_dict, 'vc_port', int, 443)270 vc_passwd = smart_get(req_dict, 'vc_passwd', str)271 hostsystem_name = smart_get(req_dict, 'hostsystem_name', str)272 detail = smart_get(req_dict, 'detail', bool, False)273 try:274 data = list()275 vim_api = VimTasks(vc_ip, vc_port, vc_user, vc_passwd)276 hostsystem = vim_api.get_obj(name=hostsystem_name)277 if hostsystem:278 datastores = vim_api.datastore_of_host(hostsystem)279 serializer = DataStoreSerializer(datastores, detail=detail)280 data = serializer.data281 except Exception, e:282 msg = msg_prefix + u"失败, 错误信息: " + unicode(e)283 logger.error(format_exc())284 return Response({"status": -1, "msg": msg, "data": {}}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)285 else:286 msg = msg_prefix + u"成功!"287 return Response({"status": 1, "msg": msg, "data": data})288@api_view(['POST'])289# @permission_classes((require_menu(["I00301"]),))290@post_validated_fields(require=['vc_ip', 'vc_user', 'vc_passwd'])291def get_templates(request):292 """293 获取数据中心模板列表294 *参数295 ** vc_ip, vcenter ip, str296 ** vc_user, vcenter用户名, str297 ** vc_passwd, vcenter用户密码, str298 ** detail, 是否显示详细信息, bool299 """300 msg_prefix = u"获取数据中心模板列表 "301 req_dict = post_data_to_dict(request.data)302 vc_ip = smart_get(req_dict, 'vc_ip', str)303 vc_user = smart_get(req_dict, 'vc_user', str)304 vc_port = smart_get(req_dict, 'vc_port', int, 443)305 vc_passwd = smart_get(req_dict, 'vc_passwd', str)306 detail = smart_get(req_dict, 'detail', bool, True)307 try:308 vim_api = VimTasks(vc_ip, vc_port, vc_user, vc_passwd)309 templates = vim_api.get_template()310 serializer = VirtualMachineSerializer(templates, detail=detail)311 except Exception, e:312 msg = msg_prefix + u"失败, 错误信息: " + unicode(e)313 logger.error(format_exc())314 return Response({"status": -1, "msg": msg, "data": {}}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)315 else:316 msg = msg_prefix + u"成功!"317 return Response({"status": 1, "msg": msg, "data": serializer.data})318@api_view(['POST'])319# @permission_classes((require_menu(["I00301"]),))320@post_validated_fields(require=['network'])321def network_recommend(request):322 """323 获取推荐网络信息324 *参数325 ** network, 网段, str326 ** exist_vm_ip, 已推荐的ip, list327 """328 msg_prefix = u"获取推荐网络信息 "329 req_dict = post_data_to_dict(request.data)330 network = smart_get(req_dict, 'network', str)331 try:332 token = request.META.get('HTTP_AUTHORIZATION')333 is_network = network.find('/')334 if is_network == -1:335 raise Exception(u"请检查网络格式")336 # 默认网关337 ip_network = ipaddress.ip_network(unicode(network))338 ip_addrs = [str(i) for i in list(ip_network.hosts())]339 default_gateway = ip_addrs[-1]340 # 掩码341 hostmask = ip_network.netmask.exploded342 # avaliable_ipaddr343 avaliable_ipaddr = get_avaliable_ip(network, token)344 data = dict(345 gateway=default_gateway,346 hostmask=hostmask,347 ipaddress=avaliable_ipaddr348 )349 except Exception, e:350 msg = msg_prefix + u"失败, 错误信息: " + unicode(e)351 logger.error(format_exc())352 return Response({"status": -1, "msg": msg, "data": {}}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)353 else:354 msg = msg_prefix + u"成功!"355 return Response({"status": 1, "msg": msg, "data": data})356@api_view(['POST'])357# @permission_classes((require_menu(["I00301"]),))358@post_validated_fields(require=['ipaddress'])359def ping_ip(request):360 """361 & ip是否能ping通362 * 参数363 ** ipaddr, ip地址, str364 * 返回值365 *** state, 状态, bool366 """367 msg_prefix = u"ip 连接测试 "368 req_dict = post_data_to_dict(request.data)369 ipaddress = req_dict.pop('ipaddress')370 try:371 state = ping(host=ipaddress)372 data = dict(373 state=state374 )375 except Exception, e:376 msg = msg_prefix + u"失败, 错误信息: " + unicode(e)377 logger.error(format_exc())378 return Response({"status": -1, "msg": msg, "data": {}},379 status=status.HTTP_500_INTERNAL_SERVER_ERROR)380 else:381 msg = msg_prefix + u"成功!"382 return Response(383 {"status": 0, "msg": msg, "data": data})384@api_view(['POST'])385# @permission_classes((require_menu(["I00301"]),))386@post_validated_fields(387 require=['vc_ip', 'vc_user', 'vc_passwd', 'net', 'env_type', 'unit', 'application', 'node_type'])388def vc_resource_recommend(request):389 """390 & vmware资源供应参数推荐391 - 获取vmware虚拟机申请推荐参数392 * 参数393 ** vc_ip, vcenter ip, str394 ** vc_user, vcenter用户名, str395 ** vc_passwd, vcenter用户密码, str396 ** vc_port, vcenter连接端口, int397 ** env_type, 环境类型, str398 ** net, 虚拟机网段, str399 ** unit, 所属单位, str400 ** application, 应用程序, str401 ** node_type, 节点类型, str402 ** exist_names, 虚拟机名称缓存, str403 * 返回值404 *** datacenter_name, 数据中心名, str405 *** network_name, 网络名, str406 *** cluster_name, 集群名, str407 *** hostsystem_name, 虚主机名, str408 *** datastore_name, 存储名, str409 *** vm_name, 虚拟机名, str410 """411 msg_prefix = u"vmware资源供应参数推荐 "412 req_dict = post_data_to_dict(request.data)413 vc_ip = smart_get(req_dict, 'vc_ip', str)414 vc_user = smart_get(req_dict, 'vc_user', str)415 vc_port = smart_get(req_dict, 'vc_port', int, 443)416 vc_passwd = smart_get(req_dict, 'vc_passwd', str)417 env_type = smart_get(req_dict, 'env_type', str)418 net = smart_get(req_dict, 'net', str)419 unit = smart_get(req_dict, 'unit', str)420 application = smart_get(req_dict, 'application', str)421 node_type = smart_get(req_dict, 'node_type', str)422 exist_names = smart_get(req_dict, 'exist_names', list)423 try:424 token = request.META.get('HTTP_AUTHORIZATION')425 calc_server = CalcServer(vc_ip=vc_ip, vc_user=vc_user, vc_passwd=vc_passwd, vc_port=vc_port)426 result = calc_server.vmware_resource_recommend(net)427 vc_info_list = vc_info(token=token)428 vm_name_list = list()429 for vc in vc_info_list:430 vim_api = VimBase(vc['vc_ip'], 443, vc['vc_user'], vc['vc_passwd'])431 virtualmachines = vim_api.get_virtualmachines()432 for vm in virtualmachines:433 vm_name_list.append(vm.name)434 default_name = default_vm_name(env_type, unit, application, node_type, exist_names, vm_name_list)435 result.update(vm_name=default_name)436 except Exception, e:437 msg = msg_prefix + u"失败, 错误信息: " + unicode(e)438 logger.error(format_exc())439 return Response({"status": -1, "msg": msg, "data": {}}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)440 else:441 msg = msg_prefix + u"成功!"442 return Response({"status": 1, "msg": msg, "data": result})443@api_view(['POST'])444# @permission_classes((require_menu(["I00301"]),))445@post_validated_fields(require=['vc_ip', 'vc_user', 'vc_passwd', 'vm_name', 'vm_ip', 'datastore_name', 'cluster_name',446 'datacenter_name', 'template_name', 'hostsystem_name', 'network'])447def prod_virtual_machine(request):448 """449 & 生成虚拟机450 - 生成虚拟机451 * 参数452 ** vc_ip, vcenter ip, str453 ** vc_user, vcenter用户名, str454 ** vc_passwd, vcenter用户密码, str455 ** vm_name, 虚拟机名, str456 ** vm_ip, 虚拟机ip, str457 ** datastore_name, 虚拟机存储名, str458 ** cluster_name, 虚拟机所属集群名, str459 ** datacenter_name, 虚拟机所属数据中心名, str460 ** template_name, 虚拟机所用模板名, str461 ** hostsystem_name, 虚拟机所属主机名, str462 ** gateway, 网关, str463 ** subnetMask, 掩码, str464 ** dns, dns, str465 ** apply_user, 负责人, str466 ** node_type, 节点类型, str467 ** application, 应用名称, str468 ** env_type, 环境类型, str469 ** expiration, 过期时间, str470 ** network, 虚拟机网络, str471 ** target_cpu_cores, cpu核心, int472 ** target_mem_gb, 内存大小, int473 ** add_datadisk_gb, 新增硬盘大小, int474 * 返回值475 *** status, success/error, str476 """477 msg_prefix = "克隆虚拟机 "478 req_dict = post_data_to_dict(request.data)479 vc_ip = smart_get(req_dict, 'vc_ip', str)480 vc_user = smart_get(req_dict, 'vc_user', str)481 vc_port = smart_get(req_dict, 'vc_port', int, 443)482 vc_passwd = smart_get(req_dict, 'vc_passwd', str)483 vm_name = smart_get(req_dict, 'vm_name', str)484 vm_ip = smart_get(req_dict, 'vm_ip', str)485 datastore_name = smart_get(req_dict, 'datastore_name', str)486 cluster_name = smart_get(req_dict, 'cluster_name', str)487 datacenter_name = smart_get(req_dict, 'datacenter_name', str)488 template_name = smart_get(req_dict, 'template_name', str)489 hostsystem_name = smart_get(req_dict, 'hostsystem_name', str)490 gateway = smart_get(req_dict, 'gateway', str)491 subnetMask = smart_get(req_dict, 'subnetMask', str)492 dns = smart_get(req_dict, 'dns', str)493 network = smart_get(req_dict, 'network', str)494 target_cpu_cores = smart_get(req_dict, 'target_cpu_cores', int)495 target_mem_gb = smart_get(req_dict, 'target_mem_gb', int)496 add_datadisk_gb = smart_get(req_dict, 'add_datadisk_gb', int)497 node_type = smart_get(req_dict, 'node_type', str)498 apply_user = smart_get(req_dict, 'apply_user', str)499 env_type = smart_get(req_dict, 'env_type', str)500 expiration = smart_get(req_dict, 'expiration', str)501 application = smart_get(req_dict, 'application', str)502 try:503 if dns:504 dns = dns.split(',')505 kwargs = dict(506 vm_name=vm_name,507 vm_ip=vm_ip,508 datastore_name=datastore_name,509 cluster_name=cluster_name,510 datacenter_name=datacenter_name,511 template_name=template_name,512 hostsystem_name=hostsystem_name,513 gateway=gateway,514 subnetMask=subnetMask,515 dns=dns,516 node_type=node_type,517 apply_user=apply_user,518 env_type=env_type,519 expiration=expiration,520 application=application,521 network=network,522 target_cpu_cores=target_cpu_cores,523 target_mem_gb=target_mem_gb,524 add_datadisk_gb=add_datadisk_gb,525 )526 vim_api = VimTasks(vc_ip, vc_port, vc_user, vc_passwd)527 result = vim_api.prod_vm(**kwargs)528 except Exception, e:529 msg = msg_prefix + u"失败, 错误信息: " + unicode(e)530 logger.error(format_exc())531 return Response({"status": -1, "msg": msg, "data": {}}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)532 else:533 msg = msg_prefix + u"成功!"534 response = Response({"status": 1, "msg": msg, "data": result})535 return response536@api_view(['POST'])537# @permission_classes((require_menu(["I00301"]),))538@post_validated_fields(require=['vc_ip', 'vc_user', 'vc_passwd', 'vm_name', 'vm_ip', 'datastore_name', 'cluster_name',539 'datacenter_name', 'template_name', 'hostsystem_name'])540def clone_virtual_machine(request):541 """542 & 克隆虚拟机543 - 克隆虚拟机544 * 参数545 ** vc_ip, vcenter ip, str546 ** vc_user, vcenter用户名, str547 ** vc_passwd, vcenter用户密码, str548 ** vm_name, 虚拟机名, str549 ** vm_ip, 虚拟机ip, str550 ** datastore_name, 虚拟机存储名, str551 ** cluster_name, 虚拟机所属集群名, str552 ** datacenter_name, 虚拟机所属数据中心名, str553 ** template_name, 虚拟机所用模板名, str554 ** hostsystem_name, 虚拟机所属主机名, str555 ** gateway, 网关, str556 ** subnetMask, 掩码, str557 ** dns, dns, str558 * 返回值559 *** status, success/error, str560 """561 msg_prefix = "克隆虚拟机 "562 req_dict = post_data_to_dict(request.data)563 vc_ip = smart_get(req_dict, 'vc_ip', str)564 vc_user = smart_get(req_dict, 'vc_user', str)565 vc_port = smart_get(req_dict, 'vc_port', int, 443)566 vc_passwd = smart_get(req_dict, 'vc_passwd', str)567 vm_name = smart_get(req_dict, 'vm_name', str)568 vm_ip = smart_get(req_dict, 'vm_ip', str)569 datastore_name = smart_get(req_dict, 'datastore_name', str)570 cluster_name = smart_get(req_dict, 'cluster_name', str)571 datacenter_name = smart_get(req_dict, 'datacenter_name', str)572 template_name = smart_get(req_dict, 'template_name', str)573 hostsystem_name = smart_get(req_dict, 'hostsystem_name', str)574 gateway = smart_get(req_dict, 'gateway', str)575 subnetMask = smart_get(req_dict, 'subnetMask', str)576 dns = smart_get(req_dict, 'dns', str)577 print '-' * 40 + "clone" + '-' * 40578 print req_dict579 print '-' * 100580 try:581 kwargs = dict(582 vm_name=vm_name,583 vm_ip=vm_ip,584 datastore_name=datastore_name,585 cluster_name=cluster_name,586 datacenter_name=datacenter_name,587 template_name=template_name,588 hostsystem_name=hostsystem_name,589 gateway=gateway,590 subnetMask=subnetMask,591 dns=dns,592 )593 vim_api = VimTasks(vc_ip, vc_port, vc_user, vc_passwd)594 result = vim_api.clone_vm(**kwargs)595 data = dict(596 status=result597 )598 except Exception, e:599 msg = msg_prefix + u"失败, 错误信息: " + unicode(e)600 logger.error(format_exc())601 return Response({"status": -1, "msg": msg, "data": {}}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)602 else:603 msg = msg_prefix + u"成功!"604 response = Response({"status": 1, "msg": msg, "data": data})605 return response606@api_view(['POST'])607# @permission_classes((require_menu(["I00301"]),))608@post_validated_fields(require=['vc_ip', 'vc_user', 'vc_passwd', 'vm_name'])609def reconfigure_virtual_machine(request):610 """611 & 配置虚拟机612 - 配置虚拟机613 * 参数614 ** vc_ip, vcenter ip, str615 ** vc_user, vcenter用户名, str616 ** vc_passwd, vcenter用户密码, str617 ** vm_name, 虚拟机名, str618 ** network, 虚拟机网络, str619 ** apply_user, 负责人, str620 ** node_type, 节点类型, str621 ** application, 应用名称, str622 ** env_type, 环境类型, str623 ** expiration, 过期时间, str624 ** target_cpu_cores, cpu核心, int625 ** target_mem_gb, 内存大小, int626 ** add_datadisk_gb, 新增硬盘大小, int627 * 返回值628 *** status, success/error, str629 """630 msg_prefix = "配置虚拟机 "631 req_dict = post_data_to_dict(request.data)632 print '-' * 40 + "reconfigure" + '-' * 40633 print req_dict634 print '-' * 100635 vc_ip = smart_get(req_dict, 'vc_ip', str)636 vc_user = smart_get(req_dict, 'vc_user', str)637 vc_port = smart_get(req_dict, 'vc_port', int, 443)638 vc_passwd = smart_get(req_dict, 'vc_passwd', str)639 vm_name = smart_get(req_dict, 'vm_name', str)640 network = smart_get(req_dict, 'network', str)641 target_cpu_cores = smart_get(req_dict, 'target_cpu_cores', int)642 target_mem_gb = smart_get(req_dict, 'target_mem_gb', int)643 add_datadisk_gb = smart_get(req_dict, 'add_datadisk_gb', int)644 node_type = smart_get(req_dict, 'node_type', str, '')645 apply_user = smart_get(req_dict, 'apply_user', str, '')646 env_type = smart_get(req_dict, 'env_type', str, '')647 expiration = smart_get(req_dict, 'expiration', str, '')648 application = smart_get(req_dict, 'application', str, '')649 kwargs = dict(650 vm_name=vm_name,651 network=network,652 target_cpu_cores=target_cpu_cores,653 target_mem_gb=target_mem_gb,654 add_datadisk_gb=add_datadisk_gb,655 node_type=node_type,656 apply_user=apply_user,657 env_type=env_type,658 expiration=expiration,659 application=application,660 )661 try:662 vim_api = VimTasks(vc_ip, vc_port, vc_user, vc_passwd)663 result = vim_api.reconfig_vm(**kwargs)664 data = dict(665 status=result666 )667 except Exception, e:668 msg = msg_prefix + u"失败, 错误信息: " + unicode(e)669 logger.error(format_exc())670 return Response({"status": -1, "msg": msg, "data": {}}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)671 else:672 msg = msg_prefix + u"成功!"673 response = Response({"status": 1, "msg": msg, "data": data})674 return response675@api_view(['POST'])676# @permission_classes((require_menu(["I00301"]),))677@post_validated_fields(require=['vc_ip', 'vc_user', 'vc_passwd', 'vm_name'])678def poweron_virtual_machine(request):679 """680 & 开机681 - 开机682 * 参数683 ** vc_ip, vcenter ip, str684 ** vc_user, vcenter用户名, str685 ** vc_passwd, vcenter用户密码, str686 ** vm_name, 虚拟机名, str687 * 返回值688 *** status, success/error, str689 """690 msg_prefix = "开机 "691 req_dict = post_data_to_dict(request.data)692 vc_ip = smart_get(req_dict, 'vc_ip', str)693 vc_user = smart_get(req_dict, 'vc_user', str)694 vc_port = smart_get(req_dict, 'vc_port', int, 443)695 vc_passwd = smart_get(req_dict, 'vc_passwd', str)696 vm_name = smart_get(req_dict, 'vm_name', str)697 print '-' * 40 + "poweron" + '-' * 40698 print req_dict699 print '-' * 100700 try:701 vim_api = VimTasks(vc_ip, vc_port, vc_user, vc_passwd)702 result = vim_api.poweron_vm(vm_name=vm_name)703 data = dict(704 status=result705 )706 except Exception, e:707 msg = msg_prefix + u"失败, 错误信息: " + unicode(e)708 logger.error(format_exc())709 return Response({"status": -1, "msg": msg, "data": {}}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)710 else:711 msg = msg_prefix + u"成功!"712 response = Response({"status": 1, "msg": msg, "data": data})713 return response714@api_view(['POST'])715# @permission_classes((require_menu(["I00301"]),))716@post_validated_fields(require=['vc_ip', 'vc_user', 'vc_passwd', 'vm_name'])717def poweroff_virtual_machine(request):718 """719 & 关机720 - 关机721 * 参数722 ** vc_ip, vcenter ip, str723 ** vc_user, vcenter用户名, str724 ** vc_passwd, vcenter用户密码, str725 ** vm_name, 虚拟机名, str726 * 返回值727 *** status, success/error, str728 """729 msg_prefix = "关机 "730 req_dict = post_data_to_dict(request.data)731 vc_ip = smart_get(req_dict, 'vc_ip', str)732 vc_user = smart_get(req_dict, 'vc_user', str)733 vc_port = smart_get(req_dict, 'vc_port', int, 443)734 vc_passwd = smart_get(req_dict, 'vc_passwd', str)735 vm_name = smart_get(req_dict, 'vm_name', str)736 try:737 vim_api = VimTasks(vc_ip, vc_port, vc_user, vc_passwd)738 result = vim_api.poweroff_vm(vm_name=vm_name)739 data = dict(740 status=result741 )742 except Exception, e:743 msg = msg_prefix + u"失败, 错误信息: " + unicode(e)744 logger.error(format_exc())745 return Response({"status": -1, "msg": msg, "data": {}}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)746 else:747 msg = msg_prefix + u"成功!"748 response = Response({"status": 1, "msg": msg, "data": data})749 return response750@api_view(['POST'])751# @permission_classes((require_menu(["I00301"]),))752@post_validated_fields(require=['vc_ip', 'vc_user', 'vc_passwd', 'vm_name'])753def destroy_virtual_machine(request):754 """755 & 删除虚拟机756 - 删除虚拟机757 * 参数758 ** vc_ip, vcenter ip, str759 ** vc_user, vcenter用户名, str760 ** vc_passwd, vcenter用户密码, str761 ** vm_name, 虚拟机名, str762 * 返回763 *** status, success/error, str764 """765 msg_prefix = u"删除虚拟机 "766 req_dict = post_data_to_dict(request.data)767 vc_ip = smart_get(req_dict, 'vc_ip', str)768 vc_user = smart_get(req_dict, 'vc_user', str)769 vc_port = smart_get(req_dict, 'vc_port', int, 443)770 vc_passwd = smart_get(req_dict, 'vc_passwd', str)771 vm_name = smart_get(req_dict, 'vm_name', str)772 try:773 vim_api = VimTasks(vc_ip, vc_port, vc_user, vc_passwd)774 result = vim_api.destroy_vm(vm_name=vm_name)775 data = dict(776 status=result777 )778 except Exception, e:779 msg = msg_prefix + u"失败, 错误信息: " + unicode(e)780 logger.error(format_exc())781 return Response({"status": -1, "msg": msg, "data": {}},782 status=status.HTTP_500_INTERNAL_SERVER_ERROR)783 else:784 msg = msg_prefix + u"成功!"785 return Response({"status": 0, "msg": msg, "data": data})786#787# @api_view(['POST'])788# # @permission_classes((require_menu(["I00301"]),))789# @post_validated_fields(require=['vc_ip', 'vc_user', 'vc_passwd', 'vm_name'])790# def search(request):791# """792# - 搜索虚拟机793# * 参数794# ** vc_ip, vcenter ip, str795# ** vc_user, vcenter用户名, str796# ** vc_passwd, vcenter用户密码, str797# ** vm_name, 虚拟机名, str798# * 返回799# *** status, success/error, str800# """801# msg_prefix = u"搜索虚拟机 "802# req_dict = post_data_to_dict(request.data)803# vc_ip = smart_get(req_dict, 'vc_ip', str)804# vc_user = smart_get(req_dict, 'vc_user', str)805# vc_port = smart_get(req_dict, 'vc_port', int, 443)806# vc_passwd = smart_get(req_dict, 'vc_passwd', str)807# vm_name = smart_get(req_dict, 'vm_name', str)808# try:809# if not vm_name:810# raise Exception(u"请填写虚拟机名")811# vm_name_list = list()812# result = False813# vim_api = VimTasks(vc_ip, vc_port, vc_user, vc_passwd)814# vm_list = vim_api.get_virtualmachines()815# for vm in vm_list:816# vm_name_list.append(vm.name)817# if vm_name in vm_name_list:818# result = True819#820# data = dict(821# result=result822# )823# except Exception, e:824# msg = msg_prefix + u"失败, 错误信息: " + unicode(e)825# logger.error(format_exc())826# return Response({"status": -1, "msg": msg, "data": {}},827# status=status.HTTP_500_INTERNAL_SERVER_ERROR)828# else:829# msg = msg_prefix + u"成功!"830# return Response({"status": 0, "msg": msg, "data": data})831@api_view(['POST'])832# @permission_classes((require_menu(["I00301"]),))833@post_validated_fields(require=['vm_name'])834def search_vm_name(request):835 """836 - 搜索虚拟机名837 """838 msg_prefix = u"搜索虚拟机名 "839 req_dict = post_data_to_dict(request.data)840 vm_name = smart_get(req_dict, 'vm_name', str)841 try:842 is_exist = False843 authorization = request.META.get('HTTP_AUTHORIZATION')844 vc_info_list = vc_info(token=authorization)845 vm_name_list = list()846 for vc in vc_info_list:847 vim_api = VimBase(vc[VC_IP], 443, vc[VC_USER], vc[VC_PASSWD])848 virtualmachines = vim_api.get_virtualmachines()849 for vm in virtualmachines:850 vm_name_list.append(vm.name)851 if vm_name in vm_name_list:852 is_exist = True853 except Exception, e:854 msg = msg_prefix + u"失败, 错误信息: " + unicode(e)855 logger.error(format_exc())856 return Response({"status": -1, "msg": msg, "data": {}},857 status=status.HTTP_500_INTERNAL_SERVER_ERROR)858 else:859 msg = msg_prefix + u"成功!"860 return Response({"status": 0, "msg": msg, "data": is_exist})861@api_view(['POST'])862# @permission_classes((require_menu(["I00301"]),))863@post_validated_fields(require=['vc_ip', 'vc_user', 'vc_passwd', 'cluster_name'])864def get_best_hosts(request):865 """866 smart867 & 主机868 - 获取集群中最优主机869 *参数870 ** vc_ip, vcenter ip, str871 ** vc_user, vcenter用户名, str872 ** vc_passwd, vcenter用户密码, str873 ** cluster_name, 集群名, str874 ** detail, 显示详细信息, bool875 *返回值876 *** hostsystem_name, 最优主机名, str877 """878 msg_prefix = u"获取集群最优主机 "879 req_dict = post_data_to_dict(request.data)880 vc_ip = smart_get(req_dict, 'vc_ip', str)881 vc_user = smart_get(req_dict, 'vc_user', str)882 vc_port = smart_get(req_dict, 'vc_port', int, 443)883 vc_passwd = smart_get(req_dict, 'vc_passwd', str)884 cluster_name = smart_get(req_dict, 'cluster_name', str)885 detail = smart_get(req_dict, 'detail', bool, False)886 try:887 vim_api = VimTasks(vc_ip, vc_port, vc_user, vc_passwd)888 cluster = vim_api.get_obj(name=cluster_name)889 cluster_serializer = ClusterSerializer(cluster)890 best_host = cluster_serializer.best_host_of_mb891 serializer = HostSystemSerializer(best_host, detail=detail)892 except Exception, e:893 msg = msg_prefix + u"失败, 错误信息: " + unicode(e)894 logger.error(format_exc())895 return Response({"status": -1, "msg": msg, "data": {}}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)896 else:897 msg = msg_prefix + u"成功!"898 return Response({"status": 1, "msg": msg, "data": serializer.data})899@api_view(['POST'])900# @permission_classes((require_menu(["I00301"]),))901@post_validated_fields(require=['vc_ip', 'vc_user', 'vc_passwd', 'cluster_name'])902def get_cluster_resp(request):903 """904 获取集群关联资源池列表905 *参数906 ** vc_ip, vcenter ip, str907 ** vc_user, vcenter用户名, str908 ** vc_passwd, vcenter用户密码, str909 ** cluster_name, 集群名, str910 ** detail, 显示详细信息, bool911 """912 msg_prefix = u"获取集群资源池列表 "913 req_dict = post_data_to_dict(request.data)914 vc_ip = smart_get(req_dict, 'vc_ip', str)915 vc_user = smart_get(req_dict, 'vc_user', str)916 vc_port = smart_get(req_dict, 'vc_port', int, 443)917 vc_passwd = smart_get(req_dict, 'vc_passwd', str)918 cluster_name = smart_get(req_dict, 'cluster_name', str)919 detail = smart_get(req_dict, 'detail', bool, False)920 try:921 vim_api = VimTasks(vc_ip, vc_port, vc_user, vc_passwd)922 cluster = vim_api.get_obj(name=cluster_name)923 resp = vim_api.resp_of_cluster(cluster)924 serializer = ResourcePoolSerializer(resp, detail=detail)925 except Exception, e:926 msg = msg_prefix + u"失败, 错误信息: " + unicode(e)927 logger.error(format_exc())928 return Response({"status": -1, "msg": msg, "data": {}}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)929 else:930 msg = msg_prefix + u"成功!"931 return Response({"status": 1, "msg": msg, "data": serializer.data})932##############################################分割线#################################################################933@api_view(['POST'])934# @permission_classes((require_menu(["I00301"]),))935@post_validated_fields(require=['vc_ip', 'vc_user', 'vc_passwd', 'vm_name'])936def get_vm_by_dnsname(request):937 """938 & 由dns名查找虚拟机939 - 由dns名查找虚拟机940 *参数941 ** vc_ip, vcenter ip, str942 ** vc_user, vcenter用户名, str943 ** vc_passwd, vcenter用户密码, str944 ** vm_name, 虚拟机名, str945 ** detail, 显示详细信息, bool946 """947 msg_prefix = u"搜索虚拟机 "948 req_dict = post_data_to_dict(request.data)949 vc_ip = req_dict.pop('vc_ip')950 vc_user = req_dict.pop('vc_user')951 vc_passwd = req_dict.pop('vc_passwd')952 vc_port = req_dict.pop('vc_port', 443)953 vm_name = smart_get(req_dict, 'vm_name', str)954 detail = smart_get(req_dict, 'detail', bool, True)955 try:956 vim_api = VimTasks(vc_ip, vc_port, vc_user, vc_passwd)957 virtualmachines = vim_api.findvm_by_dnsname(vm_name=vm_name)958 serializer = VirtualMachineSerializer(virtualmachines, detail=detail)959 except Exception, e:960 msg = msg_prefix + u"失败, 错误信息: " + unicode(e)961 logger.error(format_exc())962 return Response({"status": -1, "msg": msg, "data": {}}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)963 else:964 msg = msg_prefix + u"成功!"965 return Response({"status": 1, "msg": msg, "data": serializer.data})966@api_view(['POST'])967# @permission_classes((require_menu(["I00301"]),))968@post_validated_fields(require=['vc_ip', 'vc_user', 'vc_passwd', 'ipaddress'])969def get_vm_by_ip(request):970 """971 & 由ip地址查找虚拟机972 - 注 - 虚拟机关机状态不能使用ip查找973 *参数974 ** vc_ip, vcenter ip, str975 ** vc_user, vcenter用户名, str976 ** vc_passwd, vcenter用户密码, str977 ** detail, 显示详细信息, bool978 """979 msg_prefix = u"获取虚拟机 "980 req_dict = post_data_to_dict(request.data)981 vc_ip = req_dict.pop('vc_ip')982 vc_user = req_dict.pop('vc_user')983 vc_passwd = req_dict.pop('vc_passwd')984 vc_port = req_dict.pop('vc_port', 443)985 ipaddress = smart_get(req_dict, 'ipaddress', str)986 detail = smart_get(req_dict, 'detail', bool, True)987 try:988 vim_api = VimTasks(vc_ip, vc_port, vc_user, vc_passwd)989 virtualmachine = vim_api.findvm_by_ip(ip=ipaddress)990 serializer = VirtualMachineSerializer(virtualmachine, detail=detail)991 except Exception, e:992 msg = msg_prefix + u"失败, 错误信息: " + unicode(e)993 logger.error(format_exc())994 return Response({"status": -1, "msg": msg, "data": {}}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)995 else:996 msg = msg_prefix + u"成功!"997 return Response({"status": 1, "msg": msg, "data": serializer.data})998@api_view(['POST'])999# @permission_classes((require_menu(["I00301"]),))1000@post_validated_fields(require=['vc_ip', 'vc_user', 'vc_passwd', 'hostsystem_name'])1001def get_best_datastore(request):1002 """1003 筛选最佳存储(空间占用率最低)1004 *参数1005 ** vc_ip, vcenter ip, str1006 ** vc_user, vcenter用户名, str1007 ** vc_passwd, vcenter用户密码, str1008 ** hostsystem_name, 主机名, str1009 ** detail, 显示详细信息, bool1010 """1011 msg_prefix = u"获取主机存储列表 "1012 req_dict = post_data_to_dict(request.data)1013 vc_ip = smart_get(req_dict, 'vc_ip', str)1014 vc_user = smart_get(req_dict, 'vc_user', str)1015 vc_port = smart_get(req_dict, 'vc_port', int, 443)1016 vc_passwd = smart_get(req_dict, 'vc_passwd', str)1017 hostsystem_name = smart_get(req_dict, 'hostsystem_name', str)1018 detail = smart_get(req_dict, 'detail', bool, False)1019 try:1020 vim_api = VimTasks(vc_ip, vc_port, vc_user, vc_passwd)1021 hostsystem = vim_api.get_obj(name=hostsystem_name)1022 host_serializer = HostSystemSerializer(hostsystem)1023 best_datastore = host_serializer.best_datastore1024 serializer = DataStoreSerializer(best_datastore, detail=detail)1025 except Exception, e:1026 msg = msg_prefix + u"失败, 错误信息: " + unicode(e)1027 logger.error(format_exc())1028 return Response({"status": -1, "msg": msg, "data": {}}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)1029 else:1030 msg = msg_prefix + u"成功!"1031 return Response({"status": 1, "msg": msg, "data": serializer.data})1032@api_view(['POST'])1033# @permission_classes((require_menu(["I00301"]),))1034@post_validated_fields(require=['vc_ip', 'vc_user', 'vc_passwd'])1035def get_networks(request):1036 """1037 获取所有网络1038 *参数1039 ** vc_ip, vcenter ip, str1040 ** vc_user, vcenter用户名, str1041 ** vc_passwd, vcenter用户密码, str1042 ** detail, 显示详细信息, bool1043 """1044 msg_prefix = u"获取所有网络 "1045 req_dict = post_data_to_dict(request.data)1046 vc_ip = smart_get(req_dict, 'vc_ip', str)1047 vc_user = smart_get(req_dict, 'vc_user', str)1048 vc_port = smart_get(req_dict, 'vc_port', int, 443)1049 vc_passwd = smart_get(req_dict, 'vc_passwd', str)1050 detail = smart_get(req_dict, 'detail', bool, False)1051 try:1052 vim_api = VimTasks(vc_ip, vc_port, vc_user, vc_passwd)1053 networks = vim_api.network_of_all()1054 serializer = NetworkSerializer(networks, detail=detail)1055 except Exception, e:1056 msg = msg_prefix + u"失败, 错误信息: " + unicode(e)1057 logger.error(format_exc())1058 return Response({"status": -1, "msg": msg, "data": {}}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)1059 else:1060 msg = msg_prefix + u"成功!"1061 return Response({"status": 1, "msg": msg, "data": serializer.data})1062@api_view(['POST'])1063# @permission_classes((require_menu(["I00301"]),))1064@post_validated_fields(require=['vc_ip', 'vc_user', 'vc_passwd', 'datacenter_name'])1065def get_datacenter_network(request):1066 """1067 获取数据中心所有网络1068 *参数1069 ** vc_ip, vcenter ip, str1070 ** vc_user, vcenter用户名, str1071 ** vc_passwd, vcenter用户密码, str1072 ** datacenter_name, 数据中心名, str1073 ** detail, 显示详细信息, bool1074 """1075 msg_prefix = u"获取所有网络 "1076 req_dict = post_data_to_dict(request.data)1077 vc_ip = smart_get(req_dict, 'vc_ip', str)1078 vc_user = smart_get(req_dict, 'vc_user', str)1079 vc_port = smart_get(req_dict, 'vc_port', int, 443)1080 vc_passwd = smart_get(req_dict, 'vc_passwd', str)1081 datacenter_name = smart_get(req_dict, 'datacenter_name', str)1082 detail = smart_get(req_dict, 'detail', bool, False)1083 try:1084 vim_api = VimTasks(vc_ip, vc_port, vc_user, vc_passwd)1085 datacenter = vim_api.get_obj(name=datacenter_name)1086 networks = vim_api.network_of_datacenter(datacenter)1087 serializer = NetworkSerializer(networks, detail=detail)1088 except Exception, e:1089 msg = msg_prefix + u"失败, 错误信息: " + unicode(e)1090 logger.error(format_exc())1091 return Response({"status": -1, "msg": msg, "data": {}}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)1092 else:1093 msg = msg_prefix + u"成功!"1094 return Response({"status": 1, "msg": msg, "data": serializer.data})1095@api_view(['POST'])1096# @permission_classes((require_menu(["I00301"]),))1097@post_validated_fields(require=['vc_ip', 'vc_user', 'vc_passwd'])1098def get_virtualmachines(request):1099 """1100 获取数据中心虚拟机或模板列表1101 *参数1102 ** vc_ip, vcenter ip, str1103 ** vc_user, vcenter用户名, str1104 ** vc_passwd, vcenter用户密码, str1105 ** datacenter_name, 数据中心名, str1106 ** detail, 显示详细信息, bool1107 """1108 msg_prefix = u"获取虚拟机或模板列表 "1109 req_dict = post_data_to_dict(request.data)1110 vc_ip = smart_get(req_dict, 'vc_ip', str)1111 vc_user = smart_get(req_dict, 'vc_user', str)1112 vc_port = smart_get(req_dict, 'vc_port', int, 443)1113 vc_passwd = smart_get(req_dict, 'vc_passwd', str)1114 detail = smart_get(req_dict, 'detail', bool, False)1115 try:1116 vim_api = VimTasks(vc_ip, vc_port, vc_user, vc_passwd)1117 virtualmachines = vim_api.get_virtualmachines()1118 serializer = VirtualMachineSerializer(virtualmachines, detail=detail)1119 except Exception, e:1120 msg = msg_prefix + u"失败, 错误信息: " + unicode(e)1121 logger.error(format_exc())1122 return Response({"status": -1, "msg": msg, "data": {}}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)1123 else:1124 msg = msg_prefix + u"成功!"1125 return Response({"status": 1, "msg": msg, "data": serializer.data})1126@api_view(['POST'])1127# @permission_classes((require_menu(["I00301"]),))1128@post_validated_fields(require=['vc_ip', 'vc_user', 'vc_passwd', 'vm_name'])1129def get_virtualmachine_info(request):1130 """1131 获取虚拟机信息1132 *参数1133 ** vc_ip, vcenter ip, str1134 ** vc_user, vcenter用户名, str1135 ** vc_passwd, vcenter用户密码, str1136 ** vm_name, 虚拟机名, str1137 """1138 msg_prefix = u"获取虚拟机或模板列表 "1139 req_dict = post_data_to_dict(request.data)1140 vc_ip = smart_get(req_dict, 'vc_ip', str)1141 vc_user = smart_get(req_dict, 'vc_user', str)1142 vc_port = smart_get(req_dict, 'vc_port', int, 443)1143 vc_passwd = smart_get(req_dict, 'vc_passwd', str)1144 vm_name = smart_get(req_dict, 'vm_name', str)1145 try:1146 if not vm_name:1147 raise Exception(u"请填写虚拟机名")1148 vm_obj = None1149 vm_info = dict()1150 vim_api = VimTasks(vc_ip, vc_port, vc_user, vc_passwd)1151 virtualmachines = vim_api.get_virtualmachines()1152 for vm in virtualmachines:1153 if vm.name == vm_name:1154 vm_obj = vm1155 if vm_obj:1156 serializer = VirtualMachineSerializer(vm_obj, detail=True)1157 vm_info = serializer.data1158 except Exception, e:1159 msg = msg_prefix + u"失败, 错误信息: " + unicode(e)1160 logger.error(format_exc())1161 return Response({"status": -1, "msg": msg, "data": {}}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)1162 else:1163 msg = msg_prefix + u"成功!"1164 return Response({"status": 1, "msg": msg, "data": vm_info})1165@api_view(['POST'])1166# @permission_classes((require_menu(["I00301"]),))1167@post_validated_fields(require=['vc_ip', 'vc_user', 'vc_passwd'])1168def get_customspec(request):1169 """1170 获取自定义规则列表1171 *参数1172 ** vc_ip, vcenter ip, str1173 ** vc_user, vcenter用户名, str1174 ** vc_passwd, vcenter用户密码, str1175 ** detail - 显示详细信息1176 """1177 msg_prefix = u"获取自定义规则 "1178 req_dict = post_data_to_dict(request.data)1179 vc_ip = smart_get(req_dict, 'vc_ip', str)1180 vc_user = smart_get(req_dict, 'vc_user', str)1181 vc_port = smart_get(req_dict, 'vc_port', int, 443)1182 vc_passwd = smart_get(req_dict, 'vc_passwd', str)1183 detail = smart_get(req_dict, 'detail', bool, False)1184 try:1185 vim_api = VimTasks(vc_ip, vc_port, vc_user, vc_passwd)1186 customspec = vim_api.all_customspec()1187 serializer = CustomSpecSerializer(customspec, detail=detail)1188 except Exception, e:1189 msg = msg_prefix + u"失败, 错误信息: " + unicode(e)1190 logger.error(format_exc())1191 return Response({"status": -1, "msg": msg, "data": {}}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)1192 else:1193 msg = msg_prefix + u"成功!"1194 return Response({"status": 1, "msg": msg, "data": serializer.data})1195@api_view(['POST'])1196# @permission_classes((require_menu(["I00301"]),))1197@post_validated_fields(require=['vc_ip', 'vc_user', 'vc_passwd', 'spec_name'])1198def delete_customspec(request):1199 """1200 删除自定义规则1201 *参数1202 ** vc_ip, vcenter ip, str1203 ** vc_user, vcenter用户名, str1204 ** vc_passwd, vcenter用户密码, str1205 ** spec_name, 自定义规则name, str1206 """1207 msg_prefix = u"删除自定义规则 "1208 req_dict = post_data_to_dict(request.data)1209 vc_ip = smart_get(req_dict, 'vc_ip', str)1210 vc_user = smart_get(req_dict, 'vc_user', str)1211 vc_port = smart_get(req_dict, 'vc_port', int, 443)1212 vc_passwd = smart_get(req_dict, 'vc_passwd', str)1213 spec_name = smart_get(req_dict, 'spec_name', str)1214 try:1215 vim_api = VimTasks(vc_ip, vc_port, vc_user, vc_passwd)1216 result = vim_api.delete_customspec(spec_name)1217 except Exception, e:1218 msg = msg_prefix + u"失败, 错误信息: " + unicode(e)1219 logger.error(format_exc())1220 return Response({"status": -1, "msg": msg, "data": {}}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)1221 else:1222 msg = msg_prefix + u"成功!"1223 return Response({"status": 1, "msg": msg, "data": result})1224@api_view(['POST'])1225# @permission_classes((require_menu(["I00301"]),))1226@post_validated_fields(require=['env_type', 'unit', 'stock_app', 'internal_app'])1227def default_vmware_name(request):1228 """1229 获取推荐虚拟机名称1230 *参数1231 ** env_type, 环境类型, str1232 ** unit, 单位, str1233 ** stock_app, 存量应用, str1234 ** internal_app, 分行特色应用, str1235 ** exist_names, 虚拟机名称页面缓存, list1236 * 返回值1237 *** default_name, 默认虚拟机名, str1238 """1239 msg_prefix = u"获取推荐虚拟机名称 "1240 req_dict = post_data_to_dict(request.data)1241 env_type = smart_get(req_dict, 'env_type', str)1242 unit = smart_get(req_dict, 'unit', str)1243 stock_app = smart_get(req_dict, 'stock_app', str)1244 internal_app = smart_get(req_dict, 'internal_app', str)1245 exist_names = smart_get(req_dict, 'exist_names', list)1246 try:1247 default_name = default_vm_name(env_type, unit, stock_app, internal_app, exist_names)1248 except Exception, e:1249 msg = msg_prefix + u"失败, 错误信息: " + unicode(e)1250 logger.error(format_exc())1251 return Response({"status": -1, "msg": msg, "data": {}}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)1252 else:1253 msg = msg_prefix + u"成功!"1254 return Response({"status": 1, "msg": msg, "data": {"default_name": default_name}})1255@api_view(['POST'])1256# @permission_classes((require_menu(["I00301"]),))1257@post_validated_fields(require=['vc_ip', 'vc_user', 'vc_passwd', 'vm_name'])1258def get_disk(request):1259 """1260 获取所有磁盘1261 * 参数1262 ** vc_ip, vcenter ip, str1263 ** vc_user, vcenter用户名, str1264 ** vc_passwd, vcenter用户密码, str1265 ** vm_name, 虚拟机名, str1266 """1267 msg_prefix = u"获取虚拟机磁盘列表 "1268 req_dict = post_data_to_dict(request.data)1269 vc_ip = req_dict.pop('vc_ip')1270 vc_user = req_dict.pop('vc_user')1271 vc_passwd = req_dict.pop('vc_passwd')1272 vc_port = req_dict.pop('vc_port', 443)1273 vm_name = smart_get(req_dict, 'vm_name', str)1274 try:1275 vim_api = VimTasks(vc_ip, vc_port, vc_user, vc_passwd)1276 virtualmachines = vim_api.findvm_by_dnsname(vm_name=vm_name)1277 disks = vim_api.get_all_disk(virtualmachines)1278 except Exception, e:1279 msg = msg_prefix + u"失败, 错误信息: " + unicode(e)1280 logger.error(format_exc())1281 return Response({"status": -1, "msg": msg, "data": {}},1282 status=status.HTTP_500_INTERNAL_SERVER_ERROR)1283 else:1284 msg = msg_prefix + u"成功!"1285 return Response(1286 {"status": 0, "msg": msg, "data": str(disks)})1287@api_view(['POST'])1288# @permission_classes((require_menu(["I00301"]),))1289@post_validated_fields(require=['vc_ip', 'vc_user', 'vc_passwd', 'vm_name', 'disk_size'])1290def add_disk(request):1291 """1292 添加新磁盘1293 * 参数1294 ** vc_ip, vcenter ip, str1295 ** vc_user, vcenter用户名, str1296 ** vc_passwd, vcenter用户密码, str1297 ** vm_name, 虚拟机名, str1298 ** disk_size, 磁盘大小, int1299 * 返回值1300 ** state, 添加磁盘状态, str1301 """1302 msg_prefix = u"添加磁盘 "1303 req_dict = post_data_to_dict(request.data)1304 vc_ip = req_dict.pop('vc_ip')1305 vc_user = req_dict.pop('vc_user')1306 vc_passwd = req_dict.pop('vc_passwd')1307 vc_port = req_dict.pop('vc_port', 443)1308 vm_name = smart_get(req_dict, 'vm_name', str)1309 disk_size = smart_get(req_dict, 'disk_size', int)1310 try:1311 vim_api = VimTasks(vc_ip, vc_port, vc_user, vc_passwd)1312 virtualmachines = vim_api.findvm_by_dnsname(vm_name=vm_name)1313 state = vim_api.add_disk(virtualmachines, disk_size)1314 data = {"state": state}1315 except Exception, e:1316 msg = msg_prefix + u"失败, 错误信息: " + unicode(e)1317 logger.error(format_exc())1318 return Response({"status": -1, "msg": msg, "data": {}},1319 status=status.HTTP_500_INTERNAL_SERVER_ERROR)1320 else:1321 msg = msg_prefix + u"成功!"1322 return Response(1323 {"status": 0, "msg": msg, "data": data})1324@api_view(['POST'])1325# @permission_classes((require_menu(["I00301"]),))1326@post_validated_fields(require=['host_list', 'conn_user', 'conn_pass', 'local_user', 'become_pass'])1327def push_pubkey(request):1328 """1329 推送用户公钥1330 * 参数1331 ** ipaddress - 目标ip1332 ** conn_user - 远程主机用户1333 ** conn_pass - 远程主机用户密码1334 ** become_pass - 远程主机sudo密码1335 ** local_user - 本地用户1336 """1337 msg_prefix = u"推送用户公钥 "1338 req_dict = post_data_to_dict(request.data)1339 host_list = smart_get(req_dict, 'host_list', str)1340 conn_user = smart_get(req_dict, 'conn_user', str)1341 conn_pass = smart_get(req_dict, 'conn_pass', str)1342 become_pass = smart_get(req_dict, 'become_pass', str)1343 local_user = smart_get(req_dict, 'local_user', str)1344 try:1345 ansible_api = AnsiblePlay(host_list, local_user, conn_user, conn_pass, become_pass)1346 data = ansible_api.play_authorized_user(conn_user, local_user)1347 except Exception, e:1348 msg = msg_prefix + u"失败, 错误信息: " + unicode(e)1349 logger.error(format_exc())1350 return Response({"status": -1, "msg": msg, "data": {}},1351 status=status.HTTP_500_INTERNAL_SERVER_ERROR)1352 else:1353 msg = msg_prefix + u"成功!"1354 return Response({"status": 0, "msg": msg, "data": {"result": str(data)}})1355@api_view(['POST'])1356# @permission_classes((require_menu(["I00301"]),))1357@post_validated_fields(require=['ipaddress', 'conn_user', 'auth_type', 'os_type'])1358def remove_vg(request):1359 """1360 删除vg1361 * 参数1362 ** ipaddress - 目标ip地址1363 ** conn_user - 目标用户(此ip上用户)1364 ** conn_pass - 目标主机用户密码1365 ** become_pass - 目标主机用户sudo密码1366 ** local_user - 本地用户(平台账户)1367 ** os_type - 操作系统类型1368 ** auth_type - 认证方式(pubkey/password)1369 ** vg_name - vg_name1370 ** disk_path - 磁盘路径1371 """1372 msg_prefix = u"删除vg "1373 req_dict = post_data_to_dict(request.data)1374 ipaddress = smart_get(req_dict, 'ipaddress', str)1375 conn_user = smart_get(req_dict, 'conn_user', str)1376 conn_pass = smart_get(req_dict, 'conn_pass', str)1377 local_user = smart_get(req_dict, 'local_user', str)1378 become_pass = smart_get(req_dict, 'become_pass', str)1379 auth_type = smart_get(req_dict, 'auth_type', str)1380 os_type = smart_get(req_dict, 'os_type', str)1381 vg_name = smart_get(req_dict, 'vg_name', str, "datavg")1382 disk_path = smart_get(req_dict, 'disk_path', str)1383 try:1384 play = PlayWithAdminUsingPass(ipaddress, conn_user, conn_pass, local_user, become_pass=become_pass)1385 readout = play.resize_vg(vg_name, disk_path)1386 except Exception, e:1387 msg = msg_prefix + u"失败, 错误信息: " + unicode(e)1388 logger.error(format_exc())1389 return Response({"status": -1, "msg": msg, "data": {}},1390 status=status.HTTP_500_INTERNAL_SERVER_ERROR)1391 else:1392 msg = msg_prefix + u"成功!"1393 return Response({"status": 0, "msg": msg, "data": str(readout)})1394@api_view(['POST'])1395# @permission_classes((require_menu(["I00301"]),))1396@post_validated_fields(1397 require=['ipaddress', 'conn_user', 'auth_type', 'os_type', 'unit_number', 'conn_pass', 'local_user', 'become_pass'])1398def vm_partition(request):1399 """1400 操作系统分区和添加文件系统1401 * 参数1402 ** ipaddress - 目标ip地址1403 ** conn_user - 目标用户(此ip上用户)1404 ** conn_pass - 目标主机用户密码1405 ** become_pass - 目标主机用户sudo密码1406 ** local_user - 本地用户(平台账户)1407 ** os_type - 操作系统类型1408 ** auth_type - 认证方式(pubkey/password)1409 ** disk_path - 磁盘路径 (默认为 /dev/sd)1410 ** unit_number - 磁盘编号1411 ** vg_name - vg_name1412 """1413 msg_prefix = u"操作系统分区和添加文件系统 "1414 req_dict = post_data_to_dict(request.data)1415 ipaddress = smart_get(req_dict, 'ipaddress', str)1416 conn_user = smart_get(req_dict, 'conn_user', str)1417 conn_pass = smart_get(req_dict, 'conn_pass', str)1418 become_pass = smart_get(req_dict, 'become_pass', str)1419 local_user = smart_get(req_dict, 'local_user', str, 'admin')1420 auth_type = smart_get(req_dict, 'auth_type', str)1421 os_type = smart_get(req_dict, 'os_type', str)1422 unit_number = smart_get(req_dict, 'unit_number', int)1423 disk_path = smart_get(req_dict, 'disk_path', str, '/dev/sd')1424 vg_name = smart_get(req_dict, 'vg_name', str, "datavg")1425 try:1426 result = None1427 if os_type == "Linux":1428 disk_path = disk_path + chr(97 + unit_number)1429 if disk_path:1430 # ssh_executor = SshExecutor(hostname=ipaddress, conn_user=conn_user, conn_pass=conn_pass,1431 # auth_type=auth_type, local_user=local_user)1432 # readout = ssh_executor.add_disk_to_vg(vg_name, disk_path)1433 play = PlayWithAdminUsingPass(ipaddress, conn_user, conn_pass, local_user, become_pass)1434 # result = play.parted(disk_path)1435 result = play.test()1436 else:1437 raise Exception(u"未找到磁盘!")1438 else:1439 pass1440 except Exception, e:1441 msg = msg_prefix + u"失败, 错误信息: " + unicode(e)1442 logger.error(format_exc())1443 return Response({"status": -1, "msg": msg, "data": {}},1444 status=status.HTTP_500_INTERNAL_SERVER_ERROR)1445 else:1446 msg = msg_prefix + u"成功!"1447 return Response({"status": 0, "msg": msg, "data": {"result": result}})1448@api_view(['POST'])1449# @permission_classes((require_menu(["I00301"]),))1450@post_validated_fields(require=['ipaddress', 'conn_user', 'auth_type', 'soft_id'])1451def vm_install_soft(request):1452 """1453 安装软件1454 * 参数1455 ** ipaddress - 目标ip地址1456 ** conn_user - 目标用户(此ip上用户)1457 ** conn_pass - 目标主机用户密码1458 ** become_pass - 目标主机用户sudo密码1459 ** local_user - 本地用户(平台账户)1460 ** auth_type - 认证方式(pubkey/passwd)1461 ** soft_id - 安装软件id(列表)1462 ** install_dir - 软件安装介质本地存放目录(绝对路径)1463 ** package_type - 软件包类型1464 ** package_name - 软件包名称1465 """1466 msg_prefix = u"安装软件,任务启动 "1467 req_dict = post_data_to_dict(request.data)1468 ipaddress = smart_get(req_dict, 'ipaddress', str)1469 conn_user = smart_get(req_dict, 'conn_user', str)1470 conn_pass = smart_get(req_dict, 'conn_pass', str)1471 become_pass = smart_get(req_dict, 'become_pass', str)1472 auth_type = smart_get(req_dict, 'auth_type', str)1473 local_user = smart_get(req_dict, 'local_user', str)1474 install_dir = smart_get(req_dict, 'install_dir', str)1475 soft_ids = smart_get(req_dict, 'soft_id', int)1476 try:1477 software = Software.objects.get(id=soft_ids)1478 if software.support_os == 'Linux':1479 if software.install_method == "ansible":1480 if software.playbook:1481 pass1482 else:1483 play = PlayWithAdminUsingPass(ipaddress, conn_user, conn_pass, local_user, become_pass)1484 dirs = [install_dir, REMOTE_LOGDIR]1485 play.create_dir(dirs)1486 run = play.shell_cmd(install_dir, REMOTE_LOGDIR, software.medium_path, software.script_path, 1)1487 # result = play.install_soft(softname=software.name, package_manage=software.package_manage,1488 # medium_path=software.medium_path)1489 elif software.install_method == "ssh":1490 ssh_executor = SshExecutor(hostname=ipaddress, conn_user=conn_user, auth_type=auth_type,1491 local_user=local_user, conn_pass=conn_pass)1492 medium_path = software.medium_path1493 script_path = software.script_path1494 result = ssh_executor.install_stuff(install_dir, medium_path, script_path)1495 elif software.install_method == "dcap":1496 pass1497 elif software.support_os == 'Windows':1498 pass1499 else:1500 raise Exception(u"不支持的操作系统!")1501 except Exception, e:1502 msg = msg_prefix + u"失败, 错误信息: " + unicode(e)1503 logger.error(format_exc())1504 return Response({"status": -1, "msg": msg, "data": {}},1505 status=status.HTTP_500_INTERNAL_SERVER_ERROR)1506 else:1507 msg = msg_prefix + u"成功!"1508 return Response({"status": 0, "msg": msg, "data": {}})1509@api_view(['POST'])1510# @permission_classes((require_menu(["I00301"]),))1511@post_validated_fields(require=['ipaddress'])1512def vm_add_user(request):1513 """1514 添加管理员用户1515 * 参数1516 ** ipaddress - 目标ip地址1517 """1518 msg_prefix = u"添加管理员用户,任务启动 "1519 req_dict = post_data_to_dict(request.data)1520 ipaddress = smart_get(req_dict, 'ip', str)1521 try:1522 # play = PlayWithAdmin(ipaddress)1523 # play.play_add_user(target_user)1524 pass1525 except Exception, e:1526 msg = msg_prefix + u"失败, 错误信息: " + unicode(e)1527 logger.error(format_exc())1528 return Response({"status": -1, "msg": msg, "data": {}},1529 status=status.HTTP_500_INTERNAL_SERVER_ERROR)1530 else:1531 msg = msg_prefix + u"成功!"1532 return Response({"status": 0, "msg": msg, "data": {}})1533# @api_view(['POST'])1534# @permission_classes((require_menu(["I00302", "I00303", "I00304"]),))1535# @post_validated_fields(require=['id'])1536# def vm_mail_notice(request):1537# """1538# 邮件通知申请人/审批人1539# :param request:1540# :return:1541# """1542# msg_prefix = u"邮件通知 "1543# req_dict = post_data_to_dict(request.data)1544# id = smart_get(req_dict, 'id', int)1545# try:1546# if not ipaddress:1547# virtualmachine = VirtualMachine.objects.get(id=id)1548# vcenter = virtualmachine.resourcepool.vcenter1549# ipaddress = get_vm_ip(virtualmachine)1550#1551# subject = DEFAULT_SUBJECT_PREFIX + u"虚拟环境资源信息"1552# content = (u"虚拟环境资源[{vm_name}]生成完毕,附资源详情信息,请知晓。\n\n" +1553# u"资源详情:\n" +1554# u"\t资源名称: {vm_name}\n" +1555# u"\tIP 地址: {vm_ip}\n" +1556# "").format(1557# vm_name=virtualmachine.name, os=virtualmachine.guestos_fullname,1558# vm_ip=", ".join([ip for ip in ipaddress]),...

Full Screen

Full Screen

user.py

Source:user.py Github

copy

Full Screen

...23 elif value.lower() in ("0", "false", "no", "off", "disable"):24 return False25 raise ValueError("%s is not boolean value" % value)26class SmartParser(ConfigParser):27 def smart_get(self, obj, key, conv=str, sec='main'):28 try:29 val = self.get(sec, key)30 setattr(obj, key, conv(val))31 except NoSectionError:32 pass33 except NoOptionError:34 pass35 except Exception:36 print_exc()37 def smart_set(self, obj, key, sec='main'):38 self.set(sec, key, str(getattr(obj, key)))39class EditorPreferences(object):40 period_save = True41 check_spelling = True42 spell_lang = ""43 spaces_instead_of_tabs = False44 tab_width = 845 auto_indent = True46 line_numbers = True47 right_margin = True48 right_margin_value = 8049 current_line = False50 text_wrapping = True51 white_chars = False52class UserPreferences(object):53 preview = Orientation.HORIZONTAL.numerator54 auto_scroll = True55 parser = 'rst'56 writer = 'html4'57 style = ''58 custom_style = False59 editor = EditorPreferences()60 def __init__(self):61 self.load()62 def load(self):63 directory = get_user_config_dir()64 cp = SmartParser()65 cp.read("%s/formiko.ini" % directory)66 cp.smart_get(self, 'preview', int)67 cp.smart_get(self, 'auto_scroll', smart_bool)68 cp.smart_get(self, 'parser')69 if self.parser not in PARSERS:70 log_default_handler("Application", LogLevelFlags.LEVEL_WARNING,71 "Unknow parser `%s' in config, set default."72 % self.parser)73 self.parser = 'rst'74 cp.smart_get(self, 'writer')75 cp.smart_get(self, 'style')76 cp.smart_get(self, 'custom_style', smart_bool)77 cp.smart_get(self.editor, 'period_save', smart_bool, 'editor')78 cp.smart_get(self.editor, 'check_spelling', smart_bool, 'editor')79 cp.smart_get(self.editor, 'spell_lang', str, 'editor')80 cp.smart_get(self.editor, 'spaces_instead_of_tabs', smart_bool,81 'editor')82 cp.smart_get(self.editor, 'tab_width', int, 'editor')83 cp.smart_get(self.editor, 'auto_indent', smart_bool, 'editor')84 cp.smart_get(self.editor, 'line_numbers', smart_bool, 'editor')85 cp.smart_get(self.editor, 'right_margin', smart_bool, 'editor')86 cp.smart_get(self.editor, 'right_margin_value', int, 'editor')87 cp.smart_get(self.editor, 'current_line', smart_bool, 'editor')88 cp.smart_get(self.editor, 'text_wrapping', smart_bool, 'editor')89 cp.smart_get(self.editor, 'white_chars', smart_bool, 'editor')90 def save(self):91 cp = SmartParser()92 cp.add_section('main')93 cp.set('main', 'preview', str(int(self.preview)))94 cp.smart_set(self, 'auto_scroll')95 cp.smart_set(self, 'parser')96 cp.smart_set(self, 'writer')97 cp.smart_set(self, 'style')98 cp.smart_set(self, 'custom_style')99 cp.add_section('editor')100 cp.smart_set(self.editor, 'period_save', 'editor')101 cp.smart_set(self.editor, 'check_spelling', 'editor')102 cp.smart_set(self.editor, 'spell_lang', 'editor')103 cp.smart_set(self.editor, 'spaces_instead_of_tabs', 'editor')104 cp.smart_set(self.editor, 'tab_width', 'editor')105 cp.smart_set(self.editor, 'auto_indent', 'editor')106 cp.smart_set(self.editor, 'line_numbers', 'editor')107 cp.smart_set(self.editor, 'right_margin', 'editor')108 cp.smart_set(self.editor, 'right_margin_value', 'editor')109 cp.smart_set(self.editor, 'current_line', 'editor')110 cp.smart_set(self.editor, 'text_wrapping', 'editor')111 cp.smart_set(self.editor, 'white_chars', 'editor')112 directory = get_user_config_dir()113 if not exists(directory):114 makedirs(directory)115 with open("%s/formiko.ini" % directory, 'w+') as fp:116 cp.write(fp)117class UserCache(object):118 width = 800119 height = 600120 paned = 400121 is_maximized = False122 view = View.BOTH123 def __init__(self):124 self.load()125 def load(self):126 directory = get_user_cache_dir()127 cp = SmartParser()128 cp.read("%s/formiko/window.ini" % directory)129 cp.smart_get(self, 'width', int)130 cp.smart_get(self, 'height', int)131 cp.smart_get(self, 'paned', int)132 cp.smart_get(self, 'is_maximized', smart_bool)133 cp.smart_get(self, 'view', View)134 def save(self):135 cp = SmartParser()136 cp.add_section('main')137 cp.set('main', 'width', str(self.width))138 cp.set('main', 'height', str(self.height))139 cp.set('main', 'paned', str(self.paned))140 cp.set('main', 'is_maximized', str(self.is_maximized))141 cp.set('main', 'view', str(self.view))142 directory = get_user_cache_dir()+"/formiko"143 if not exists(directory):144 makedirs(directory)145 with open("%s/window.ini" % directory, 'w+') as fp:...

Full Screen

Full Screen

parser.py

Source:parser.py Github

copy

Full Screen

...8else: # python 3.x9 from configparser import ConfigParser, NoSectionError, NoOptionError10 uni_cls = str11from falias.util import uni12def smart_get(value, cls=uni_cls, delimiter=','):13 """ Smart convert function, which convert value to cls. """14 if issubclass(cls, uni_cls):15 return uni(value)16 if issubclass(cls, str):17 return value18 if issubclass(cls, bool):19 if value.lower() in ('true', 'yes', '1', 'on', 'enable'):20 return True21 elif value.lower() in ('false', 'no', '0', 'off', 'disable'):22 return False23 else:24 raise ValueError("%s is not boolean value" % value)25 if cls in (list, tuple):26 if value:27 return cls(map(lambda s: uni(s.strip()), value.split(delimiter)))28 return cls()29 else:30 return cls(value)31class Parser(ConfigParser):32 """ Wrapper to ConfigParser class, with better get method. """33 def get(self, section, option, default=None, cls=uni_cls, delimiter=','):34 """35 Method do the same as original get, but it can work with default value36 and use smart_get convert function to converting values to classes.37 """38 default = None if default is None else str(default)39 try:40 value = ConfigParser.get(self, section, option).strip()41 except NoSectionError:42 if default is None:43 raise44 value = default45 except NoOptionError:46 if default is None:47 raise48 value = default49 return smart_get(value, cls, delimiter)50class Options:51 """52 Compatible like class to ConfigParser, for read values from dictionary53 (options) with syntax section_option.54 """55 def __init__(self, options):56 self.o = options57 def get(self, sec, key, default=None, cls=uni_cls, delimiter=','):58 default = None if default is None else str(default)59 key = "%s_%s" % (sec, key)60 if default is None and key not in self.o:61 raise RuntimeError('Envirnonment variable `%s` is not set' % key)62 value = self.o.get(key, default).strip()63 return smart_get(value, cls, delimiter)64 def options(self, section):65 """Returns options in section like in ConfigParser."""66 sec_len = len(section) + 167 return list(key[sec_len:] for key, value in self.o.items()...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run autotest automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful