我正在构建一个Flask服务器,并验证主机名是唯一的,IP地址在发送curl请求时不与另一个IP重叠。POST请求是这样的:
curl http://127.0.0.1:5000/hosts --request POST -d '[{"address": "1.2.3.4", "hostname": "test1", "routes": "1.2.3.1/16"}, {"address": "1.2.3.4", "hostname": "test2", "routes": "5.1.2.5/16"}]' -H 'Content-Type: application/json'
代码如下:
def put_hosts():
content = request.get_json(silent=True)
with open('example.json', 'r') as config_file:
data = json.load(config_file)
for i in content:
data.append(i)
with open('example.json', 'w') as config_file:
json.dump(data, config_file, sort_keys = True, indent = 4,
ensure_ascii = False)
return jsonify(data), 201
目前一切正常,除非用户添加两个相同的IP地址或名称,它们都被保存为副本。我想在发送请求时过滤这些重复的内容。如果用户给出两个相同的IP地址,我想返回一个错误。我试着修复这个问题:
lines = config_file.readlines()
for line in lines:
if line.rstrip() == "{} {}".format(host['address'], host['hostname']):
duplicate = True
但没有成功。有没有办法让它们不重叠
这可以通过多种方式解决。如果要自动删除重复项—使用字典:
In [1]: a = [{"address": "1.2.3.4", "hostname": "test1", "routes": "1.2.3.1/16"}, {"address": "1.2.3.4", "hostname": "test2", "routes": "5.1.2.5/16"}]
In [2]: a
Out[2]:
[{'address': '1.2.3.4', 'hostname': 'test1', 'routes': '1.2.3.1/16'},
{'address': '1.2.3.4', 'hostname': 'test2', 'routes': '5.1.2.5/16'}]
In [3]: {each['address']: each for each in a}
Out[3]:
{'1.2.3.4': {'address': '1.2.3.4',
'hostname': 'test2',
'routes': '5.1.2.5/16'}}
现在你有了一个字典,其中键是唯一的ipaddress,值是保存该ipaddress的整个json。因为字典不能有重复的键,所以重复项会被自动删除。
如果你想返回一个错误,收集所有的ip地址并检查是否有重复的。收集之后,创建一组结果并比较其长度。Set将删除所有重复项。因此,如果存在重复,则长度将不匹配。
In [5]: [each['address'] for each in a]
Out[5]: ['1.2.3.4', '1.2.3.4']
In [6]: set([each['address'] for each in a])
Out[6]: {'1.2.3.4'}
In [7]: len(set([each['address'] for each in a])) == len([each['address'] for each in a])
Out[7]: False