如何使用 Tornado 发送带有 http POST 的压缩文件
How to send a compressed file with an http POST with Tornado
我需要发送带有 HTTP 请求的压缩 JSON 文件
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)
但是当我尝试这样做时出现以下错误:
TypeError: Expected bytes, unicode, or None; got <type 'file'>
如何发送文件?有没有办法让请求接受 gzip?
您的 body
包含一个文件,而不是实际数据。试试这个:
gzip_file = create_gzip()
body = bytearray(gzip_file.read())
其实很简单:传递给 HTTPRequest
的 body
必须是:
body=open('articoli.json.gz',"rb").read()
tornado.httpclient.HTTPRequest("http://localhost:8889/variazione", method='POST',
headers=headers, body=body)
我需要发送带有 HTTP 请求的压缩 JSON 文件
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)
但是当我尝试这样做时出现以下错误:
TypeError: Expected bytes, unicode, or None; got <type 'file'>
如何发送文件?有没有办法让请求接受 gzip?
您的 body
包含一个文件,而不是实际数据。试试这个:
gzip_file = create_gzip()
body = bytearray(gzip_file.read())
其实很简单:传递给 HTTPRequest
的 body
必须是:
body=open('articoli.json.gz',"rb").read()
tornado.httpclient.HTTPRequest("http://localhost:8889/variazione", method='POST',
headers=headers, body=body)