请检查我的Python代码,以便使用requests库进行HTTP操作,并提供任何可能的改进指针。
import requests
token = input()
payload={}
headers = {
"Accept": "application/yang-data+json",
"Content-Type": "application/yang-data+json",
"Authorization": "Bearer {}".format(token),
}
url = "https://sandbox-xxxx.cisco.com/restconf/data/native/router/bgp"
try:
response = requests.get(url, headers=headers, data=payload, verify=False, timeout=10)
except requests.exceptions.HTTPError as errh:
print(f"An HTTP Error occured: {errh}")
except requests.exceptions.ConnectionError as errc:
print(f"An Error Connecting to the API occured: {errc}")
except requests.exceptions.Timeout as errt:
print(f"A Timeout Error occured: {errt}")
except requests.exceptions.RequestException as err:
print(f"An Unknown Error occured: {err}")
else:
print(response.status_code)
print(response.json())发布于 2022-05-13 13:24:33
既然这是整个剧本,
curl;对于不同的异常类型,分离您的excepts并没有很大的价值。这是为数不多的几个使用案例之一,在这种情况下,except Exception并不是一个坏主意。如果使用repr()格式说明符打印异常对象的!r,它将显示异常类型和内容,同时省略跟踪。如果您确实希望看到跟踪,只需完全删除您的try/except,并让默认打印生效。
occured拼写为occurred。
不要调用input()提示符。
verify=False是危险的。如果证书没有有效的信任链,则应该在操作系统或requests中提取证书并显式信任它。
考虑使用pprint打印JSON文档。
打印状态代码时,还应打印原因字符串。
from pprint import pprint
import requests
token = input('Please enter your bearer authentication token: ')
sandbox = input('Please enter your sandbox ID: ')
headers = {
"Accept": "application/yang-data+json",
"Content-Type": "application/yang-data+json",
"Authorization": "Bearer " + token,
}
try:
with requests.get(
url=f"https://sandbox-{sandbox}.cisco.com/restconf/data/native/router/bgp",
headers=headers,
data={},
verify=False,
timeout=10,
) as response:
doc = response.json()
except Exception as e:
print(f'An error occurred: {e!r}')
else:
print(response.status_code, response.reason)
pprint(doc)https://codereview.stackexchange.com/questions/276495
复制相似问题