django中嵌套的try-except

mac2022-06-30  24

# 因为此时为yaml模板,而且只抓取node port,所以这样处理效率快content_dict = parse_yaml(content.replace("{{", "").replace("}}", ""))if 'service' in content_dict.keys(): # 记录本次yaml里所有的node_port,并更新到数据库 now_app_list = [] for service_item in content_dict['service']: for port_item in service_item['port']: if 'nodePort' in port_item.keys(): node_port = int(port_item['nodePort']) if 30000 <= node_port <= 32000: # 这里判断比较复杂,如果端口有,而且app相同,不更新。如果端口有,app不一样,报冲突。如果端口没有,可插入。 now_app_list.append(node_port) try: AppPort.objects.get(node_port=node_port, app=app) pass except AppPort.DoesNotExist: try: AppPort.objects.get(node_port=node_port) messages.info(self.request, 'nodeport{}端口冲突!'.format(node_port)) return HttpResponseRedirect(reverse_lazy("app:yaml_edit", kwargs=self.kwargs)) except AppPort.DoesNotExist: name = '{}-{}'.format(app.name, node_port) AppPort.objects.create( name=name, app=app, node_port=node_port ) else: messages.info(self.request, 'nodeport{}端口不在指定范围内(30000-~32000)!'.format(node_port)) return HttpResponseRedirect(reverse_lazy("app:yaml_edit", kwargs=self.kwargs)) # 取出AppPort里所有此app的node_port,多余的要清除。 all_app_list = AppPort.objects.filter(app=app).values_list('node_port', flat=True) if all_app_list: # 取交集,也就是数据库里多余的端口列表 diff_list = [x for x in all_app_list if x not in now_app_list] if diff_list: AppPort.objects.filter(node_port__in=diff_list).delete()  

 感觉上面这段代码,应用的技术点蛮多的,作个记录。

包括其node port的管理思想,提取技巧。

orm的列表扁平化,列表交集,批量删除

转载于:https://www.cnblogs.com/aguncn/p/11359430.html

相关资源:django 双重嵌套模板
最新回复(0)