Python 需要将响应保存到文件,并在终端中打印状态
我试图将requests.post()响应的状态保存到一个文件中,并在终端中打印它。我在文件中有一个主机名列表,因此捕获到一个异常,它出现并且不会继续循环。他怎样才能达到预期的行动Python 需要将响应保存到文件,并在终端中打印状态,python,python-3.x,python-requests,Python,Python 3.x,Python Requests,我试图将requests.post()响应的状态保存到一个文件中,并在终端中打印它。我在文件中有一个主机名列表,因此捕获到一个异常,它出现并且不会继续循环。他怎样才能达到预期的行动 with open(file_input,'r') as f: content = f.readlines() try: for x in content: url='https://url/a/b/c/{}'.format(x.strip()) payload=(
with open(file_input,'r') as f:
content = f.readlines()
try:
for x in content:
url='https://url/a/b/c/{}'.format(x.strip())
payload=('{{"ip-address": "x.x.x.x","user-name": "john","password": str(Pass),"db-name": str(x.strip()),"service-name": "y","port": "y","connection-string": "y"}}')
response = requests.post(url,json=payload,header=add_cookie)
print(response.text)
response.raise_for_status()
except requests.exceptions.HTTPError as e:
# Whoops it wasn't a 200
print ("Error: " + str(e))
# Must have been a 200 status code
json_obj = response.json()
print (json_obj)
with open('response.txt',mode='wb') as localfile:
localfile.write(response.text)
打开(文件输入,'r')作为f:
content=f.readlines()
对于内容中的x:
url='1〕https://url/a/b/c/{}.格式(x.strip())
有效负载=(“{”ip地址“:”x.x.x.x“,”用户名“:”john“,”密码“:str(Pass),”db名称“:str(x.strip()),”服务名称“:”y“,”端口“:”y“,”连接字符串“:”y“}”)
尝试:
response=requests.post(url,json=payload,header=add\u cookie)
打印(response.text)
打印(响应状态\ U代码)
除异常作为错误外:
打印(“错误:+str(错误))
将open('errors.txt',mode='a')作为f:
f、 写入(str(err))
持续
json_obj=response.json()
打印(json_obj)
打开('response.txt',mode='wb')作为本地文件:
localfile.write(response.text)
可以更轻松地实现:
导入请求
打开(文件输入,“r”)作为f:
file_url=f.readlines()#将所有URL读入列表
对于文件\u url中的url\u后缀:
url='1〕https://url/a/b/c/{}.格式(url_后缀.strip())
payload={#不是JSON表示形式中的上一个有效负载
“ip地址”:“x.x.x.x”,
“用户名”:“john”,
“密码”:str(Pass),
“db名称”:str(x.strip()),
“服务名称”:“y”,
“端口”:“y”,
“连接字符串”:“y”,
}
response=requests.post(url,json=payload,header=add\u cookie)
如果response.ok:
打印(“JSON接收:”)
打印(response.json())#注意:验证响应是否为json
使用open('response.txt','a')作为本地文件:#注意:追加模式!
localfile.write(response.text)
其他:#状态代码4XX/5XX
打印(“获取url时出错”、url、r.status\U代码、r.text)
请注意,
requests.post()的dict
到json=
参数。您的有效负载
是一个格式奇怪的字符串。出现了什么错误?请将代码放入块中的循环中,然后尝试除
块之外的操作。要写入响应,请在写入模式下打开一个文件并提供数据。我得到了json_obj=response.json()的json解码错误。或response.txt未定义。上面编辑的循环是否可以修复缩进