python 从嵌套 yaml 中提取的变量
python variable extracted from nested yaml
正在尝试找到一种遍历 roleprivs 的方法,但在从 python 到达 yaml 的该级别时遇到问题。
testrole.yaml
info:
rolename: "testDeveloper"
desc: "Test Developer Role"
roletype: "user"
roleprivs:
admin-appliance:
name: "Administrate Appliance" # Informational Only Not used in code
description: "admin-appliance" # Informational Only Not used in code
code: "admin-appliance"
access: "full"
admin-backupSettings:
name: "Administrate Backup Settings" # Informational Only Not used in code
description: "admin-appliance" # Informational Only Not used in code
code: "admin-backupSettings"
access: "full"
我有几个不同的需求/用例。
- 下面脚本的第 1 部分 - 获取目录中的所有文件并获取角色名、描述符和角色类型并创建一个角色。
- 获取上面新建角色的角色ID。
- 需要帮助 - 返回原始 yaml 文件并对其进行迭代并仅获取 roleprivs..code 和 roleprivs..code --> 角色类型类似于 admin-appliance。请记住,大约有 50 种奇怪的功能需要根据访问类型进行更新。
问题:
如何将 yaml 文件中的代码和访问权限放入 python 变量中?
def genericRoleCreate(baseURL, bearerToken):
print("initial")
files = glob.glob(ROLES_DIR)
logger.debug('Roles Dir '+ROLES_DIR)
for file in files:
yaml_file = file
logger.debug(yaml_file)
with open(yaml_file) as f:
try:
result=yaml.safe_load(f)
authority = result['info']['rolename']
desc = result['info']['desc']
roletype = result['info']['roletype']
url = baseURL+"/api/roles"
payload= json.dumps({"role":{"authority": authority, "description": desc, "roletype": roletype}})
headers = {'Content-Type': 'application/json','Authorization': 'Bearer ' +bearerToken}
roleResult = requests.request("POST", url, verify=False, headers=headers, data=payload)
logger.debug(roleResult.text)
except yaml.YAMLError as exc:
logger.error(exc)
# Getting Role ID
try:
with open(yaml_file) as f:
result = yaml.safe_load(f)
authority = result['info']['rolename']
url = baseURL+"/api/roles?phrase="+authority
headers = {'Content-Type': 'application/json','Authorization': 'Bearer ' +bearerToken}
roleResult = requests.request("GET", url, verify=False, headers=headers )
#print(roleResult.text)
roleID = json.loads(roleResult.text)
role = roleID['roles'][0]['id']
#logger.debug(role)
logger.info("Get Role ID")
print(role)
#return role
#logger.debug("Role ID: "+role)
except Exception as e:
logger.error('Exception occurred', exc_info=True)
logger.error('Error getting roleID')
# Start Updating
#role = getRoleId(baseURL, bearerToken)
try:
with open(yaml_file) as f:
result = yaml.safe_load(f)
except Exception as e:
logger.error("Broken")
strRoleID = str(role)
url = baseURL+"/api/roles/"+strRoleID+"/update-permission"
#logger.debug(result)
keys = list(result.keys())
for features in keys:
#logger.debug(keys)
code = result[features]['code']
access = result[features]['access']
payload = json.dumps({
"permissionCode": code,
"access": access
})
headers = {'Content-Type': 'application/json','Authorization': 'Bearer ' +bearerToken}
requests.request("PUT", url, verify=False, headers=headers, data=payload)
请记住,我确实知道我应该将那个讨厌的大东西分解成多个函数——我在其他地方把它分解了——但当时把所有东西都编译成一个函数。
我一直在尝试多次迭代如何达到功能级别。我看了很多例子,但似乎无法弄清楚如何降到一个水平。
更新 1
try:
with open(yaml_file, 'r') as f:
result = yaml.safe_load(f)
except Exception as e:
logger.error("Broken")
strRoleID = str(role)
url = baseURL+"/api/roles/"+strRoleID+"/update-permission"
#logger.debug(result)
keys = list(result['roleprivs'].keys())
#code2 = {roleprivs for roleprivs in result['roleprivs'].keys()}
#print(code2)
#return inventory, sites
for features in keys:
print(features)
上面的代码产生输出:
admin-appliance
admin-backupSettings
现在的问题是我如何在链中更深入一步并获取代码并访问 python 中的变量。
经过几个小时的测试和研究,我最终解决了这个问题...我遇到的主要问题是我如何在 roleprivs 之后进入下一个级别。我可以轻松地打印 roleprivs 下的主要元素,但是获取代码和访问元素有点困难。
我还把 运行 保存在一个错误中,其中索引需要是一个整数。这清理了我之前做的一些键并将其放入一个衬垫中。应该有助于清理我一直在使用的一些 for 循环。
for k, v in result['roleprivs'].items():
print("Code "+result['roleprivs'][k]['code'])
print("Access: "+result['roleprivs'][k]['access'])
access = result['roleprivs'][k]['access']
code = result['roleprivs'][k]['code']
payload = json.dumps({
"permissionCode": code,
"access": access
})
headers = {'Content-Type': 'application/json','Authorization': 'Bearer ' +bearerToken}
requests.request("PUT", url, verify=False, headers=headers, data=payload)
根据原始代码,我可能在 ./config/roles/ 目录中有多个角色。我需要确保我可以读取所有内容并在 for 循环中为每个内容进行迭代。这为我解决了。
最终输出:
2021-10-13 01:25:50,212:84:logger:role:genericRoleCreate:DEBUG:./config/roles/testDeveloper.yaml
2021-10-13 01:25:50,487:110:logger:role:genericRoleCreate:INFO:Get Role ID
8
Code admin-appliance
Access: full
Code admin-backupSettings
Access: full
正在尝试找到一种遍历 roleprivs 的方法,但在从 python 到达 yaml 的该级别时遇到问题。
testrole.yaml
info:
rolename: "testDeveloper"
desc: "Test Developer Role"
roletype: "user"
roleprivs:
admin-appliance:
name: "Administrate Appliance" # Informational Only Not used in code
description: "admin-appliance" # Informational Only Not used in code
code: "admin-appliance"
access: "full"
admin-backupSettings:
name: "Administrate Backup Settings" # Informational Only Not used in code
description: "admin-appliance" # Informational Only Not used in code
code: "admin-backupSettings"
access: "full"
我有几个不同的需求/用例。
- 下面脚本的第 1 部分 - 获取目录中的所有文件并获取角色名、描述符和角色类型并创建一个角色。
- 获取上面新建角色的角色ID。
- 需要帮助 - 返回原始 yaml 文件并对其进行迭代并仅获取 roleprivs..code 和 roleprivs..code --> 角色类型类似于 admin-appliance。请记住,大约有 50 种奇怪的功能需要根据访问类型进行更新。
问题: 如何将 yaml 文件中的代码和访问权限放入 python 变量中?
def genericRoleCreate(baseURL, bearerToken):
print("initial")
files = glob.glob(ROLES_DIR)
logger.debug('Roles Dir '+ROLES_DIR)
for file in files:
yaml_file = file
logger.debug(yaml_file)
with open(yaml_file) as f:
try:
result=yaml.safe_load(f)
authority = result['info']['rolename']
desc = result['info']['desc']
roletype = result['info']['roletype']
url = baseURL+"/api/roles"
payload= json.dumps({"role":{"authority": authority, "description": desc, "roletype": roletype}})
headers = {'Content-Type': 'application/json','Authorization': 'Bearer ' +bearerToken}
roleResult = requests.request("POST", url, verify=False, headers=headers, data=payload)
logger.debug(roleResult.text)
except yaml.YAMLError as exc:
logger.error(exc)
# Getting Role ID
try:
with open(yaml_file) as f:
result = yaml.safe_load(f)
authority = result['info']['rolename']
url = baseURL+"/api/roles?phrase="+authority
headers = {'Content-Type': 'application/json','Authorization': 'Bearer ' +bearerToken}
roleResult = requests.request("GET", url, verify=False, headers=headers )
#print(roleResult.text)
roleID = json.loads(roleResult.text)
role = roleID['roles'][0]['id']
#logger.debug(role)
logger.info("Get Role ID")
print(role)
#return role
#logger.debug("Role ID: "+role)
except Exception as e:
logger.error('Exception occurred', exc_info=True)
logger.error('Error getting roleID')
# Start Updating
#role = getRoleId(baseURL, bearerToken)
try:
with open(yaml_file) as f:
result = yaml.safe_load(f)
except Exception as e:
logger.error("Broken")
strRoleID = str(role)
url = baseURL+"/api/roles/"+strRoleID+"/update-permission"
#logger.debug(result)
keys = list(result.keys())
for features in keys:
#logger.debug(keys)
code = result[features]['code']
access = result[features]['access']
payload = json.dumps({
"permissionCode": code,
"access": access
})
headers = {'Content-Type': 'application/json','Authorization': 'Bearer ' +bearerToken}
requests.request("PUT", url, verify=False, headers=headers, data=payload)
请记住,我确实知道我应该将那个讨厌的大东西分解成多个函数——我在其他地方把它分解了——但当时把所有东西都编译成一个函数。
我一直在尝试多次迭代如何达到功能级别。我看了很多例子,但似乎无法弄清楚如何降到一个水平。
更新 1
try:
with open(yaml_file, 'r') as f:
result = yaml.safe_load(f)
except Exception as e:
logger.error("Broken")
strRoleID = str(role)
url = baseURL+"/api/roles/"+strRoleID+"/update-permission"
#logger.debug(result)
keys = list(result['roleprivs'].keys())
#code2 = {roleprivs for roleprivs in result['roleprivs'].keys()}
#print(code2)
#return inventory, sites
for features in keys:
print(features)
上面的代码产生输出:
admin-appliance
admin-backupSettings
现在的问题是我如何在链中更深入一步并获取代码并访问 python 中的变量。
经过几个小时的测试和研究,我最终解决了这个问题...我遇到的主要问题是我如何在 roleprivs 之后进入下一个级别。我可以轻松地打印 roleprivs 下的主要元素,但是获取代码和访问元素有点困难。
我还把 运行 保存在一个错误中,其中索引需要是一个整数。这清理了我之前做的一些键并将其放入一个衬垫中。应该有助于清理我一直在使用的一些 for 循环。
for k, v in result['roleprivs'].items():
print("Code "+result['roleprivs'][k]['code'])
print("Access: "+result['roleprivs'][k]['access'])
access = result['roleprivs'][k]['access']
code = result['roleprivs'][k]['code']
payload = json.dumps({
"permissionCode": code,
"access": access
})
headers = {'Content-Type': 'application/json','Authorization': 'Bearer ' +bearerToken}
requests.request("PUT", url, verify=False, headers=headers, data=payload)
根据原始代码,我可能在 ./config/roles/ 目录中有多个角色。我需要确保我可以读取所有内容并在 for 循环中为每个内容进行迭代。这为我解决了。
最终输出:
2021-10-13 01:25:50,212:84:logger:role:genericRoleCreate:DEBUG:./config/roles/testDeveloper.yaml
2021-10-13 01:25:50,487:110:logger:role:genericRoleCreate:INFO:Get Role ID
8
Code admin-appliance
Access: full
Code admin-backupSettings
Access: full