【问题标题】:Python Requests Stream Data from APIPython 从 API 请求流数据
【发布时间】:2019-12-21 04:42:36
【问题描述】:

用例:我正在尝试连接到流式 API,提取这些事件,过滤它们并保存相关事件。

问题:我的代码运行良好,直到大约 1100 次响应。在这一点之后,代码不会崩溃,但它似乎停止从流中提取更多数据。我猜这是某种缓冲问题,但老实说流媒体对我来说是新的,我不知道是什么导致了这个问题。

代码

import requests
def stream():
    s = requests.Session()
    r = s.get(url, headers=headers, stream=True)
    for line in r.iter_lines():
        if line:
            print(line)

我也在没有会话对象的情况下尝试过这个,我得到了相同的结果。

是否有我忽略的参数或我不知道的概念?我已经搜索了文档/互联网,但没有任何东西对我产生影响。

非常感谢任何帮助。

编辑 在我看来一切都正确我认为流在初始连接时只会生成大量事件,然后它们会减慢速度。然而,现在的问题是,在连接几分钟后,我收到了这个错误:

Traceback (most recent call last):
  File "C:\Users\joe\PycharmProjects\proj\venv\lib\site-packages\urllib3\response.py", line 572, in _update_chunk_length
    self.chunk_left = int(line, 16)
ValueError: invalid literal for int() with base 16: b''

【问题讨论】:

    标签: python python-3.x api python-requests


    【解决方案1】:

    遵循"Body Content Workflow"requests 库)部分的流数据指南。

    示例方法:

    import requests
    
    def get_stream(url):
        s = requests.Session()
    
        with s.get(url, headers=None, stream=True) as resp:
            for line in resp.iter_lines():
                if line:
                    print(line)
    
    url = 'https://jsonplaceholder.typicode.com/posts/1'
    get_stream(url)
    

    输出:

    b'{'
    b'  "userId": 1,'
    b'  "id": 1,'
    b'  "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",'
    b'  "body": "quia et suscipit\\nsuscipit recusandae consequuntur expedita et cum\\nreprehenderit molestiae ut ut quas totam\\nnostrum rerum est autem sunt rem eveniet architecto"'
    b'}'
    

    【讨论】:

      【解决方案2】:

      您可能会受到速率限制。尝试打印请求对象的状态码。

      例如,在您的代码中:

      import requests
      def stream():
          s = requests.Session()
          r = s.get(url, headers=headers, stream=True)
          print(r.status_code)
          for line in r.iter_lines():
              if line:
                  print(line)
      

      运行此程序,直到获得第 1100 个响应。您正在调用的服务可能有速率限制。如果您收到 429 响应,则意味着您必须等待一段时间才能继续拨打电话。

      【讨论】:

        猜你喜欢
        • 2021-06-19
        • 1970-01-01
        • 1970-01-01
        • 2017-08-15
        • 1970-01-01
        • 1970-01-01
        • 2015-10-11
        • 1970-01-01
        • 2021-10-06
        相关资源
        最近更新 更多