需求背景:
有两个接口A和B,A是长链接,请求方法是get,B是普通的post请求,B发起请求后数据C会先返回到长连接请求然后再返回到请求B。
设计思路:
整体思路:由于A和B的响应时间都比较长,先发请求B,然后发请求A,长连接请求流程:先new一个session对象,建立链接,然后不断请求获取长连接返回数据。
最终代码实现:
def A(environment,cf,token):
print("开始建立长连接......")
url = "https://" + cf["host"][environment] + cf["path"]["directives"]
print("url:",url)
headers = {
'Authorization': "Bearer "+ str(token),
'Device-Id': "test_device_222",
'Content-Type': "Bearer "+ str(token),
'User-Agent': "PostmanRuntime/7.15.2",
'Accept': "*/*",
'Cache-Control': "no-cache",
'Postman-Token': "10731c98-e876-49e0-9b69-543b55a47be0,6a238e6a-6d64-4dce-874b-58049dbc50a5",
'Host': cf["host"][environment],
'Accept-Encoding': "gzip, deflate",
'Connection': "keep-alive",
'cache-control': "no-cache"
}
client = requests.session() #返回的是session()对象
while True:
print("===================【%sA开始请求】==================" % time.asctime(time.localtime(time.time())))
#建一个长连接
r = client.get(url,headers=headers,verify=False,stream=True)
delimiter = "--------test_device_222".encode("utf-8")
for line in r.iter_lines(delimiter=delimiter):
if line:
decoded_line = line.decode('utf-8')
print(decoded_line)
#发起post请求,接口B
def B(url,cf,token,environment,metadata_json ):
pcmfile = cf["path"]["pcmfile"]
headers = {
'Device-Id': 'test_device_222',
'Authorization': 'Bearer ' + token,
}
metadata_json['event']['header']['messageId'] = "test-" + str(uuid.uuid4())
body = json.dumps(metadata_json)
#打开本地pcm文件,读取数据,写入body中
pcm_file = {'metadata': body,'audio': (pcmfile, open(pcmfile, 'rb').read(), 'application/octet-stream')}
print("================【B 请求开始时间:%s】=================="%time.asctime( time.localtime(time.time())))
response = requests.post(url, files=pcm_file, headers=headers,verify=False)
#如果请求报错401,说明token过期,重新获取发起请求
if response.status_code==401:
multipart_data = B(url,cf,token,environment)
else:
multipart_data = decoder.MultipartDecoder.from_response(response)
print("================【B 请求结束时间:%s】=================="%time.asctime( time.localtime(time.time())))
说明点:
a. 获取长连接返回数据时,发起get请求必须要加的参数是“stream”,由于我测试的请求是https请求,需要在方法中加上参数“verify=False”,关闭ssl证书校验。
b. 很多模块没导入,pycharm会弹出提示的,装上就可以了
c. cf 是我自己定义的字典变量,用来写配置,因为配置比较少,我暂时写在了代码中
主要想说明长连接请求的发送,其他的就不详细赘述了
参考文档:https://2.python-requests.org//en/latest/user/advanced/#streaming-requests,搜流式获取结果