2 # -*- coding: utf-8 -*-
7 from os
.path
import getsize
, basename
8 from hashlib
import md5
10 __author__
= "Alfonso Tierno, alfonso.tiernosepulveda@telefonica.com"
11 __date__
= "$2018-01-01$"
13 version_date
= "Jan 2018"
17 print("Usage: ", sys
.argv
[0], "[options]")
18 print(" --version: prints current version")
19 print(" -f|--file FILE: file to be sent")
20 print(" -h|--help: shows this help")
21 print(" -u|--url URL: complete server URL")
22 print(" -s|--chunk-size SIZE: size of chunks, by default 1000")
23 print(" -t|--token TOKEN: Authorizaton token, previously obtained from server")
24 print(" -v|--verbose print debug information, can be used several times")
28 if __name__
== "__main__":
30 # load parameters and configuration
31 opts
, args
= getopt
.getopt(sys
.argv
[1:], "hvu:s:f:t:",
32 ["url=", "help", "version", "verbose", "file=", "chunk-size=", "token="])
41 print("upload version " + __version__
+ ' ' + version_date
)
43 elif o
in ("-v", "--verbose"):
45 elif o
in ("-h", "--help"):
48 elif o
in ("-u", "--url"):
50 elif o
in ("-s", "--chunk-size"):
52 elif o
in ("-f", "--file"):
54 elif o
in ("-t", "--token"):
57 assert False, "Unhandled option"
58 total_size
= getsize(pkg_file
)
62 with
open(pkg_file
, 'rb') as f
:
64 "Content-type": "application/gzip",
65 "Content-Filename": basename(pkg_file
),
66 "Accept": "application/json",
69 headers
["Authorization"] = token
70 while index
< total_size
:
71 chunk_data
= f
.read(chunk_size
)
72 file_md5
.update(chunk_data
)
73 # payload = {"file_name": pkg_file, "chunk_data": base64.b64encode(chunk_data).decode("utf-8"),
74 # "chunk_size": chunk_size}
76 headers
["Transaction-Id"] = transaction_id
77 if index
+len(chunk_data
) == total_size
:
78 headers
["Content-File-MD5"] = file_md5
.hexdigest()
79 # payload["id"] = transaction_id
80 headers
["Content-range"] = "bytes {}-{}/{}".format(index
, index
+len(chunk_data
)-1, total_size
)
81 # refers to rfc2616: https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
83 print("TX chunk Headers: {}".format(headers
))
84 r
= requests
.post(url
, data
=chunk_data
, headers
=headers
, verify
=False)
85 if r
.status_code
not in (200, 201):
86 print("Got {}: {}".format(r
.status_code
, r
.text
))
89 print("RX {}: {}".format(r
.status_code
, r
.text
))
91 if not transaction_id
:
92 transaction_id
= response
["id"]
93 index
+= len(chunk_data
)
95 print("RX {}: {}".format(r
.status_code
, r
.text
))
97 print("---\nid: {}".format(response
["id"]))
98 except Exception as e
: