Skip to content
This repository was archived by the owner on Aug 11, 2020. It is now read-only.

Commit d32a8e6

Browse files
sanfilipexdx
authored andcommitted
move method logic to method module; add HTTP method type handling for machine related methods
1 parent b4fc50b commit d32a8e6

File tree

3 files changed

+141
-112
lines changed

3 files changed

+141
-112
lines changed

paperspace/__init__.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
from .config import *
22
from .login import login, logout
3-
from .jobs import print_json_pretty, run
3+
from .method import print_json_pretty
4+
from .jobs import run
45
from . import jobs
56

67
__version__ = "0.0.11"

paperspace/jobs.py

Lines changed: 1 addition & 111 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,7 @@
33
import os
44
import re
55
import sys
6-
import tempfile
76
import time
8-
import zipfile
97

108
import boto3
119
import botocore
@@ -15,115 +13,7 @@
1513
from .login import apikey
1614
from .method import *
1715

18-
def zip_to_tmp(files, ignore_files=[]):
19-
file = files[0]
20-
zipname = os.path.join(tempfile.gettempdir(),
21-
os.path.basename(os.path.abspath(os.path.expanduser(file)))) + '.zip'
22-
outZipFile = zipfile.ZipFile(zipname, 'w', zipfile.ZIP_DEFLATED)
23-
files_added = set()
24-
with outZipFile:
25-
for file in files:
26-
file = os.path.abspath(os.path.expanduser(file))
27-
if os.path.isdir(file):
28-
for dirpath, dirnames, filenames in os.walk(file):
29-
dirnames[:] = [d for d in dirnames if d not in ignore_files]
30-
for filename in filenames:
31-
if filename not in ignore_files:
32-
filepath = os.path.join(dirpath, filename)
33-
arcname = os.path.relpath(filepath, file)
34-
if arcname not in files_added:
35-
outZipFile.write(filepath, arcname)
36-
files_added.add(arcname)
37-
else:
38-
arcname = os.path.basename(file)
39-
if arcname not in files_added:
40-
outZipFile.write(file, arcname)
41-
files_added.add(arcname)
42-
return zipname
43-
44-
45-
def print_json_pretty(res):
46-
print(json.dumps(res, indent=2, sort_keys=True))
47-
48-
49-
def method(category, method, params):
50-
params = params.copy()
51-
if 'apiKey' in params:
52-
config.PAPERSPACE_API_KEY = params.pop('apiKey')
53-
elif not config.PAPERSPACE_API_KEY:
54-
config.PAPERSPACE_API_KEY = apikey()
55-
params.pop('tail', None)
56-
no_logging = params.pop('no_logging', None)
57-
workspace_files = params.pop('extraFiles', [])
58-
ignore_files = params.pop('ignoreFiles', [])
59-
60-
if method in ['artifactsGet', 'artifactsList', 'getJob', 'getJobs',
61-
'getLogs', 'getClusterAvailableMachineTypes']:
62-
63-
http_method = 'GET'
64-
path = '/' + category + '/' + method
65-
66-
elif method in ['artifactsDestroy', 'clone', 'destroy', 'stop']:
67-
68-
http_method = 'POST'
69-
path = '/' + category + '/' + params['jobId'] + '/' + method
70-
del params['jobId']
71-
72-
else:
73-
74-
http_method = 'POST'
75-
path = '/' + category + '/' + method
76-
77-
files = None
78-
if method == 'createJob' and 'workspace' in params:
79-
80-
workspace = params.get('workspace', None)
81-
ignore_files.extend(['.git', '.gitignore', '__pycache__'])
82-
if workspace:
83-
if workspace != 'none':
84-
workspace_files.insert(0, workspace)
85-
del params['workspace']
86-
87-
if workspace_files:
88-
workspace_file = None
89-
for file in workspace_files:
90-
file_path = os.path.expanduser(file)
91-
if not os.path.exists(file_path):
92-
message = format('error: file or directory not found: %s' % file_path)
93-
if no_logging:
94-
return { 'error': True, 'message': message }
95-
print(message)
96-
sys.exit(1)
97-
elif file_path == '/':
98-
message = 'error: cannot zip root directory'
99-
if no_logging:
100-
return { 'error': True, 'message': message }
101-
print(message)
102-
sys.exit(1)
103-
104-
if len(workspace_files) == 1 and (file_path.endswith('.zip') or file_path.endswith('.gz')):
105-
workspace_file = file_path
106-
107-
if not workspace_file:
108-
workspace_file = zip_to_tmp(workspace_files, ignore_files)
109-
110-
files = {'file': open(workspace_file, 'rb')}
111-
params['workspaceFileName'] = os.path.basename(workspace_file)
112-
113-
try:
114-
r = requests.request(http_method, config.CONFIG_HOST + path,
115-
headers={'x-api-key': config.PAPERSPACE_API_KEY},
116-
params=params, files=files)
117-
except requests.exceptions.RequestException as e:
118-
return requests_exception_to_error_obj(e)
119-
120-
try:
121-
return response_error_check(r.json())
122-
except ValueError:
123-
return status_code_to_error_obj(r.status_code)
124-
125-
126-
def list(params):
16+
def list(params={}):
12717
return method('jobs', 'getJobs', params)
12818

12919

paperspace/method.py

Lines changed: 138 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,143 @@
1+
import json
2+
import os
3+
import sys
4+
import tempfile
5+
import time
6+
import zipfile
7+
from pprint import pprint
8+
19
import requests
210

11+
from . import config
12+
13+
def zip_to_tmp(files, ignore_files=[]):
14+
file = files[0]
15+
zipname = os.path.join(tempfile.gettempdir(),
16+
os.path.basename(os.path.abspath(os.path.expanduser(file)))) + '.zip'
17+
outZipFile = zipfile.ZipFile(zipname, 'w', zipfile.ZIP_DEFLATED)
18+
files_added = set()
19+
with outZipFile:
20+
for file in files:
21+
file = os.path.abspath(os.path.expanduser(file))
22+
if os.path.isdir(file):
23+
for dirpath, dirnames, filenames in os.walk(file):
24+
dirnames[:] = [d for d in dirnames if d not in ignore_files]
25+
for filename in filenames:
26+
if filename not in ignore_files:
27+
filepath = os.path.join(dirpath, filename)
28+
arcname = os.path.relpath(filepath, file)
29+
if arcname not in files_added:
30+
outZipFile.write(filepath, arcname)
31+
files_added.add(arcname)
32+
else:
33+
arcname = os.path.basename(file)
34+
if arcname not in files_added:
35+
outZipFile.write(file, arcname)
36+
files_added.add(arcname)
37+
return zipname
38+
39+
40+
def print_json_pretty(res):
41+
print(json.dumps(res, indent=2, sort_keys=True))
42+
43+
44+
def method(category, method, params):
45+
params = params.copy()
46+
if 'apiKey' in params:
47+
config.PAPERSPACE_API_KEY = params.pop('apiKey')
48+
elif not config.PAPERSPACE_API_KEY:
49+
config.PAPERSPACE_API_KEY = apikey()
50+
params.pop('tail', None)
51+
no_logging = params.pop('no_logging', None)
52+
workspace_files = params.pop('extraFiles', [])
53+
ignore_files = params.pop('ignoreFiles', [])
54+
55+
if category == 'jobs' and method in ['artifactsGet', 'artifactsList', 'getJob', 'getJobs', 'getLogs', 'getClusterAvailableMachineTypes']:
56+
http_method = 'GET'
57+
path = '/' + category + '/' + method
58+
59+
elif category == 'jobs' and method in ['artifactsDestroy', 'clone', 'destroy', 'stop']:
60+
http_method = 'POST'
61+
path = '/' + category + '/' + params['jobId'] + '/' + method
62+
del params['jobId']
63+
64+
elif ((category == 'machines' and method in ['getAvailability', 'getMachines', 'getMachinePublic', 'getUtilization'])
65+
or (category == 'scripts' and method in ['getScript', 'getScripts', 'getScriptText'])
66+
or (category == 'networks' and method == 'getNetworks')
67+
or (category == 'templates' and method == 'getTemplates')
68+
or (category == 'users' and method == 'getUsers')):
69+
http_method = 'GET'
70+
path = '/' + category + '/' + method
71+
72+
elif category == 'machines' and method in ['destroyMachine', 'restart', 'start', 'stop', 'updateMachinePublic']:
73+
http_method = 'POST'
74+
path = '/' + category + '/' + params['machineId'] + '/' + method
75+
76+
elif category == 'scripts' and method == 'destroy':
77+
http_method = 'POST'
78+
path = '/' + category + '/' + params['scriptId'] + '/' + method
79+
del params['scriptId']
80+
81+
else:
82+
http_method = 'POST'
83+
path = '/' + category + '/' + method
84+
85+
files = None
86+
if method == 'createJob' and 'workspace' in params:
87+
88+
workspace = params.get('workspace', None)
89+
ignore_files.extend(['.git', '.gitignore', '__pycache__'])
90+
if workspace:
91+
if workspace != 'none':
92+
workspace_files.insert(0, workspace)
93+
del params['workspace']
94+
95+
if workspace_files:
96+
workspace_file = None
97+
for file in workspace_files:
98+
file_path = os.path.expanduser(file)
99+
if not os.path.exists(file_path):
100+
message = format('error: file or directory not found: %s' % file_path)
101+
if no_logging:
102+
return { 'error': True, 'message': message }
103+
print(message)
104+
sys.exit(1)
105+
elif file_path == '/':
106+
message = 'error: cannot zip root directory'
107+
if no_logging:
108+
return { 'error': True, 'message': message }
109+
print(message)
110+
sys.exit(1)
111+
112+
if len(workspace_files) == 1 and (file_path.endswith('.zip') or file_path.endswith('.gz')):
113+
workspace_file = file_path
114+
115+
if not workspace_file:
116+
workspace_file = zip_to_tmp(workspace_files, ignore_files)
117+
118+
files = {'file': open(workspace_file, 'rb')}
119+
params['workspaceFileName'] = os.path.basename(workspace_file)
120+
121+
try:
122+
data = None
123+
if category == 'machines' and method == 'createSingleMachinePublic':
124+
data = params
125+
params = None
126+
r = requests.request(http_method, config.CONFIG_HOST + path,
127+
headers={'x-api-key': config.PAPERSPACE_API_KEY},
128+
params=params, data=data, files=files)
129+
#pprint(vars(r.request))
130+
except requests.exceptions.RequestException as e:
131+
return requests_exception_to_error_obj(e)
132+
133+
try:
134+
if r.status_code != 204:
135+
return response_error_check(r.json())
136+
else:
137+
return {}
138+
except ValueError:
139+
return status_code_to_error_obj(r.status_code)
140+
3141

4142
def response_error_check(res):
5143
if ('error' not in res

0 commit comments

Comments
 (0)