读取Http流

时间:2018-11-30 11:04:14

标签: python stream python-requests python-asyncio aiohttp

我正在尝试从流式API中读取数据,该数据使用分块传输编码发送。每个块可以有多个记录,每个记录都由CRLF分隔。并且数据始终使用gzip压缩发送。我正在尝试获取提要,然后一次进行一些处理。我已经看过一堆stackOverflow资源,但是找不到在Python中执行此操作的方法。在我的情况下,iter_content(chunk)大小在行上引发异常。

for chunk in api_response.iter_content(chunk_size=1024): 

在Fiddler(我用作代理)中,我看到数据正在不断下载,并在Fiddler中执行“ COMETPeek”,实际上,我可以看到一些示例json。

即使iter_lines也无效。我看过这里提到的asyncio和aiohttp案例:Why doesn't requests.get() return? What is the default timeout that requests.get() uses?

但不确定如何执行处理。如您所见,我已经尝试使用一堆python库。抱歉,某些代码可能包含一些我后来无法使用的库,因为它们无法解决问题。

我也查看了请求库的文档,但找不到任何实质内容。

如上所述,以下是我尝试执行的示例代码。任何指示我应该如何进行的指示都将受到高度赞赏。

这是我第一次尝试读取流

from oauthlib.oauth2 import BackendApplicationClient
from requests_oauthlib import OAuth2Session
import requests
import zlib
import json

READ_BLOCK_SIZE = 1024*8

clientID="ClientID"
clientSecret="ClientSecret"

proxies = {
"https": "http://127.0.0.1:8888",
}

client = BackendApplicationClient(client_id=clientID)
oauth = OAuth2Session(client=client)

token = oauth.fetch_token(token_url='https://baseTokenURL/token', client_id=clientID,client_secret=clientSecret,proxies=proxies,verify=False) 

auth_t=token['access_token']
#auth_t = accesstoken.encode("ascii", "ignore")

headers = {
'authorization': "Bearer " + auth_t,
'content-type': "application/json",
'Accept-Encoding': "gzip",
}
dec=zlib.decompressobj(32 + zlib.MAX_WBITS)

try:
    init_res = requests.get('https://BaseStreamURL/api/1/stream/specificStream', headers=headers, allow_redirects=False,proxies=proxies,verify=False)
    if init_res.status_code == 302:
        print(init_res.headers['Location'])
        api_response = requests.get(init_res.headers['Location'], headers=headers, allow_redirects=False,proxies=proxies,verify=False, timeout=20, stream=True,params={"smoothing":"1", "smoothingBucketSize" : "180"})
        if  api_response.status_code == 200:
            #api_response.raw.decode_content = True

            #print(api_response.raw.read(20))
            for chunk in api_response.iter_content(chunk_size=api_response.chunk_size): 
                #Parse the response
    elif init_res.status_code == 200:
        print(init_res.content)
except Exception as ce:
    print(ce)

更新 我现在正在看这个:https://aiohttp.readthedocs.io/en/v0.20.0/client.html

那会是路吗?

2 个答案:

答案 0 :(得分:0)

以防万一有人觉得有用。我找到了一种使用aiohttp从api通过python流式传输的方法。下面是骨架。请记住,这只是一个骨架,它通过不断向我展示结果而起作用。如果有人有更好的方法-我全神贯注,因为这是我第一次尝试顺其自然。

async def fetch(session, url, headers):
    with async_timeout.timeout(None):
        async with session.get(init_res.headers['Location'], headers=headers, proxy="http://127.0.0.1:8888", allow_redirects=False,timeout=None) as r:
            while True:
                chunk=await r.content.read(1024*3)
                if not chunk:
                    break                    
                print(chunk)

async def main(url, headers):
    async with aiohttp.ClientSession() as session:
        html = await fetch(session, url,headers)

在呼叫者中

try:
    init_res = requests.get('https://BaseStreamURL/api/1/stream/specificStream', headers=headers, allow_redirects=False,proxies=proxies,verify=False)
    if init_res.status_code == 302:
        loc=init_res.headers['Location']
        loop = asyncio.get_event_loop()
        loop.run_until_complete(main(loc, headers=headers))
    elif init_res.status_code == 200:
        print(init_res.content)
except Exception as ce:
    print(ce)

答案 1 :(得分:0)

我已经从堆栈溢出的答案中实现了以下几点 下面为我​​工作。

 MAX_REDIRECTS =1000
        def get_data(url, **kwargs):
            import requests
            kwargs.setdefault('allow_redirects', False)
            for i in range(0, MAX_REDIRECTS):
                response = requests.get(url, **kwargs)
#check for response codes to check if redirects happedned
                if response.status_code == requests.codes.moved or \
                   response.status_code == requests.codes.found:
                    if 'Location' in response.headers:
                        url = response.headers['Location']
                        content_type_header = response.headers.get('content_type')
                        continue
                    else:
                        print ("problem reading")
                return response

在您的行中调用上述功能

init_res = requests.get('https://BaseStreamURL/api/1/stream/specificStream', headers=headers, allow_redirects=False,proxies=proxies,verify=False)

init_res = get_data('https://BaseStreamURL/api/1/stream/specificStream',stream=True, headers=headers,params=payload)