You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

http_put.py 1.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. #!/usr/bin/env python3
  2. """
  3. Small script to upload file using HTTP PUT
  4. """
  5. import argparse
  6. import os
  7. import sys
  8. import requests
  9. def main():
  10. parser = argparse.ArgumentParser(
  11. description='Upload a file usgin HTTP PUT method',
  12. epilog=(
  13. "To use HTTP Auth set HTTP_PUT_AUTH environment variable to user:password\n"
  14. "Example: %(prog)s file1 file2 https://example.com/dir/"))
  15. parser.add_argument(
  16. "file", type=argparse.FileType('rb'), nargs='+', help="File to upload")
  17. parser.add_argument(
  18. "dir_url", help="Remote URL (path to a directory, must include a trailing /)")
  19. args = parser.parse_args()
  20. if not args.dir_url.endswith('/'):
  21. parser.error("URL must end with /")
  22. http_auth = os.getenv('HTTP_PUT_AUTH')
  23. if http_auth:
  24. user, password = http_auth.split(':')
  25. auth = (user, password)
  26. else:
  27. auth = None
  28. exit_code = 0
  29. for fh in args.file:
  30. try:
  31. r = requests.put(args.dir_url + fh.name, data=fh, auth=auth, timeout=(45, 90))
  32. r.raise_for_status()
  33. print("{} uploaded to {}".format(fh.name, r.url))
  34. except (requests.exceptions.ConnectionError,
  35. requests.exceptions.HTTPError) as err:
  36. print(err, file=sys.stderr)
  37. exit_code = 1
  38. return exit_code
  39. if __name__ == '__main__':
  40. sys.exit(main())