优化这部分代码: def network_planes_check(self): LOG.info('start network_planes_check...') err_msgs = [] with open(self.JSON_PATH, 'r') as f: data = json.load(f) ip_versions = [] for vxlan_plane in data["vxlan_planes"]: for info in vxlan_plane["ip_ranges"]: cidr = info["cidr"] start = info["start"] end = info["end"] # Check if cidr/start/end is configured if cidr and start and end: # Check if cidr format is correct try: ip_network = ipaddress.ip_network(cidr) ip_versions.append(ip_network.version) if ipaddress.ip_address(start) in ip_network \ and ipaddress.ip_address(end) in ip_network: # Check if cidr is within start and end range if ipaddress.ip_address(start) <= ipaddress.ip_address(end): err_msgs.append('IP is valid') else: err_msgs.append('start_ip %s is not ' 'less than end_ip %s' % (start, end)) else: err_msgs.append('start_ip %s or end_ip %s is ' 'not in cidr %s' % (start, end, cidr)) except ValueError: err_msgs.append("Error: cidr format is incorrect") else: err_msgs.append("Error: cidr/start/end is not configured") ip_ver_count = len(set(ip_versions)) if ip_ver_count > 1: err_msgs.append("Error: cidr is mixed ipv4/ipv6") return err_msgs
时间: 2024-02-10 11:14:20 浏览: 101
Here's an optimized version of the code:
```
def network_planes_check(self):
LOG.info('start network_planes_check...')
err_msgs = []
with open(self.JSON_PATH, 'r') as f:
data = json.load(f)
ip_versions = set() # Use set to avoid duplicates
for vxlan_plane in data["vxlan_planes"]:
for info in vxlan_plane["ip_ranges"]:
cidr, start, end = info.get("cidr"), info.get("start"), info.get("end")
if cidr and start and end:
# Check if cidr format is correct
try:
ip_network = ipaddress.ip_network(cidr)
except ValueError:
err_msgs.append("Error: cidr format is incorrect")
continue
ip_versions.add(ip_network.version)
if (ipaddress.ip_address(start) not in ip_network or
ipaddress.ip_address(end) not in ip_network):
err_msgs.append('start_ip %s or end_ip %s is not in cidr %s' % (start, end, cidr))
elif ipaddress.ip_address(start) > ipaddress.ip_address(end):
err_msgs.append('start_ip %s is not less than end_ip %s' % (start, end))
else:
err_msgs.append('IP is valid')
else:
err_msgs.append("Error: cidr/start/end is not configured")
if len(ip_versions) > 1:
err_msgs.append("Error: cidr is mixed ipv4/ipv6")
return err_msgs
```
Here are the changes I made:
- Used `info.get("cidr")` instead of `info["cidr"]` to avoid a `KeyError` if `cidr` is missing.
- Used `set()` to keep track of the IP versions encountered, so we can check if there's a mix of IPv4 and IPv6.
- Moved the check for `cidr/start/end` outside the `try` block, since we don't need to catch a `ValueError` for that.
- Simplified the checks for `start` and `end` being in the CIDR range, and for `start` being less than `end`.
- Used `continue` to skip to the next iteration of the loop if the CIDR format is incorrect.
阅读全文