卷曲到 Python 以下载 GZ 文件?

Curl to Python to download a GZ file?

curl --location --request GET 'https://sampleurl/sample.log.gz' \
--header 'Authorization: Bearer XXXTokenXXX' \
--data-raw '{
    "enabled": true
}' | gunzip -c

我的要求是下载一个 gz 日志文件。以上是按预期工作的样本卷曲。如何将此添加到 python 代码?

编辑:原来有一个库专门解决这个问题。这是 gzip library, and a Whosebug post about this exact topic.


旧答案:您可以将 requests library by passing in custom headers 用作字典,然后将您的回复内容写入文件。

import requests
url = 'https://sampleurl/sample.log.gz'
headers = {'Authorization': 'Bearer XXXTokenXXX'}
response = requests.get(url, headers=headers)  # if the URL will redirect, include allow_redirects=True

with open('C:\path\to\save\to', 'wb') as file:
    file.write(response.content)

您可能需要修改它以使其适用于您的用例(特别是如果 --data-raw 位很重要),但这是一般的想法。如果您需要下载特别大的文件或想查看其他一些替代解决方案,可以查看此 older question.