-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathclient.py
96 lines (83 loc) · 3.01 KB
/
client.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
#!/usr/bin/env python
#
# client.py
#
# A barebones VCO API client
#
# Dependencies:
#
# The only library required to use this tool is the Python requests library, which can be installed with pip, e.g.
# ```
# pip install requests
# ```
#
# Examples:
#
# (1) Initialize, authenticate:
# ```
# client = VcoRequestManager("vcoXX-usvi1.velocloud.net")
# client.authenticate(os.environ["VC_USERNAME"], os.environ["VC_PASSWORD"], is_operator=True)
# ```
# (2) Get Edges
# ```
# client.call_api("enterprise/getEnterpriseEdges", { "enterpriseId": 1 })
# ```
#
import requests
import json
import re
class ApiException(Exception):
pass
class VcoRequestManager(object):
def __init__(self, hostname, verify_ssl=True):
self._session = requests.Session()
self._verify_ssl = verify_ssl
self._root_url = self._get_root_url(hostname)
self._portal_url = self._root_url + "/portal/"
self._livepull_url = self._root_url + "/livepull/liveData/"
self._seqno = 0
def _get_root_url(self, hostname):
"""
Translate VCO hostname to a root url for API calls
"""
if hostname.startswith("http"):
re.sub('http(s)?://', '', hostname)
proto = "https://"
return proto + hostname
def authenticate(self, username, password, is_operator=True):
"""
Authenticate to API - on success, a cookie is stored in the session
"""
path = "/login/operatorLogin" if is_operator else "/login/enterpriseLogin"
url = self._root_url + path
data = { "username": username, "password": password }
headers = { "Content-Type": "application/json" }
r = self._session.post(url, headers=headers, data=json.dumps(data),
allow_redirects=False, verify=self._verify_ssl)
def call_api(self, method, params):
"""
Build and submit a request
Returns method result as a Python dictionary
"""
self._seqno += 1
headers = { "Content-Type": "application/json" }
method = self._clean_method_name(method)
payload = { "jsonrpc": "2.0",
"id": self._seqno,
"method": method,
"params": params }
if method in ("liveMode/readLiveData", "liveMode/requestLiveActions", "liveMode/clientExitLiveMode"):
url = self._livepull_url
else:
url = self._portal_url
r = self._session.post(url, headers=headers,
data=json.dumps(payload), verify=self._verify_ssl)
response_dict = r.json()
if "error" in response_dict:
raise ApiException(response_dict["error"]["message"])
return response_dict["result"]
def _clean_method_name(self, raw_name):
"""
Ensure method name is properly formatted prior to initiating request
"""
return raw_name.strip("/")