Python发送长连接-获取长连接实时返回结果

需求背景:

有两个接口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,搜流式获取结果

Python爬虫中,登录后获取其他页面信息通常涉及到两个步骤:首先,登录并获取到包含cookies或者session信息的响应;然后,利用这些会话信息去访问受保护的资源。 以下是一个基本流程: 1. **模拟登录**: 使用像`requests`这样的库,发送POST请求到登录页面,携带用户名、密码以及可能需要的其他数据(如CSRF令牌)。登录成功后,服务器会返回一个带有cookie或session id的响应头。例如: ```python login_data = { 'username': 'your_username', 'password': 'your_password' } session = requests.Session() response = session.post('http://example.com/login', data=login_data) cookies = response.cookies ``` 2. **保存会话**: 你需要将cookies或session_id保存下来,以便后续的请求能带上这些信息。可以使用`requests`的`Session`对象来管理。 3. **带会话访问其他页面**: 使用已经登录的`session`对象来发起请求,这时其他页面可能会检查这个session的有效性。例如,获取信息的URL可能是`http://example.com/protected_page`: ```python protected_response = session.get('http://example.com/protected_page') ``` 4. **解析和提取信息**: 获取到的`response`对象包含了新的HTML内容,你可以使用如`BeautifulSoup`, `lxml`或`pandas`等工具解析HTML,提取所需的数据。 请注意,不同的网站可能有不同的验证机制,有的可能还会采用JWT(JSON Web Tokens)或其他形式的身份验证。在实际操作时,根据网站的具体结构进行调整。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值