Fix Stacktrace on missing or bad file path.
import json
import ntpath
+import os
import requests
+import sys
from .api import Api
+
def path_leaf(path):
head, tail = ntpath.split(path)
return tail or ntpath.basename(head)
+def load_data_files(data, attributes):
+ files = {}
+ exit_msg = {'message': []}
+ exit = False
+
+ for attribute in attributes:
+ if attribute not in data:
+ exit = True
+ exit_msg['message'].append("The \'%s\' attribute has no file associated with it." % attribute)
+ else:
+ if os.path.exists(data[attribute]):
+ files[attribute] = open(data[attribute], 'rb')
+ else:
+ exit = True
+ exit_msg['message'].append("The \'%s\' attribute file (%s) does not exit." % (attribute, data[attribute]))
+
+ return files, exit, exit_msg
+
+
class Add(Api):
"""Add asset"""
@@ -28,34 +50,27 @@ class Add(Api):
except:
raise Exception('Invalid args. Please review help')
- # TODO add try except on this part of the code
- files = {}
+ exit = False
+
if asset == 'dataset':
- files = {
- 'data_opener': open(data['data_opener'], 'rb'),
- 'description': open(data['description'], 'rb')
- }
+ files, exit, exit_msg = load_data_files(data, ['data_opener', 'description'])
elif asset == 'challenge':
- files = {
- 'metrics': open(data['metrics'], 'rb'),
- 'description': open(data['description'], 'rb')
- }
+ files, exit, exit_msg = load_data_files(data, ['metrics', 'description'])
elif asset == 'algo':
- files = {
- 'file': open(data['file'], 'rb'),
- 'description': open(data['description'], 'rb')
- }
+ files, exit, exit_msg = load_data_files(data, ['file', 'description'])
elif asset == 'data':
# support bulk with multiple files
- files = data.get('files', None)
- if files and type(files) == list:
+ data_files = data.get('files', None)
+ if data_files and type(data_files) == list:
files = {
- path_leaf(x): open(x, 'rb') for x in files
+ path_leaf(x): open(x, 'rb') for x in data_files
}
else:
- files = {
- 'file': open(data['file'], 'rb'),
- }
+ files, exit, exit_msg = load_data_files(data, ['file'])
+
+ if exit:
+ print(json.dumps(exit_msg))
+ sys.exit(1)
if 'permissions' not in data:
data['permissions'] = 'all'
