Skip to content

Instantly share code, notes, and snippets.

@sajalshres
Last active January 5, 2021 04:11
Show Gist options
  • Save sajalshres/7059d1fb4cdfbd025cea008b25743185 to your computer and use it in GitHub Desktop.
Save sajalshres/7059d1fb4cdfbd025cea008b25743185 to your computer and use it in GitHub Desktop.
A simple file upload utility in Python

File Upload

A simple module to upload file to an endpoint

Usage

❯ python .\file_upload.py -h
usage: file_upload.py [OPTIONS] [FILE]...

Upload file to a graphql api

positional arguments:
  file                  path of the file to upload

optional arguments:
  -h, --help            show this help message and exit
  -v, --version         show program's version number and exit

required arguments:
  -d DOMAIN, --domain DOMAIN
                        Base domain of the api
  -t TOKEN, --token TOKEN
                        token for authentication
import os
import sys
import argparse
from typing import IO
import requests
from requests.exceptions import HTTPError
__author__ = "Sajal N. Shrestha"
__status__ = "Development"
__version__ = "0.1.0"
def parse_argument() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(
usage="%(prog)s [OPTIONS] [FILE]...", description="Upload file to a graphql api"
)
# positional argument
parser.add_argument(
"file", type=argparse.FileType("r"), help="path of the file to upload"
)
# optional argument
parser.add_argument(
"-v", "--version", action="version", version=f"{parser.prog} {__version__}"
)
parser.add_argument(
"-t",
"--token",
dest="token",
help="token for authentication or environment variable TOKEN",
)
# required argument
required_arguments = parser.add_argument_group("required arguments")
required_arguments.add_argument(
"-d", "--domain", dest="domain", required=True, help="base domain of the api",
)
return parser
def parse_url(domain: str) -> str:
# TODO: WIP
return f"https://{domain}/api/graphql"
def file_upload(domain: str, token: str, file: IO) -> None:
url = parse_url(domain=domain)
headers = {
"authority": domain,
"authorization": f"Bearer {token}",
"content-type": "application/json",
}
try:
request = requests.post(url, headers=headers, files={"file": file})
request.raise_for_status()
if request.status_code == requests.codes.ok:
print("File has been successfully uploaded")
else:
print("Something went wrong!!!")
except (
requests.exceptions.ConnectionError,
requests.exceptions.HTTPError,
requests.exceptions.RequestException,
) as error:
print("Unexpected exception occurred: ", error)
def main() -> None:
parser = parse_argument()
args = parser.parse_args()
token = os.environ.get("TOKEN", args.token)
if not token:
print(
"error: environment variable 'TOKEN' or following arguments are required: -t/--token"
)
sys.exit(1)
file_upload(domain=args.domain, token=token, file=args.file)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment