curl的Python版本——输出



我有一个GitLab API(v4(,我需要调用它来获得一个项目子目录(在v.14.4中有一些明显的新内容,它似乎还没有包括python-GitLab libs(,这在curl中可以用以下命令完成:

curl --header "PRIVATE-TOKEN: A_Token001" http://192.168.156.55/api/v4/projects/10/repository/archive?path=ProjectSubDirectory --output ~./temp/ProjectSubDirectory.tar.gz

问题在最后一部分,--output ~./GitLab/some_project_files/ProjectSubDirectory.tar.gz

我尝试了不同的方法(.content,.text(,但都失败了,比如:

...
response = requests.get(url=url, headers=headers, params=params).content
# and save the respon content with with open(...)

但在所有情况下,它都保存了一个无效的tar.gz文件或其他问题。

我甚至试过https://curlconverter.com/,但它生成的代码不能正常工作,它似乎恰恰忽略了--output参数,没有显示任何关于文件本身的信息:

headers = {'PRIVATE-TOKEN': 'A_Token001',}
params = (('path', 'ProjectSubDirectory'),)
response = requests.get('http://192.168.156.55/api/v4/projects/10/repository/archive', headers=headers, params=params)

目前,我只是创建了一个脚本,并用子进程调用它,但我不太喜欢这种方法,因为Python有库作为请求,我想应该有一些方法来做同样的事情。。。

两个关键事项。

  1. 允许重定向
  2. 在写入文件之前,请使用raise_for_status()确保请求成功。这将有助于发现其他潜在问题,如身份验证失败

之后,将response.content写入以二进制模式打开的文件以写入('wb'(

import requests
url = "https://..."
headers = {} # ...
paramus = {} # ...
output_path = 'path/to/local/file.tar.gz'
response = requests.get(url, headers=headers, params=params, allow_redirects=True)
response.raise_for_status() # make sure the request is successful
with open(output_path, 'wb') as f:
f.write(response.content)

最新更新