> 使用python request库和OpenStack Restful
> APIs,在/root目录下,创建api.py文件,编写python代码,代码实现以下任务:
> (1)首先实现查询用户,如果用户名称“user_demo”已经存在,先删除。
> (2)如果不存在“user_demo”,创建该用户,密码设置为“jnxl2022”。
> (3)创建完成后,查询该用户信息,查询的body部分内容控制台输出,同时json格式的输出到文件当前目录下的user_demo.json文件中,json格式要求indent=4。
```python
import requests
import json
auth_url = "OpenStack_Identity_API_Endpoint"
username = "OpenStack_Username"
password = "OpenStack_Password"
project_name = "OpenStack_Project_Name"
def get_token():
headers = {'Content-Type': 'application/json'}
data = {
"auth": {
"identity": {
"methods": [
"password"
],
"password": {
"user": {
"name": username,
"domain": {
"name": "Default"
},
"password": password
}
}
},
"scope": {
"project": {
"name": project_name,
"domain": {
"name": "Default"
}
}
}
}
}
response = requests.post(f"{auth_url}/auth/tokens", headers=headers, json=data)
if response.status_code != 201:
raise Exception("Failed to get token")
return response.headers['X-Subject-Token']
def delete_user(token):
headers = {'X-Auth-Token': token}
response = requests.delete(f"{auth_url}/users/user_demo", headers=headers)
if response.status_code != 204:
raise Exception("Failed to delete user")
def create_user(token):
headers = {'X-Auth-Token': token, 'Content-Type': 'application/json'}
data = {
"user": {
"name": "user_demo",
"password": "jnxl2022",
"domain_id": "demo",
"enabled": True
}
}
response = requests.post(f"{auth_url}/users", headers=headers, json=data)
if response.status_code != 201:
raise Exception("Failed to create user")
def get_user_info(token):
headers = {'X-Auth-Token': token}
response = requests.get(f"{auth_url}/users/user_demo", headers=headers)
if response.status_code != 200:
raise Exception("Failed to get user info")
return response.json()
def main():
token = get_token()
try:
delete_user(token)
except Exception as e:
print(e)
create_user(token)
user_info = get_user_info(token)
print(json.dumps(user_info, indent=4))
with open("user_demo.json", "w") as f:
json.dump(user_info, f, indent=4)
if __name__ == "__main__":
main()
```