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