1

I guess this is kind of a stupid question, but I have tried to search for the answere on google and here with no luck.

So I am connection to a API using a Get request with the http.client package.

The get request is sent to a adress with a ziped file. Sending the request goes ok, and I get a returned object. What I want to do next is to just save the returned file to a folder.

I have tried looking in the http.client documentation withount finding anything about it.

This is an example of how the code looks like. I have had to remove some of it for privacy reasons

conn = http.client.HTTPConnection("Adress to the server")

headers = {
    'cache-control': "no-cache",
    }

conn.request("GET", path_to_file + "?authTicket=" + ticket, 
headers=headers)

res = conn.getresponse()

return res

The code runs ok, but my problem is what to do next. If the returned data was just a normal json file I would just do something like:

data = res.read()
data = data.decode("uft-8")

And then be able to work with it inside the script. But I have no idea how to handel the ziped file that is returned. I would idealy like to unzip it before saving, but as a start it is ok to just save it to file.

Hope someone have a simple solution to this.

I did look a bit more into it, and when using the getheaders() on the returned object I get this:

[('Date', 'Wed, 19 Apr 2017 13:48:41 GMT'),
('Content-Type', 'application/octet-stream; charset=UTF-8'),
('Content-Disposition', 'attachment;filename=filename.csv.gz'),
('Content-Length', '2117014'),
('Server', 'Jetty(9.2.17.v20160517)')]

im not sure if that is relevant, but I guess I now would need a way to download the attachement.

4

1 回答 1

0

您可以在 Python 中轻松提取 zip 文件:

import requests
from zipfile import ZipFile
import io

my_request = requests.get(URL)
ficheiro = ZipFile(io.BytesIO(my_request.content))

ficheiro.extract('file_name')

您可以在此处获取有关zipfile模块和zipfile.ZipFile类的更多信息:

https://docs.python.org/3/library/zipfile.html

于 2017-04-19T14:10:24.147 回答