Created
August 14, 2019 08:25
-
-
Save hargikas/fe716f841bdf6b4b84f36cf650aa1527 to your computer and use it in GitHub Desktop.
A simple python script for uploading files to transfer.sh
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import argparse | |
import io | |
import os | |
from pathlib import Path | |
import progressbar | |
import requests | |
from requests_toolbelt.streaming_iterator import StreamingIterator | |
TRANSFER_SH = 'https://transfer.sh/%s' | |
DEFAULT_SSL_SIZE = 0x20000 # 131072 bytes, default max ssl buffer size | |
def read_in_chunks(file_to_upload, file_size, chunk_size=DEFAULT_SSL_SIZE): | |
"""Lazy function (generator) to read a file piece by piece. | |
Display a progress bar while reading""" | |
widgets = ['Uploading %s:' % (file_to_upload.name), ' ', progressbar.Bar(), ' ', progressbar.AdaptiveETA( | |
), ' ', progressbar.AdaptiveTransferSpeed(), ' ', progressbar.DataSize(), ' '] | |
with io.open(str(file_to_upload), 'rb') as fin, progressbar.ProgressBar(max_value=file_size, widgets=widgets) as bar: | |
cur_size = 0 | |
while True: | |
data = fin.read(chunk_size) | |
cur_size += len(data) | |
if not data: | |
break | |
bar.update(cur_size) | |
yield data | |
def StreamingFile(file_to_upload): | |
file_path = str(file_to_upload) | |
file_size = os.path.getsize(file_path) | |
return StreamingIterator(file_size, read_in_chunks(file_to_upload, file_size)) | |
def upload_to_transfer_sh(file_to_upload): | |
result = None | |
url = TRANSFER_SH % (file_to_upload.name) | |
response = requests.put(url, data=StreamingFile(file_to_upload)) | |
if response.status_code == 200: | |
result = str(response.text).strip() | |
return result | |
if __name__ == "__main__": | |
parser = argparse.ArgumentParser(description='Upload some files') | |
parser.add_argument('files', metavar='file', type=str, | |
nargs='+', help='a file to upload') | |
args = parser.parse_args() | |
for c_file in args.files: | |
file_to_upload = Path(c_file) | |
url = upload_to_transfer_sh(file_to_upload) | |
print("Download link:", url) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment