|
| 1 | +import requests |
| 2 | +from typing import List |
| 3 | + |
| 4 | + |
| 5 | +class QualiAPISession: |
| 6 | + def __init__(self, host, username='', password='', domain='Global', token_id='', port=9000): |
| 7 | + self.session = requests.Session() |
| 8 | + self.base_url = f"http://{host}:{port}/Api" |
| 9 | + self._json_header = {"Content-Type": "application/json"} |
| 10 | + self.login(username, password, token_id, domain) |
| 11 | + |
| 12 | + def login(self, username="", password="", token_id="", domain="Global"): |
| 13 | + if token_id: |
| 14 | + body = {"Token": token_id, "Domain": domain} |
| 15 | + elif username and password: |
| 16 | + body = {"Username": username, "Password": password, "Domain": domain} |
| 17 | + else: |
| 18 | + raise ValueError("Must supply Username / Password OR a token_id") |
| 19 | + url = f"{self.base_url}/Auth/Login" |
| 20 | + login_result = requests.put(url, json=body, headers=self._json_header) |
| 21 | + if not login_result.ok: |
| 22 | + raise Exception(f"Failed Quali API login. Status {login_result.status_code}: {login_result.text}") |
| 23 | + |
| 24 | + # strip the extraneous quotes |
| 25 | + token_str = login_result.text[1:-1] |
| 26 | + self.session.headers.update({"Authorization": f"Basic {token_str}"}) |
| 27 | + |
| 28 | + @staticmethod |
| 29 | + def _validate_response(response: requests.Response): |
| 30 | + if not response.ok: |
| 31 | + response.raise_for_status() |
| 32 | + |
| 33 | + def import_package(self, package_filepath: str): |
| 34 | + """ |
| 35 | + Push a zipped Package file into the CloudShell Server |
| 36 | + provide full path to zip file |
| 37 | + """ |
| 38 | + url = f"{self.base_url}/Package/ImportPackage" |
| 39 | + with open(package_filepath, "rb") as package_file: |
| 40 | + package_content = package_file.read() |
| 41 | + response = self.session.post(url, files={'QualiPackage': package_content}) |
| 42 | + self._validate_response(response) |
| 43 | + |
| 44 | + def export_package(self, blueprint_full_names: List[str], file_path: str): |
| 45 | + """ |
| 46 | + Export one or more multiple blueprints from CloudShell as a Quali Package |
| 47 | + pass file name to export to local dir, or full path |
| 48 | + """ |
| 49 | + url = f"{self.base_url}/Package/ExportPackage" |
| 50 | + body = {"TopologyNames": blueprint_full_names} |
| 51 | + response = self.session.post(url, json=body, headers=self._json_header) |
| 52 | + self._validate_response(response) |
| 53 | + with open(file_path, "wb") as target_file: |
| 54 | + target_file.write(response.content) |
| 55 | + |
0 commit comments