Last active
December 10, 2015 12:14
-
-
Save moritzschaefer/f4080aec001826f6c496 to your computer and use it in GitHub Desktop.
Upload and share to Seafile. Command line tool using Web API
This file contains hidden or 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
| #!/usr/bin/env python3 | |
| import sys | |
| import requests | |
| import getpass | |
| try: | |
| host = sys.argv[1] | |
| library = sys.argv[2] | |
| username = sys.argv[3] | |
| filename = sys.argv[4] | |
| except IndexError: | |
| print('Usage: <host> <library> <username> <file> [password]') | |
| sys.exit(1) | |
| try: | |
| password = sys.argv[5] | |
| except IndexError: | |
| password = getpass.getpass() | |
| # get token | |
| response = requests.post('{host}/api2/auth-token/'.format(host=host), | |
| data={'username': username, 'password': password}) | |
| try: | |
| token = response.json()['token'] | |
| except KeyError: | |
| print('Credentials wrong') | |
| sys.exit(1) | |
| auth_header = {'Authorization': 'Token {token}'.format(token=token)} | |
| # get libraries | |
| libraries = requests.get('{host}/api2/repos/'.format(host=host), | |
| headers=auth_header).json() | |
| try: | |
| repoid = [l['id'] for l in libraries if l['name'] == library][0] | |
| except IndexError: | |
| print('Library doesn\'t exist. Available libraries:') | |
| print(', '.join([l['name'] for l in libraries])) | |
| sys.exit(1) | |
| uploadlink = requests.get( | |
| '{host}/api2/repos/{repoid}/upload-link/'.format(host=host, repoid=repoid), | |
| headers=auth_header) \ | |
| .text.strip('"') | |
| response = requests.post(uploadlink, | |
| data={'filename': filename, 'parent_dir': '/'}, | |
| files={'file': open(filename, 'rb')} | |
| ) | |
| if response.status_code != 200: | |
| print('Error uploading file: {}'.format(response.text)) | |
| sys.exit(1) | |
| # now create shared link | |
| response = requests.put('{host}/api2/repos/{repoid}/file/shared-link/' | |
| .format(host=host, repoid=repoid), | |
| data={'p': '/{}'.format(filename)}, | |
| headers=auth_header) | |
| if response.status_code == 201: | |
| print(response.headers['Location']) | |
| else: | |
| print('Error sharing uploaded file: {}'.format(response.text)) | |
| sys.exit(1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment