小代码---http请求信息写入文件

python3版本

import datetime
import requests
import os
import time

log_name="client-quality.log"

def appendStrToFile(filePath, string):
with open(filePath, "ab") as f:
f.write(string)

def create_log_file(filePath):
if os.path.exists(filePath):
os.remove(filePath)
f = open(filePath, 'w')
f.close()

if __name__ == '__main__':
create_log_file(log_name)
for i in range(10000):
time_now = datetime.datetime.now()
appendStrToFile(log_name,str.encode(time_now.strftime("%Y-%m-%d %H:%M:%S") + ' '))
time_to = (time_now+datetime.timedelta(minutes=-5)).strftime("%Y-%m-%d %H:%M:%S")
time_from = (time_now+datetime.timedelta(days=-14,minutes=-5)).strftime("%Y-%m-%d %H:%M:%S")

url1 = "http://ip/xxx/api/v1/search_info?server_zone=internal"
body_profile ='{"time":["'+ time_from +'","'+ time_to +'"],"xxxxx":"memory","xxxx":[0,1,2],"xxxx":"avg"}'
r=requests.post(url1, data=body_profile)
#print(r.text)
log=url1+": "+str(r.elapsed.total_seconds())+" "
appendStrToFile(log_name,str.encode(log))
#print(r.elapsed.total_seconds())

原文地址:https://www.cnblogs.com/to-here/p/13344875.html