Search code examples
pythongziptornado

How to send a compressed file with an http POST with Tornado


I need to send a zipped JSON file with an HTTP request

def create_gzip():
    with open('articoli.json', 'rb') as f_in, gzip.open('articoli.json.gz', 'wb') as f_out:
        shutil.copyfileobj(f_in, f_out)
    return open('articoli.json.gz', 'rb')

body = create_gzip()
headers = tornado.httputil.HTTPHeaders({"content-type": "application/zip charset=utf-8"})
request = tornado.httpclient.HTTPRequest("http://localhost:8889/variazione", method='POST', headers=headers, body=body)
http_response = http_client.fetch(request)

But when I try to do so it gives the following error:

 TypeError: Expected bytes, unicode, or None; got <type 'file'>

How can I send the file? There is a way to make the request accept a gzip?


Solution

  • It was actually pretty simple: the body that you pass to the HTTPRequest must be:

    body=open('articoli.json.gz',"rb").read()
    tornado.httpclient.HTTPRequest("http://localhost:8889/variazione", method='POST', 
                                                     headers=headers, body=body)