How to get the raw content of a response in requests with Python?

前端 未结 3 1055
北恋
北恋 2020-12-09 09:25

Trying to get the raw data of the HTTP response content in requests in Python. I am interested in forwarding the response through another channel, which means t

3条回答
  •  孤城傲影
    2020-12-09 09:55

    To add to @brien answer, as stated in the docs:

    In general, however, you should use a pattern like this to save what is being streamed to a file:

    with open(filename, 'wb') as fd:
       for chunk in r.iter_content(chunk_size=128):
          fd.write(chunk)
    

    Using Response.iter_content will handle a lot of what you would otherwise have to handle when using Response.raw directly. When streaming a download, the above is the preferred and recommended way to retrieve the content. Note that chunk_size can be freely adjusted to a number that may better fit your use cases.

    That pattern not only has the advantages described above, but is also a good to fetch data in environments with limited memory.

提交回复
热议问题