我正在尝试以下代码,它以静态方式正常工作。 我希望它更具动态性 以下是我的代码
url = 'abcxzy.com'
r1 = request.post(url,header={'Cookie':'xyz'}
r2 = request.post(url,header={'Cookie':'abcd'}
try:
r1.json()
print("Receving JSON from server 1")
r2.json()
print("Receving JSON from server 2")
except:
print("Server 1 is down")
print("Server 1 is down")
我有两个问题: 将来,如果有更多的服务器验证假设大约100,那么什么是最好的方法。 并且唯一没有响应JSON请求的服务器必须转到异常块并打印该语句只是为了不响应JSON服务器名称,当前,如果任何服务器没有获得JSON响应,它将进入异常块并打印两个print语句。
答案 0 :(得分:1)
您需要为每个网址使用某种循环,以确保为每个网址执行相同的操作。
我无法测试任何这些,所以以下只是为了给你一个想法:
# list of dictionaires, containling both url and cookie
urls = [{'url':'abc.com', 'cookie':'bla1'},
{'url':'def.com', 'cookie':'bla2'},
{'url':'ghi.com', 'cookie':'bla3'}]
#declare a variable/list for your responses
responses = []
# for each dictionary in the list, loop through
# and do the request/json
for url in urls:
try:
r = request.post(url['url'],header={'Cookie':url['cookie']})
# append your json to the responses list
responses.append(r.json())
except:
print('Something wrong with {} using {} cookie'.format(url['url'], url['cookie']))
for response in responses:
print(response)
但是你应该做的是捕获exception
语句中的特定except
,而不仅仅是全面捕获。您应该查看r.status_code
块中的except
以及r.raise_for_status()
块中的except