CoCalc Public FilesPublic / PYTHON / 01-utils.ipynbOpen with one click!
Author: Hal Snyder
Views : 140
Description: utility functions for API examples
Compute Environment: Ubuntu 18.04 (Deprecated)
In [10]:
import requests from requests.auth import HTTPBasicAuth import json import yaml import pprint
In [11]:
pp = pprint.PrettyPrinter()
In [8]:
def load_user_info(fname): r""" load user information input file: api_user: first_name: Jane last_name: Doe password: AB45yuZZ))jRw api_key: sk_sda89swelekd8x0JJ83lGSwl returns dict of user info settings """ with open(fname,"r") as inf: user_info = yaml.load(inf)['api_user'] return user_info
In [15]:
def call_api(msg="ping", payload={}, sk = '', base_url="https://cocalc.com", max_retries=3, timeout=4): r""" generic API call with retries msg - string message type: "create_account", "create_project", etc. payload - dict of parameters for the call sk - string, security key retries - int, number of retries on post return python dict of API response object """ s = requests.Session() a = requests.adapters.HTTPAdapter(max_retries=max_retries) s.mount('https://', a) url = "{}/api/v1/{}".format(base_url, msg) auth = HTTPBasicAuth(sk,'') headers = {'content-type': 'application/json'} r = s.post(url,auth=auth,data=json.dumps(payload),headers=headers, timeout=timeout) assert r.status_code == requests.codes.ok,"bad status code {}".format(r.status_code) retval = r.json() return retval
In [ ]: