code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
'''Save an object to Instapaper after instantiating it. Example:: folder = Folder(instapaper, title='stuff') result = folder.add() ''' # TODO validation per object type submit_attribs = {} for attrib in self.ATTRIBUTES: val = getattr(self, attrib, None) if val: submit_attribs[attrib] = val path = '/'.join([self.RESOURCE, 'add']) result = self.client.request(path, submit_attribs) return result
def add(self)
Save an object to Instapaper after instantiating it. Example:: folder = Folder(instapaper, title='stuff') result = folder.add()
6.873816
3.712102
1.851731
'''Issue a request for an API method whose only param is the obj ID. :param str action: The name of the action for the resource :returns: Response from the API :rtype: dict ''' if not action: raise Exception('No simple action defined') path = "/".join([self.RESOURCE, action]) response = self.client.request( path, {self.RESOURCE_ID_ATTRIBUTE: self.object_id} ) return response
def _simple_action(self, action=None)
Issue a request for an API method whose only param is the obj ID. :param str action: The name of the action for the resource :returns: Response from the API :rtype: dict
6.891215
3.533226
1.950403
'''Get highlights for Bookmark instance. :return: list of ``Highlight`` objects :rtype: list ''' # NOTE: all Instapaper API methods use POST except this one! path = '/'.join([self.RESOURCE, str(self.object_id), 'highlights']) response = self.client.request(path, method='GET', api_version='1.1') items = response['data'] highlights = [] for item in items: if item.get('type') == 'error': raise Exception(item.get('message')) elif item.get('type') == 'highlight': highlights.append(Highlight(self, **item)) return highlights
def get_highlights(self)
Get highlights for Bookmark instance. :return: list of ``Highlight`` objects :rtype: list
4.169503
3.612775
1.1541
if self.interval is not None: self._queue.put_nowait(None) self._thread.join() self.interval = None
def stop(self)
Tell the sender thread to finish and wait for it to stop sending (should be at most "timeout" seconds).
4.235915
4.258329
0.994736
if not metric or metric.split(None, 1)[0] != metric: raise ValueError('"metric" must not have whitespace in it') if not isinstance(value, (int, float)): raise TypeError('"value" must be an int or a float, not a {}'.format( type(value).__name__)) tags_suffix = ''.join(';{}={}'.format(x[0], x[1]) for x in sorted(tags.items())) message = u'{}{}{} {} {}\n'.format( self.prefix + '.' if self.prefix else '', metric, tags_suffix, value, int(round(timestamp)) ) message = message.encode('utf-8') return message
def build_message(self, metric, value, timestamp, tags={})
Build a Graphite message to send and return it as a byte string.
3.191593
3.010307
1.060222
if timestamp is None: timestamp = time.time() message = self.build_message(metric, value, timestamp, tags) if self.interval is None: self.send_socket(message) else: try: self._queue.put_nowait(message) except queue.Full: logger.error('queue full when sending {!r}'.format(message))
def send(self, metric, value, timestamp=None, tags={})
Send given metric and (int or float) value to Graphite host. Performs send on background thread if "interval" was specified when creating this Sender. If a "tags" dict is specified, send the tags to the Graphite host along with the metric.
2.851221
2.957109
0.964192
if self.log_sends: start_time = time.time() try: self.send_message(message) except Exception as error: logger.error('error sending message {!r}: {}'.format(message, error)) else: if self.log_sends: elapsed_time = time.time() - start_time logger.info('sent message {!r} to {}:{} in {:.03f} seconds'.format( message, self.host, self.port, elapsed_time))
def send_socket(self, message)
Low-level function to send message bytes to this Sender's socket. You should usually call send() instead of this function (unless you're subclassing or writing unit tests).
2.567471
2.507048
1.024102
last_check_time = time.time() messages = [] while True: # Get first message from queue, blocking until the next time we # should be sending time_since_last_check = time.time() - last_check_time time_till_next_check = max(0, self.interval - time_since_last_check) try: message = self._queue.get(timeout=time_till_next_check) except queue.Empty: pass else: if message is None: # None is the signal to stop this background thread break messages.append(message) # Get any other messages currently on queue without blocking, # paying attention to None ("stop thread" signal) should_stop = False while True: try: message = self._queue.get_nowait() except queue.Empty: break if message is None: should_stop = True break messages.append(message) if should_stop: break # If it's time to send, send what we've collected current_time = time.time() if current_time - last_check_time >= self.interval: last_check_time = current_time for i in range(0, len(messages), self.batch_size): batch = messages[i:i + self.batch_size] self.send_socket(b''.join(batch)) messages = [] # Send any final messages before exiting thread for i in range(0, len(messages), self.batch_size): batch = messages[i:i + self.batch_size] self.send_socket(b''.join(batch))
def _thread_loop(self)
Background thread used when Sender is in asynchronous/interval mode.
2.615678
2.55371
1.024266
'''Main routine.''' # validate command line arguments arg_parser = argparse.ArgumentParser() arg_parser.add_argument( '--vmssname', '-n', required=True, action='store', help='VMSS Name') arg_parser.add_argument('--rgname', '-g', required=True, action='store', help='Resource Group Name') arg_parser.add_argument('--details', '-a', required=False, action='store_true', default=False, help='Print all details') args = arg_parser.parse_args() name = args.vmssname rgname = args.rgname details = args.details # Load Azure app defaults try: with open('azurermconfig.json') as config_file: config_data = json.load(config_file) except FileNotFoundError: print("Error: Expecting azurermconfig.json in current folder") sys.exit() tenant_id = config_data['tenantId'] app_id = config_data['appId'] app_secret = config_data['appSecret'] subscription_id = config_data['subscriptionId'] # authenticate access_token = azurerm.get_access_token(tenant_id, app_id, app_secret) # get rolling upgrade latest status upgrade_status = azurerm.get_vmss_rolling_upgrades( access_token, subscription_id, rgname, name) # print details if details is True: print(json.dumps(upgrade_status, sort_keys=False, indent=2, separators=(',', ': '))) else: print(json.dumps(upgrade_status, sort_keys=False, indent=2, separators=(',', ': ')))
def main()
Main routine.
1.777119
1.761429
1.008907
'''Main routine.''' # process arguments if len(sys.argv) < 3: usage() rgname = sys.argv[1] vmss_name = sys.argv[2] # Load Azure app defaults try: with open('azurermconfig.json') as config_file: config_data = json.load(config_file) except FileNotFoundError: sys.exit('Error: Expecting azurermconfig.json in current folder') tenant_id = config_data['tenantId'] app_id = config_data['appId'] app_secret = config_data['appSecret'] subscription_id = config_data['subscriptionId'] access_token = azurerm.get_access_token(tenant_id, app_id, app_secret) print('Printing VMSS details\n') vmssget = azurerm.get_vmss( access_token, subscription_id, rgname, vmss_name) name = vmssget['name'] capacity = vmssget['sku']['capacity'] location = vmssget['location'] offer = \ vmssget['properties']['virtualMachineProfile']['storageProfile']['imageReference']['offer'] sku = vmssget['properties']['virtualMachineProfile']['storageProfile']['imageReference']['sku'] print(json.dumps(vmssget, sort_keys=False, indent=2, separators=(',', ': '))) print('Name: ' + name + ', capacity: ' + str(capacity) + ', ' + location + ', ' + offer + ', ' + sku) print('Printing VMSS instance view') instance_view = azurerm.get_vmss_instance_view( access_token, subscription_id, rgname, vmss_name) print(json.dumps(instance_view, sort_keys=False, indent=2, separators=(',', ': '))) ''' print('Listing VMSS VMs') vmss_vms = azurerm.list_vmss_vms(access_token, subscription_id, rg, vmss) print(json.dumps(vmss_vms, sort_keys=False, indent=2, separators=(',', ': '))) for vm in vmss_vms['value']: instanceId = vm['instanceId'] vminstance_view = azurerm.get_vmss_vm_instance_view(access_token, subscription_id, rg, vmss, instanceId) print('VM ' + str(instanceId) + ' instance view') print(json.dumps(vminstance_view, sort_keys=False, indent=2, separators=(',', ': '))) '''
def main()
Main routine.
1.892445
1.897234
0.997476
'''get a resource group name from a VMSS ID string''' rgname = re.search('Groups/(.+?)/providers', vmss_id).group(1) print('Resource group: ' + rgname) return rgname
def get_rg_from_id(vmss_id)
get a resource group name from a VMSS ID string
4.778095
3.947483
1.210416
'''main routine''' # Load Azure app defaults try: with open('azurermconfig.json') as config_file: config_data = json.load(config_file) except FileNotFoundError: sys.exit('Error: Expecting azurermconfig.json in current folder') tenant_id = config_data['tenantId'] app_id = config_data['appId'] app_secret = config_data['appSecret'] subscription_id = config_data['subscriptionId'] access_token = azurerm.get_access_token(tenant_id, app_id, app_secret) vmsslist = azurerm.list_vmss_sub(access_token, subscription_id) for vmss in vmsslist['value']: name = vmss['name'] location = vmss['location'] capacity = vmss['sku']['capacity'] print(''.join(['Name: ', name, ', location: ', location, ', Capacity: ', str(capacity)])) print('VMSS NICs...') rgname = get_rg_from_id(vmss['id']) vmss_nics = azurerm.get_vmss_nics( access_token, subscription_id, rgname, name) print(json.dumps(vmss_nics, sort_keys=False, indent=2, separators=(',', ': '))) print('VMSS Virtual machines...') vms = azurerm.list_vmss_vms( access_token, subscription_id, rgname, name) #print(json.dumps(vms, sort_keys=False, indent=2, separators=(',', ': '))) for vmssvm in vms['value']: vm_id = vmssvm['instanceId'] print(vm_id + ', ' + vmssvm['name'] + '\n') print('VMSS VM NICs...') vmnics = azurerm.get_vmss_vm_nics(access_token, subscription_id, rgname, name, vm_id) print(json.dumps(vmnics, sort_keys=False, indent=2, separators=(',', ': ')))
def main()
main routine
1.862582
1.864832
0.998793
'''User-Agent Header. Sends library identification to Azure endpoint. ''' version = pkg_resources.require("azurerm")[0].version user_agent = "python/{} ({}) requests/{} azurerm/{}".format( platform.python_version(), platform.platform(), requests.__version__, version) return user_agent
def get_user_agent()
User-Agent Header. Sends library identification to Azure endpoint.
6.032724
3.666902
1.645183
'''Do an HTTP GET request and return JSON. Args: endpoint (str): Azure Resource Manager management endpoint. access_token (str): A valid Azure authentication token. Returns: HTTP response. JSON body. ''' headers = {"Authorization": 'Bearer ' + access_token} headers['User-Agent'] = get_user_agent() return requests.get(endpoint, headers=headers).json()
def do_get(endpoint, access_token)
Do an HTTP GET request and return JSON. Args: endpoint (str): Azure Resource Manager management endpoint. access_token (str): A valid Azure authentication token. Returns: HTTP response. JSON body.
3.795746
2.124427
1.786715
'''Do an HTTP GET request, follow the nextLink chain and return JSON. Args: endpoint (str): Azure Resource Manager management endpoint. access_token (str): A valid Azure authentication token. Returns: HTTP response. JSON body. ''' headers = {"Authorization": 'Bearer ' + access_token} headers['User-Agent'] = get_user_agent() looping = True value_list = [] vm_dict = {} while looping: get_return = requests.get(endpoint, headers=headers).json() if not 'value' in get_return: return get_return if not 'nextLink' in get_return: looping = False else: endpoint = get_return['nextLink'] value_list += get_return['value'] vm_dict['value'] = value_list return vm_dict
def do_get_next(endpoint, access_token)
Do an HTTP GET request, follow the nextLink chain and return JSON. Args: endpoint (str): Azure Resource Manager management endpoint. access_token (str): A valid Azure authentication token. Returns: HTTP response. JSON body.
3.406686
2.344205
1.453237
'''Do an HTTP GET request and return JSON. Args: endpoint (str): Azure Resource Manager management endpoint. access_token (str): A valid Azure authentication token. Returns: HTTP response. ''' headers = {"Authorization": 'Bearer ' + access_token} headers['User-Agent'] = get_user_agent() return requests.delete(endpoint, headers=headers)
def do_delete(endpoint, access_token)
Do an HTTP GET request and return JSON. Args: endpoint (str): Azure Resource Manager management endpoint. access_token (str): A valid Azure authentication token. Returns: HTTP response.
4.055376
2.285053
1.77474
'''Do an HTTP PATCH request and return JSON. Args: endpoint (str): Azure Resource Manager management endpoint. body (str): JSON body of information to patch. access_token (str): A valid Azure authentication token. Returns: HTTP response. JSON body. ''' headers = {"content-type": "application/json", "Authorization": 'Bearer ' + access_token} headers['User-Agent'] = get_user_agent() return requests.patch(endpoint, data=body, headers=headers)
def do_patch(endpoint, body, access_token)
Do an HTTP PATCH request and return JSON. Args: endpoint (str): Azure Resource Manager management endpoint. body (str): JSON body of information to patch. access_token (str): A valid Azure authentication token. Returns: HTTP response. JSON body.
3.385607
1.86212
1.818147
'''Do an HTTP POST request and return JSON. Args: endpoint (str): Azure Resource Manager management endpoint. body (str): JSON body of information to post. access_token (str): A valid Azure authentication token. Returns: HTTP response. JSON body. ''' headers = {"content-type": "application/json", "Authorization": 'Bearer ' + access_token} headers['User-Agent'] = get_user_agent() return requests.post(endpoint, data=body, headers=headers)
def do_post(endpoint, body, access_token)
Do an HTTP POST request and return JSON. Args: endpoint (str): Azure Resource Manager management endpoint. body (str): JSON body of information to post. access_token (str): A valid Azure authentication token. Returns: HTTP response. JSON body.
3.421366
1.851929
1.84746
'''Do an HTTP PUT request and return JSON. Args: endpoint (str): Azure Resource Manager management endpoint. body (str): JSON body of information to put. access_token (str): A valid Azure authentication token. Returns: HTTP response. JSON body. ''' headers = {"content-type": "application/json", "Authorization": 'Bearer ' + access_token} headers['User-Agent'] = get_user_agent() return requests.put(endpoint, data=body, headers=headers)
def do_put(endpoint, body, access_token)
Do an HTTP PUT request and return JSON. Args: endpoint (str): Azure Resource Manager management endpoint. body (str): JSON body of information to put. access_token (str): A valid Azure authentication token. Returns: HTTP response. JSON body.
3.440017
1.856028
1.853429
'''Get Media Services Final Endpoint URL. Args: access_token (str): A valid Azure authentication token. endpoint (str): Azure Media Services Initial Endpoint. flag (bol): flag. Returns: HTTP response. JSON body. ''' return do_ams_get_url(endpoint, access_token, flag)
def get_url(access_token, endpoint=ams_rest_endpoint, flag=True)
Get Media Services Final Endpoint URL. Args: access_token (str): A valid Azure authentication token. endpoint (str): Azure Media Services Initial Endpoint. flag (bol): flag. Returns: HTTP response. JSON body.
7.744025
2.338899
3.31097
'''Acquire Media Services Authentication Token. Args: endpoint (str): Azure Media Services Initial Endpoint. body (str): A Content Body. Returns: HTTP response. JSON body. ''' headers = {"content-type": "application/x-www-form-urlencoded", "Accept": json_acceptformat} return requests.post(endpoint, data=body, headers=headers)
def do_ams_auth(endpoint, body)
Acquire Media Services Authentication Token. Args: endpoint (str): Azure Media Services Initial Endpoint. body (str): A Content Body. Returns: HTTP response. JSON body.
6.218786
2.685678
2.315536
'''Do a AMS HTTP PUT request and return JSON. Args: endpoint (str): Azure Media Services Initial Endpoint. path (str): Azure Media Services Endpoint Path. body (str): Azure Media Services Content Body. access_token (str): A valid Azure authentication token. rformat (str): A required JSON Accept Format. ds_min_version (str): A required DS MIN Version. Returns: HTTP response. JSON body. ''' min_ds = dsversion_min content_acceptformat = json_acceptformat if rformat == "json_only": min_ds = ds_min_version content_acceptformat = json_only_acceptformat headers = {"Content-Type": content_acceptformat, "DataServiceVersion": min_ds, "MaxDataServiceVersion": dsversion_max, "Accept": json_acceptformat, "Accept-Charset" : charset, "Authorization": "Bearer " + access_token, "x-ms-version" : xmsversion} response = requests.put(endpoint, data=body, headers=headers, allow_redirects=False) # AMS response to the first call can be a redirect, # so we handle it here to make it transparent for the caller... if response.status_code == 301: redirected_url = ''.join([response.headers['location'], path]) response = requests.put(redirected_url, data=body, headers=headers) return response
def do_ams_put(endpoint, path, body, access_token, rformat="json", ds_min_version="3.0;NetFx")
Do a AMS HTTP PUT request and return JSON. Args: endpoint (str): Azure Media Services Initial Endpoint. path (str): Azure Media Services Endpoint Path. body (str): Azure Media Services Content Body. access_token (str): A valid Azure authentication token. rformat (str): A required JSON Accept Format. ds_min_version (str): A required DS MIN Version. Returns: HTTP response. JSON body.
4.082647
2.739539
1.490268
'''Do a AMS HTTP POST request and return JSON. Args: endpoint (str): Azure Media Services Initial Endpoint. path (str): Azure Media Services Endpoint Path. body (str): Azure Media Services Content Body. access_token (str): A valid Azure authentication token. rformat (str): A required JSON Accept Format. ds_min_version (str): A required DS MIN Version. Returns: HTTP response. JSON body. ''' min_ds = dsversion_min content_acceptformat = json_acceptformat acceptformat = json_acceptformat if rformat == "json_only": min_ds = ds_min_version content_acceptformat = json_only_acceptformat if rformat == "xml": content_acceptformat = xml_acceptformat acceptformat = xml_acceptformat + ",application/xml" headers = {"Content-Type": content_acceptformat, "DataServiceVersion": min_ds, "MaxDataServiceVersion": dsversion_max, "Accept": acceptformat, "Accept-Charset" : charset, "Authorization": "Bearer " + access_token, "x-ms-version" : xmsversion} response = requests.post(endpoint, data=body, headers=headers, allow_redirects=False) # AMS response to the first call can be a redirect, # so we handle it here to make it transparent for the caller... if response.status_code == 301: redirected_url = ''.join([response.headers['location'], path]) response = requests.post(redirected_url, data=body, headers=headers) return response
def do_ams_post(endpoint, path, body, access_token, rformat="json", ds_min_version="3.0;NetFx")
Do a AMS HTTP POST request and return JSON. Args: endpoint (str): Azure Media Services Initial Endpoint. path (str): Azure Media Services Endpoint Path. body (str): Azure Media Services Content Body. access_token (str): A valid Azure authentication token. rformat (str): A required JSON Accept Format. ds_min_version (str): A required DS MIN Version. Returns: HTTP response. JSON body.
3.646058
2.549477
1.43012
'''Do a AMS PATCH request and return JSON. Args: endpoint (str): Azure Media Services Initial Endpoint. path (str): Azure Media Services Endpoint Path. body (str): Azure Media Services Content Body. access_token (str): A valid Azure authentication token. Returns: HTTP response. JSON body. ''' headers = {"Content-Type": json_acceptformat, "DataServiceVersion": dsversion_min, "MaxDataServiceVersion": dsversion_max, "Accept": json_acceptformat, "Accept-Charset" : charset, "Authorization": "Bearer " + access_token, "x-ms-version" : xmsversion} response = requests.patch(endpoint, data=body, headers=headers, allow_redirects=False) # AMS response to the first call can be a redirect, # so we handle it here to make it transparent for the caller... if response.status_code == 301: redirected_url = ''.join([response.headers['location'], path]) response = requests.patch(redirected_url, data=body, headers=headers) return response
def do_ams_patch(endpoint, path, body, access_token)
Do a AMS PATCH request and return JSON. Args: endpoint (str): Azure Media Services Initial Endpoint. path (str): Azure Media Services Endpoint Path. body (str): Azure Media Services Content Body. access_token (str): A valid Azure authentication token. Returns: HTTP response. JSON body.
4.168906
2.889099
1.442978
'''Do a AMS DELETE request and return JSON. Args: endpoint (str): Azure Media Services Initial Endpoint. path (str): Azure Media Services Endpoint Path. access_token (str): A valid Azure authentication token. Returns: HTTP response. JSON body. ''' headers = {"DataServiceVersion": dsversion_min, "MaxDataServiceVersion": dsversion_max, "Accept": json_acceptformat, "Accept-Charset" : charset, "Authorization": 'Bearer ' + access_token, "x-ms-version" : xmsversion} response = requests.delete(endpoint, headers=headers, allow_redirects=False) # AMS response to the first call can be a redirect, # so we handle it here to make it transparent for the caller... if response.status_code == 301: redirected_url = ''.join([response.headers['location'], path]) response = requests.delete(redirected_url, headers=headers) return response
def do_ams_delete(endpoint, path, access_token)
Do a AMS DELETE request and return JSON. Args: endpoint (str): Azure Media Services Initial Endpoint. path (str): Azure Media Services Endpoint Path. access_token (str): A valid Azure authentication token. Returns: HTTP response. JSON body.
4.570796
3.261124
1.401601
'''Do a PUT request to the Azure Storage API and return JSON. Args: endpoint (str): Azure Media Services Initial Endpoint. body (str): Azure Media Services Content Body. content_length (str): Content_length. Returns: HTTP response. JSON body. ''' headers = {"Accept": json_acceptformat, "Accept-Charset" : charset, "x-ms-blob-type" : "BlockBlob", "x-ms-meta-m1": "v1", "x-ms-meta-m2": "v2", "x-ms-version" : "2015-02-21", "Content-Length" : str(content_length)} return requests.put(endpoint, data=body, headers=headers)
def do_ams_sto_put(endpoint, body, content_length)
Do a PUT request to the Azure Storage API and return JSON. Args: endpoint (str): Azure Media Services Initial Endpoint. body (str): Azure Media Services Content Body. content_length (str): Content_length. Returns: HTTP response. JSON body.
3.815176
2.181629
1.748774
'''Do an AMS GET request to retrieve the Final AMS Endpoint and return JSON. Args: endpoint (str): Azure Media Services Initial Endpoint. access_token (str): A valid Azure authentication token. flag (str): A Flag to follow the redirect or not. Returns: HTTP response. JSON body. ''' headers = {"Content-Type": json_acceptformat, "DataServiceVersion": dsversion_min, "MaxDataServiceVersion": dsversion_max, "Accept": json_acceptformat, "Accept-Charset" : charset, "Authorization": "Bearer " + access_token, "x-ms-version" : xmsversion} body = '' response = requests.get(endpoint, headers=headers, allow_redirects=flag) if flag: if response.status_code == 301: response = requests.get(response.headers['location'], data=body, headers=headers) return response
def do_ams_get_url(endpoint, access_token, flag=True)
Do an AMS GET request to retrieve the Final AMS Endpoint and return JSON. Args: endpoint (str): Azure Media Services Initial Endpoint. access_token (str): A valid Azure authentication token. flag (str): A Flag to follow the redirect or not. Returns: HTTP response. JSON body.
4.457179
2.371134
1.879767
'''report error for bad update''' print("Error " + operation) sys.exit('Return code: ' + str(ret.status_code) + ' Error: ' + ret.text)
def handle_bad_update(operation, ret)
report error for bad update
7.597074
6.456917
1.176579
'''Extract a multi-line string from a string array, up to a specified end marker. Args: end_mark (str): The end mark string to match for. current_str (str): The first line of the string array. str_array (list): An array of strings (lines). line_num (int): The current offset into the array. Returns: Extended string up to line with end marker. ''' if end_mark not in current_str: reached_end = False line_num += 1 while reached_end is False: next_line = str_array[line_num] if end_mark in next_line: reached_end = True else: line_num += 1 current_str += next_line clean_str = current_str.split(end_mark)[0] return {'current_str': clean_str, 'line_num': line_num}
def extract_code(end_mark, current_str, str_array, line_num)
Extract a multi-line string from a string array, up to a specified end marker. Args: end_mark (str): The end mark string to match for. current_str (str): The first line of the string array. str_array (list): An array of strings (lines). line_num (int): The current offset into the array. Returns: Extended string up to line with end marker.
3.039487
1.712417
1.774968
'''Process a Python source file with Google style docstring comments. Reads file header comment, function definitions, function docstrings. Returns dictionary encapsulation for subsequent writing. Args: pyfile_name (str): file name to read. Returns: Dictionary object containing summary comment, with a list of entries for each function. ''' print('Processing file: ' + pyfile_name) # load the source file with open(pyfile_name) as fpyfile: pyfile_str = fpyfile.readlines() # meta-doc for a source file file_dict = {'source_file': pyfile_name.replace('\\', '/')} # get file summary line at the top of the file if pyfile_str[0].startswith("'''"): file_dict['summary_comment'] = pyfile_str[0][:-1].strip("'") else: file_dict['summary_comment'] = pyfile_name file_dict['functions'] = [] # find every function definition for line in pyfile_str: # process definition if line.startswith('def '): line_num = pyfile_str.index(line) fn_def = line[4:] fn_name = fn_def.split('(')[0] function_info = {'name': fn_name} extract = extract_code(':', fn_def, pyfile_str, line_num) function_info['definition'] = extract['current_str'] # process docstring line_num = extract['line_num'] + 1 doc_line = pyfile_str[line_num] if doc_line.startswith(" '''"): comment_str = doc_line[7:] extract = extract_code( "'''", comment_str, pyfile_str, line_num) function_info['comments'] = extract['current_str'] file_dict['functions'].append(function_info) return file_dict
def process_file(pyfile_name)
Process a Python source file with Google style docstring comments. Reads file header comment, function definitions, function docstrings. Returns dictionary encapsulation for subsequent writing. Args: pyfile_name (str): file name to read. Returns: Dictionary object containing summary comment, with a list of entries for each function.
3.818662
2.630762
1.451542
'''Create a markdown format documentation file. Args: meta_file (dict): Dictionary with documentation metadata. outfile_name (str): Markdown file to write to. ''' # Markdown title line doc_str = '# ' + meta_file['header'] + '\n' doc_str += 'Generated by [py2md](https://github.com/gbowerman/py2md) on ' doc_str += strftime("%Y-%m-%d %H:%M:%S ") + '\n\n' # Create a table of contents if more than one module (i.e. more than one # source file) if len(meta_file['modules']) > 1: doc_str += "## Contents\n" chapter_num = 1 for meta_doc in meta_file['modules']: chapter_name = meta_doc['summary_comment'] chapter_link = chapter_name.lstrip().replace('.', '').replace(' ', '-').lower() doc_str += str(chapter_num) + \ '. [' + chapter_name + '](#' + chapter_link + ')\n' chapter_num += 1 # Document each meta-file for meta_doc in meta_file['modules']: doc_str += '## ' + meta_doc['summary_comment'] + '\n' doc_str += '[source file](' + meta_doc['source_file'] + ')' + '\n' for function_info in meta_doc['functions']: doc_str += '### ' + function_info['name'] + '\n' doc_str += function_info['definition'] + '\n\n' if 'comments' in function_info: doc_str += '```\n' + function_info['comments'] + '\n```\n\n' # write the markdown to file print('Writing file: ' + outfile_name) out_file = open(outfile_name, 'w') out_file.write(doc_str) out_file.close()
def process_output(meta_file, outfile_name, code_links)
Create a markdown format documentation file. Args: meta_file (dict): Dictionary with documentation metadata. outfile_name (str): Markdown file to write to.
2.703716
2.486489
1.087363
'''Main routine.''' # validate command line arguments arg_parser = argparse.ArgumentParser() arg_parser.add_argument('--sourcedir', '-s', required=True, action='store', help='Source folder containing python files.') arg_parser.add_argument('--docfile', '-o', required=True, action='store', help='Name of markdown file to write output to.') arg_parser.add_argument('--projectname', '-n', required=False, action='store', help='Project name (optional, otherwise sourcedir will be used).') arg_parser.add_argument('--codelinks', '-c', required=False, action='store_true', help='Include links to source files (optional).') args = arg_parser.parse_args() source_dir = args.sourcedir doc_file = args.docfile code_links = args.codelinks proj_name = args.projectname if proj_name is None: proj_name = source_dir # main document dictionary meta_doc = {'header': proj_name + ' Technical Reference Guide'} meta_doc['modules'] = [] # process each file for source_file in glob.glob(source_dir + '/*.py'): if '__' in source_file: print('Skipping: ' + source_file) continue file_meta_doc = process_file(source_file) meta_doc['modules'].append(file_meta_doc) # create output file process_output(meta_doc, doc_file, code_links)
def main()
Main routine.
2.699793
2.695776
1.00149
'''Create a new container service - include app_id and app_secret if using Kubernetes. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. service_name (str): Name of container service. agent_count (int): The number of agent VMs. agent_vm_size (str): VM size of agents, e.g. Standard_D1_v2. agent_dns (str): A unique DNS string for the agent DNS. master_dns (str): A unique string for the master DNS. admin_user (str): Admin user name. location (str): Azure data center location, e.g. westus. public_key (str): RSA public key (utf-8). master_count (int): Number of master VMs. orchestrator (str): Container orchestrator. E.g. DCOS, Kubernetes. app_id (str): Application ID for Kubernetes. app_secret (str): Application secret for Kubernetes. admin_password (str): Admin user password. ostype (str): Operating system. Windows of Linux. Returns: HTTP response. Container service JSON model. ''' endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourcegroups/', resource_group, '/providers/Microsoft.ContainerService/ContainerServices/', service_name, '?api-version=', ACS_API]) acs_body = {'location': location} properties = {'orchestratorProfile': {'orchestratorType': orchestrator}} properties['masterProfile'] = {'count': master_count, 'dnsPrefix': master_dns} ap_profile = {'name': 'AgentPool1'} ap_profile['count'] = agent_count ap_profile['vmSize'] = agent_vm_size ap_profile['dnsPrefix'] = agent_dns properties['agentPoolProfiles'] = [ap_profile] if ostype == 'Linux': linux_profile = {'adminUsername': admin_user} linux_profile['ssh'] = {'publicKeys': [{'keyData': public_key}]} properties['linuxProfile'] = linux_profile else: # Windows windows_profile = {'adminUsername': admin_user, 'adminPassword': admin_password} properties['windowsProfile'] = windows_profile if orchestrator == 'Kubernetes': sp_profile = {'ClientID': app_id} sp_profile['Secret'] = app_secret properties['servicePrincipalProfile'] = sp_profile acs_body['properties'] = properties body = json.dumps(acs_body) return do_put(endpoint, body, access_token)
def create_container_service(access_token, subscription_id, resource_group, service_name, \ agent_count, agent_vm_size, agent_dns, master_dns, admin_user, location, public_key=None,\ master_count=3, orchestrator='DCOS', app_id=None, app_secret=None, admin_password=None, \ ostype='Linux')
Create a new container service - include app_id and app_secret if using Kubernetes. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. service_name (str): Name of container service. agent_count (int): The number of agent VMs. agent_vm_size (str): VM size of agents, e.g. Standard_D1_v2. agent_dns (str): A unique DNS string for the agent DNS. master_dns (str): A unique string for the master DNS. admin_user (str): Admin user name. location (str): Azure data center location, e.g. westus. public_key (str): RSA public key (utf-8). master_count (int): Number of master VMs. orchestrator (str): Container orchestrator. E.g. DCOS, Kubernetes. app_id (str): Application ID for Kubernetes. app_secret (str): Application secret for Kubernetes. admin_password (str): Admin user password. ostype (str): Operating system. Windows of Linux. Returns: HTTP response. Container service JSON model.
2.207121
1.579843
1.397051
'''Delete a named container. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. service_name (str): Name of container service. Returns: HTTP response. ''' endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourcegroups/', resource_group, '/providers/Microsoft.ContainerService/ContainerServices/', service_name, '?api-version=', ACS_API]) return do_delete(endpoint, access_token)
def delete_container_service(access_token, subscription_id, resource_group, service_name)
Delete a named container. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. service_name (str): Name of container service. Returns: HTTP response.
2.49019
2.084784
1.194459
'''Get details about an Azure Container Server Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. service_name (str): Name of container service. Returns: HTTP response. JSON model. ''' endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourcegroups/', resource_group, '/providers/Microsoft.ContainerService/ContainerServices/', service_name, '?api-version=', ACS_API]) return do_get(endpoint, access_token)
def get_container_service(access_token, subscription_id, resource_group, service_name)
Get details about an Azure Container Server Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. service_name (str): Name of container service. Returns: HTTP response. JSON model.
2.774105
1.992517
1.392262
'''List the container services in a resource group. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. Returns: HTTP response. JSON model. ''' endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourcegroups/', resource_group, '/providers/Microsoft.ContainerService/ContainerServices', '?api-version=', ACS_API]) return do_get(endpoint, access_token)
def list_container_services(access_token, subscription_id, resource_group)
List the container services in a resource group. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. Returns: HTTP response. JSON model.
2.912062
2.371639
1.227869
'''List the container services in a subscription. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. Returns: HTTP response. JSON model. ''' endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/providers/Microsoft.ContainerService/ContainerServices', '?api-version=', ACS_API]) return do_get(endpoint, access_token)
def list_container_services_sub(access_token, subscription_id)
List the container services in a subscription. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. Returns: HTTP response. JSON model.
3.545426
2.848303
1.24475
'''Create a new storage account in the named resource group, with the named location. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. rgname (str): Azure resource group name. account_name (str): Name of the new storage account. location (str): Azure data center location. E.g. westus. storage_type (str): Premium or Standard, local or globally redundant. Defaults to Standard_LRS. Returns: HTTP response. JSON body of storage account properties. ''' endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourcegroups/', rgname, '/providers/Microsoft.Storage/storageAccounts/', account_name, '?api-version=', STORAGE_API]) storage_body = {'location': location} storage_body['sku'] = {'name': storage_type} storage_body['kind'] = 'Storage' body = json.dumps(storage_body) return do_put(endpoint, body, access_token)
def create_storage_account(access_token, subscription_id, rgname, account_name, location, storage_type='Standard_LRS')
Create a new storage account in the named resource group, with the named location. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. rgname (str): Azure resource group name. account_name (str): Name of the new storage account. location (str): Azure data center location. E.g. westus. storage_type (str): Premium or Standard, local or globally redundant. Defaults to Standard_LRS. Returns: HTTP response. JSON body of storage account properties.
2.725644
1.63984
1.662141
'''Delete a storage account in the specified resource group. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. rgname (str): Azure resource group name. account_name (str): Name of the new storage account. Returns: HTTP response. ''' endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourcegroups/', rgname, '/providers/Microsoft.Storage/storageAccounts/', account_name, '?api-version=', STORAGE_API]) return do_delete(endpoint, access_token)
def delete_storage_account(access_token, subscription_id, rgname, account_name)
Delete a storage account in the specified resource group. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. rgname (str): Azure resource group name. account_name (str): Name of the new storage account. Returns: HTTP response.
2.290054
1.965839
1.164924
'''Get the properties for the named storage account. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. rgname (str): Azure resource group name. account_name (str): Name of the new storage account. Returns: HTTP response. JSON body of storage account properties. ''' endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourcegroups/', rgname, '/providers/Microsoft.Storage/storageAccounts/', account_name, '?api-version=', STORAGE_API]) return do_get(endpoint, access_token)
def get_storage_account(access_token, subscription_id, rgname, account_name)
Get the properties for the named storage account. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. rgname (str): Azure resource group name. account_name (str): Name of the new storage account. Returns: HTTP response. JSON body of storage account properties.
2.503962
1.840644
1.360372
'''Get the access keys for the specified storage account. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. rgname (str): Azure resource group name. account_name (str): Name of the new storage account. Returns: HTTP response. JSON body of storage account keys. ''' endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourcegroups/', rgname, '/providers/Microsoft.Storage/storageAccounts/', account_name, '/listKeys', '?api-version=', STORAGE_API]) return do_post(endpoint, '', access_token)
def get_storage_account_keys(access_token, subscription_id, rgname, account_name)
Get the access keys for the specified storage account. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. rgname (str): Azure resource group name. account_name (str): Name of the new storage account. Returns: HTTP response. JSON body of storage account keys.
2.578878
1.984497
1.299512
'''Returns storage usage and quota information for the specified subscription. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. Returns: HTTP response. JSON body of storage account usage. ''' endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/providers/Microsoft.Storage/locations/', location, '/usages', '?api-version=', STORAGE_API]) return do_get(endpoint, access_token)
def get_storage_usage(access_token, subscription_id, location)
Returns storage usage and quota information for the specified subscription. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. Returns: HTTP response. JSON body of storage account usage.
3.436211
2.341439
1.467564
'''List the storage accounts in the specified resource group. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. rgname (str): Azure resource group name. Returns: HTTP response. JSON body list of storage accounts. ''' endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourcegroups/', rgname, '/providers/Microsoft.Storage/storageAccounts', '?api-version=', STORAGE_API]) return do_get(endpoint, access_token)
def list_storage_accounts_rg(access_token, subscription_id, rgname)
List the storage accounts in the specified resource group. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. rgname (str): Azure resource group name. Returns: HTTP response. JSON body list of storage accounts.
2.576079
2.090203
1.232454
'''List the storage accounts in the specified subscription. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. Returns: HTTP response. JSON body list of storage accounts. ''' endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/providers/Microsoft.Storage/storageAccounts', '?api-version=', STORAGE_API]) return do_get(endpoint, access_token)
def list_storage_accounts_sub(access_token, subscription_id)
List the storage accounts in the specified subscription. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. Returns: HTTP response. JSON body list of storage accounts.
2.998379
2.393229
1.252859
'''Main routine.''' # validate command line arguments arg_parser = argparse.ArgumentParser() arg_parser.add_argument('--add', '-a', action='store_true', default=False, help='add a key vault') arg_parser.add_argument('--delete', '-d', action='store_true', default=False, help='delete a key vault') arg_parser.add_argument('--name', '-n', required=True, action='store', help='Name') arg_parser.add_argument('--rgname', '-g', required=True, action='store', help='Resource Group Name') arg_parser.add_argument('--location', '-l', required=True, action='store', help='Location, e.g. eastus') arg_parser.add_argument('--verbose', '-v', action='store_true', default=False, help='Print operational details') args = arg_parser.parse_args() name = args.name rgname = args.rgname location = args.location if args.add is True and args.delete is True: sys.exit('Specify --add or --delete, not both.') if args.add is False and args.delete is False: sys.exit('No operation specified, use --add or --delete.') if 'ACC_CLOUD' in os.environ and 'MSI_ENDPOINT' in os.environ: endpoint = os.environ['MSI_ENDPOINT'] else: sys.exit('Not running in cloud shell or MSI_ENDPOINT not set') # get Azure auth token if args.verbose is True: print('Getting Azure token from MSI endpoint..') access_token = azurerm.get_access_token_from_cli() if args.verbose is True: print('Getting Azure subscription ID from MSI endpoint..') subscription_id = azurerm.get_subscription_from_cli() # execute specified operation if args.add is True: # create a key vault # get Azure tenant ID if args.verbose is True: print('Getting list of tenant IDs...') tenants = azurerm.list_tenants(access_token) tenant_id = tenants['value'][0]['tenantId'] if args.verbose is True: print('My tenantId = ' + tenant_id) # get Graph object ID if args.verbose is True: print('Querying graph...') object_id = azurerm.get_object_id_from_graph() if args.verbose is True: print('My object ID = ' + object_id) # create key vault ret = azurerm.create_keyvault(access_token, subscription_id, rgname, name, location, tenant_id=tenant_id, object_id=object_id) if ret.status_code == 200: print('Successsfully created key vault: ' + name) print('Vault URI: ' + ret.json()['properties']['vaultUri']) else: print('Return code ' + str(ret.status_code) + ' from create_keyvault().') print(ret.text) # else delete named key vault else: ret = azurerm.delete_keyvault(access_token, subscription_id, rgname, name) if ret.status_code == 200: print('Successsfully deleted key vault: ' + name) else: print('Return code ' + str(ret.status_code) + ' from delete_keyvault().') print(ret.text)
def main()
Main routine.
2.263692
2.261711
1.000876
'''get resource group name from the id string''' rgidx = idstr.find('resourceGroups/') providx = idstr.find('/providers/') return idstr[rgidx + 15:providx]
def rgfromid(idstr)
get resource group name from the id string
4.711065
4.220927
1.116121
'''main routine''' # Load Azure app defaults try: with open('azurermconfig.json') as config_file: config_data = json.load(config_file) except FileNotFoundError: sys.exit('Error: Expecting azurermconfig.json in current folder') tenant_id = config_data['tenantId'] app_id = config_data['appId'] app_secret = config_data['appSecret'] subscription_id = config_data['subscriptionId'] access_token = azurerm.get_access_token(tenant_id, app_id, app_secret) # list storage accounts per sub sa_list = azurerm.list_storage_accounts_sub(access_token, subscription_id) # print(sa_list) for sta in sa_list['value']: print(sta['name'] + ', ' + sta['properties']['primaryLocation'] + ', ' + rgfromid(sta['id'])) # get storage account quota quota_info = azurerm.get_storage_usage(access_token, subscription_id) used = quota_info['value'][0]['currentValue'] limit = quota_info["value"][0]["limit"] print('\nUsing ' + str(used) + ' accounts out of ' + str(limit) + '.')
def main()
main routine
2.443724
2.452374
0.996473
'''Main routine.''' # process arguments if len(sys.argv) < 3: usage() rgname = sys.argv[1] vmss = sys.argv[2] # Load Azure app defaults try: with open('azurermconfig.json') as config_file: config_data = json.load(config_file) except FileNotFoundError: sys.exit("Error: Expecting azurermconfig.json in current folder") tenant_id = config_data['tenantId'] app_id = config_data['appId'] app_secret = config_data['appSecret'] subscription_id = config_data['subscriptionId'] access_token = azurerm.get_access_token(tenant_id, app_id, app_secret) # loop through resource groups instances = azurerm.list_vmss_vm_instance_view(access_token, subscription_id, rgname, vmss) print(json.dumps(instances, sort_keys=False, indent=2, separators=(',', ': ')))
def main()
Main routine.
2.017092
2.017042
1.000025
'''Check media service name availability. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. msname (str): media service name. Returns: HTTP response. ''' endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/providers/microsoft.media/CheckNameAvailability?', 'api-version=', MEDIA_API]) ms_body = {'name': msname} ms_body['type'] = 'mediaservices' body = json.dumps(ms_body) return do_post(endpoint, body, access_token)
def check_media_service_name_availability(access_token, subscription_id, msname)
Check media service name availability. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. msname (str): media service name. Returns: HTTP response.
2.89135
2.622309
1.102597
'''Create a media service in a resource group. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. rgname (str): Azure resource group name. location (str): Azure data center location. E.g. westus. stoname (str): Azure storage account name. msname (str): Media service name. Returns: HTTP response. JSON body. ''' endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourceGroups/', rgname, '/providers/microsoft.media/mediaservices/', msname, '?api-version=', MEDIA_API]) ms_body = {'name': msname} ms_body['location'] = location sub_id_str = '/subscriptions/' + subscription_id + '/resourceGroups/' + rgname + \ '/providers/Microsoft.Storage/storageAccounts/' + stoname storage_account = {'id': sub_id_str} storage_account['isPrimary'] = True properties = {'storageAccounts': [storage_account]} ms_body['properties'] = properties body = json.dumps(ms_body) return do_put(endpoint, body, access_token)
def create_media_service_rg(access_token, subscription_id, rgname, location, stoname, msname)
Create a media service in a resource group. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. rgname (str): Azure resource group name. location (str): Azure data center location. E.g. westus. stoname (str): Azure storage account name. msname (str): Media service name. Returns: HTTP response. JSON body.
2.257978
1.945683
1.160506
'''Delete a media service. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. rgname (str): Azure resource group name. msname (str): Media service name. Returns: HTTP response. ''' endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourceGroups/', rgname, '/providers/microsoft.media/mediaservices/', msname, '?api-version=', MEDIA_API]) return do_delete(endpoint, access_token)
def delete_media_service_rg(access_token, subscription_id, rgname, msname)
Delete a media service. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. rgname (str): Azure resource group name. msname (str): Media service name. Returns: HTTP response.
2.248359
2.064215
1.089208
'''list the media endpoint keys in a media service Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. rgname (str): Azure resource group name. msname (str): Media service name. Returns: HTTP response. JSON body. ''' endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourceGroups/', rgname, '/providers/microsoft.media/', '/mediaservices/', msname, '/listKeys?api-version=', MEDIA_API]) return do_get(endpoint, access_token)
def list_media_endpoint_keys(access_token, subscription_id, rgname, msname)
list the media endpoint keys in a media service Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. rgname (str): Azure resource group name. msname (str): Media service name. Returns: HTTP response. JSON body.
2.61921
2.183841
1.199359
'''List the media services in a subscription. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. Returns: HTTP response. JSON body. ''' endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/providers/microsoft.media/mediaservices?api-version=', MEDIA_API]) return do_get(endpoint, access_token)
def list_media_services(access_token, subscription_id)
List the media services in a subscription. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. Returns: HTTP response. JSON body.
3.038769
2.560761
1.186666
'''List the media services in a resource group. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. rgname (str): Azure resource group name. Returns: HTTP response. JSON body. ''' endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourceGroups/', rgname, '/providers/microsoft.media/mediaservices?api-version=', MEDIA_API]) return do_get(endpoint, access_token)
def list_media_services_rg(access_token, subscription_id, rgname)
List the media services in a resource group. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. rgname (str): Azure resource group name. Returns: HTTP response. JSON body.
2.524836
2.1796
1.158394
'''Get Media Services Authentication Token. Args: accountname (str): Azure Media Services account name. accountkey (str): Azure Media Services Key. Returns: HTTP response. JSON body. ''' accountkey_encoded = urllib.parse.quote(accountkey, safe='') body = "grant_type=client_credentials&client_id=" + accountname + \ "&client_secret=" + accountkey_encoded + " &scope=urn%3aWindowsAzureMediaServices" return do_ams_auth(ams_auth_endpoint, body)
def get_ams_access_token(accountname, accountkey)
Get Media Services Authentication Token. Args: accountname (str): Azure Media Services account name. accountkey (str): Azure Media Services Key. Returns: HTTP response. JSON body.
4.006927
2.98786
1.341069
'''Create Media Service Asset. Args: access_token (str): A valid Azure authentication token. name (str): Media Service Asset Name. options (str): Media Service Options. Returns: HTTP response. JSON body. ''' path = '/Assets' endpoint = ''.join([ams_rest_endpoint, path]) body = '{"Name": "' + name + '", "Options": "' + str(options) + '"}' return do_ams_post(endpoint, path, body, access_token)
def create_media_asset(access_token, name, options="0")
Create Media Service Asset. Args: access_token (str): A valid Azure authentication token. name (str): Media Service Asset Name. options (str): Media Service Options. Returns: HTTP response. JSON body.
3.859087
2.791196
1.382592
'''Create Media Service Asset File. Args: access_token (str): A valid Azure authentication token. parent_asset_id (str): Media Service Parent Asset ID. name (str): Media Service Asset Name. is_primary (str): Media Service Primary Flag. is_encrypted (str): Media Service Encryption Flag. encryption_scheme (str): Media Service Encryption Scheme. encryptionkey_id (str): Media Service Encryption Key ID. Returns: HTTP response. JSON body. ''' path = '/Files' endpoint = ''.join([ams_rest_endpoint, path]) if encryption_scheme == "StorageEncryption": body = '{ \ "IsEncrypted": "' + is_encrypted + '", \ "EncryptionScheme": "' + encryption_scheme + '", \ "EncryptionVersion": "' + "1.0" + '", \ "EncryptionKeyId": "' + encryptionkey_id + '", \ "IsPrimary": "' + is_primary + '", \ "MimeType": "video/mp4", \ "Name": "' + name + '", \ "ParentAssetId": "' + parent_asset_id + '" \ }' else: body = '{ \ "IsPrimary": "' + is_primary + '", \ "MimeType": "video/mp4", \ "Name": "' + name + '", \ "ParentAssetId": "' + parent_asset_id + '" \ }' return do_ams_post(endpoint, path, body, access_token)
def create_media_assetfile(access_token, parent_asset_id, name, is_primary="false", \ is_encrypted="false", encryption_scheme="None", encryptionkey_id="None")
Create Media Service Asset File. Args: access_token (str): A valid Azure authentication token. parent_asset_id (str): Media Service Parent Asset ID. name (str): Media Service Asset Name. is_primary (str): Media Service Primary Flag. is_encrypted (str): Media Service Encryption Flag. encryption_scheme (str): Media Service Encryption Scheme. encryptionkey_id (str): Media Service Encryption Key ID. Returns: HTTP response. JSON body.
2.029035
1.746653
1.161671
'''Create Media Service SAS Locator. Args: access_token (str): A valid Azure authentication token. asset_id (str): Media Service Asset ID. accesspolicy_id (str): Media Service Access Policy ID. Returns: HTTP response. JSON body. ''' path = '/Locators' endpoint = ''.join([ams_rest_endpoint, path]) body = '{ \ "AccessPolicyId":"' + accesspolicy_id + '", \ "AssetId":"' + asset_id + '", \ "Type":1 \ }' return do_ams_post(endpoint, path, body, access_token)
def create_sas_locator(access_token, asset_id, accesspolicy_id)
Create Media Service SAS Locator. Args: access_token (str): A valid Azure authentication token. asset_id (str): Media Service Asset ID. accesspolicy_id (str): Media Service Access Policy ID. Returns: HTTP response. JSON body.
3.307904
2.601484
1.271545
'''Create Media Service Asset Delivery Policy. Args: access_token (str): A valid Azure authentication token. ams_account (str): Media Service Account. Returns: HTTP response. JSON body. ''' path = '/AssetDeliveryPolicies' endpoint = ''.join([ams_rest_endpoint, path]) body = '{ \ "Name":"AssetDeliveryPolicy", \ "AssetDeliveryProtocol":"4", \ "AssetDeliveryPolicyType":"3", \ "AssetDeliveryConfiguration":"[{ \ \\"Key\\":\\"2\\", \ \\"Value\\":\\"' + key_delivery_url + '\\"}]" \ }' return do_ams_post(endpoint, path, body, access_token)
def create_asset_delivery_policy(access_token, ams_account, key_delivery_url)
Create Media Service Asset Delivery Policy. Args: access_token (str): A valid Azure authentication token. ams_account (str): Media Service Account. Returns: HTTP response. JSON body.
4.434733
3.502735
1.266077
'''Create Media Service Content Key Authorization Policy. Args: access_token (str): A valid Azure authentication token. content (str): Content Payload. Returns: HTTP response. JSON body. ''' path = '/ContentKeyAuthorizationPolicies' endpoint = ''.join([ams_rest_endpoint, path]) body = content return do_ams_post(endpoint, path, body, access_token)
def create_contentkey_authorization_policy(access_token, content)
Create Media Service Content Key Authorization Policy. Args: access_token (str): A valid Azure authentication token. content (str): Content Payload. Returns: HTTP response. JSON body.
5.503022
3.503402
1.570765
'''Create Media Service Content Key Authorization Policy Options. Args: access_token (str): A valid Azure authentication token. key_delivery_type (str): A Media Service Content Key Authorization Policy Delivery Type. name (str): A Media Service Contenty Key Authorization Policy Name. key_restiction_type (str): A Media Service Contenty Key Restriction Type. Returns: HTTP response. JSON body. ''' path = '/ContentKeyAuthorizationPolicyOptions' endpoint = ''.join([ams_rest_endpoint, path]) body = '{ \ "Name":"policy",\ "KeyDeliveryType":"' + key_delivery_type + '", \ "KeyDeliveryConfiguration":"", \ "Restrictions":[{ \ "Name":"' + name + '", \ "KeyRestrictionType":"' + key_restriction_type + '", \ "Requirements":null \ }] \ }' return do_ams_post(endpoint, path, body, access_token, "json_only")
def create_contentkey_authorization_policy_options(access_token, key_delivery_type="2", \ name="HLS Open Authorization Policy", key_restriction_type="0")
Create Media Service Content Key Authorization Policy Options. Args: access_token (str): A valid Azure authentication token. key_delivery_type (str): A Media Service Content Key Authorization Policy Delivery Type. name (str): A Media Service Contenty Key Authorization Policy Name. key_restiction_type (str): A Media Service Contenty Key Restriction Type. Returns: HTTP response. JSON body.
4.46339
3.022276
1.476831
'''Create Media Service OnDemand Streaming Locator. Args: access_token (str): A valid Azure authentication token. encoded_asset_id (str): A Media Service Encoded Asset ID. pid (str): A Media Service Encoded PID. starttime (str): A Media Service Starttime. Returns: HTTP response. JSON body. ''' path = '/Locators' endpoint = ''.join([ams_rest_endpoint, path]) if starttime is None: body = '{ \ "AccessPolicyId":"' + pid + '", \ "AssetId":"' + encoded_asset_id + '", \ "Type": "2" \ }' else: body = '{ \ "AccessPolicyId":"' + pid + '", \ "AssetId":"' + encoded_asset_id + '", \ "StartTime":"' + str(starttime) + '", \ "Type": "2" \ }' return do_ams_post(endpoint, path, body, access_token, "json_only")
def create_ondemand_streaming_locator(access_token, encoded_asset_id, pid, starttime=None)
Create Media Service OnDemand Streaming Locator. Args: access_token (str): A valid Azure authentication token. encoded_asset_id (str): A Media Service Encoded Asset ID. pid (str): A Media Service Encoded PID. starttime (str): A Media Service Starttime. Returns: HTTP response. JSON body.
2.870462
2.285549
1.255918
'''Create Media Service Asset Access Policy. Args: access_token (str): A valid Azure authentication token. name (str): A Media Service Asset Access Policy Name. duration (str): A Media Service duration. permission (str): A Media Service permission. Returns: HTTP response. JSON body. ''' path = '/AccessPolicies' endpoint = ''.join([ams_rest_endpoint, path]) body = '{ \ "Name": "' + str(name) + '", \ "DurationInMinutes": "' + duration + '", \ "Permissions": "' + permission + '" \ }' return do_ams_post(endpoint, path, body, access_token)
def create_asset_accesspolicy(access_token, name, duration, permission="1")
Create Media Service Asset Access Policy. Args: access_token (str): A valid Azure authentication token. name (str): A Media Service Asset Access Policy Name. duration (str): A Media Service duration. permission (str): A Media Service permission. Returns: HTTP response. JSON body.
3.370623
2.434806
1.38435
'''Create Media Service Streaming Endpoint. Args: access_token (str): A valid Azure authentication token. name (str): A Media Service Streaming Endpoint Name. description (str): A Media Service Streaming Endpoint Description. scale_units (str): A Media Service Scale Units Number. Returns: HTTP response. JSON body. ''' path = '/StreamingEndpoints' endpoint = ''.join([ams_rest_endpoint, path]) body = '{ \ "Id":null, \ "Name":"' + name + '", \ "Description":"' + description + '", \ "Created":"0001-01-01T00:00:00", \ "LastModified":"0001-01-01T00:00:00", \ "State":null, \ "HostName":null, \ "ScaleUnits":"' + scale_units + '", \ "CrossSiteAccessPolicies":{ \ "ClientAccessPolicy":"<access-policy><cross-domain-access><policy><allow-from http-request-headers=\\"*\\"><domain uri=\\"http://*\\" /></allow-from><grant-to><resource path=\\"/\\" include-subpaths=\\"false\\" /></grant-to></policy></cross-domain-access></access-policy>", \ "CrossDomainPolicy":"<?xml version=\\"1.0\\"?><!DOCTYPE cross-domain-policy SYSTEM \\"http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd\\"><cross-domain-policy><allow-access-from domain=\\"*\\" /></cross-domain-policy>" \ } \ }' return do_ams_post(endpoint, path, body, access_token)
def create_streaming_endpoint(access_token, name, description="New Streaming Endpoint", \ scale_units="1")
Create Media Service Streaming Endpoint. Args: access_token (str): A valid Azure authentication token. name (str): A Media Service Streaming Endpoint Name. description (str): A Media Service Streaming Endpoint Description. scale_units (str): A Media Service Scale Units Number. Returns: HTTP response. JSON body.
2.737487
2.407971
1.136844
'''Scale Media Service Streaming Endpoint. Args: access_token (str): A valid Azure authentication token. streaming_endpoint_id (str): A Media Service Streaming Endpoint ID. scale_units (str): A Media Service Scale Units Number. Returns: HTTP response. JSON body. ''' path = '/StreamingEndpoints' full_path = ''.join([path, "('", streaming_endpoint_id, "')", "/Scale"]) full_path_encoded = urllib.parse.quote(full_path, safe='') endpoint = ''.join([ams_rest_endpoint, full_path_encoded]) body = '{"scaleUnits": "' + str(scale_units) + '"}' return do_ams_post(endpoint, full_path_encoded, body, access_token)
def scale_streaming_endpoint(access_token, streaming_endpoint_id, scale_units)
Scale Media Service Streaming Endpoint. Args: access_token (str): A valid Azure authentication token. streaming_endpoint_id (str): A Media Service Streaming Endpoint ID. scale_units (str): A Media Service Scale Units Number. Returns: HTTP response. JSON body.
3.356834
2.608042
1.287109
'''Link Media Service Asset and Content Key. Args: access_token (str): A valid Azure authentication token. asset_id (str): A Media Service Asset ID. encryption_id (str): A Media Service Encryption ID. ams_redirected_rest_endpoint (str): A Media Service Redirected Endpoint. Returns: HTTP response. JSON body. ''' path = '/Assets' full_path = ''.join([path, "('", asset_id, "')", "/$links/ContentKeys"]) full_path_encoded = urllib.parse.quote(full_path, safe='') endpoint = ''.join([ams_rest_endpoint, full_path_encoded]) uri = ''.join([ams_redirected_rest_endpoint, 'ContentKeys', "('", encryptionkey_id, "')"]) body = '{"uri": "' + uri + '"}' return do_ams_post(endpoint, full_path_encoded, body, access_token)
def link_asset_content_key(access_token, asset_id, encryptionkey_id, ams_redirected_rest_endpoint)
Link Media Service Asset and Content Key. Args: access_token (str): A valid Azure authentication token. asset_id (str): A Media Service Asset ID. encryption_id (str): A Media Service Encryption ID. ams_redirected_rest_endpoint (str): A Media Service Redirected Endpoint. Returns: HTTP response. JSON body.
3.277396
2.507756
1.306904
'''Link Media Service Content Key Authorization Policy. Args: access_token (str): A valid Azure authentication token. ckap_id (str): A Media Service Asset Content Key Authorization Policy ID. options_id (str): A Media Service Content Key Authorization Policy Options . ams_redirected_rest_endpoint (str): A Media Service Redirected Endpoint. Returns: HTTP response. JSON body. ''' path = '/ContentKeyAuthorizationPolicies' full_path = ''.join([path, "('", ckap_id, "')", "/$links/Options"]) full_path_encoded = urllib.parse.quote(full_path, safe='') endpoint = ''.join([ams_rest_endpoint, full_path_encoded]) uri = ''.join([ams_redirected_rest_endpoint, 'ContentKeyAuthorizationPolicyOptions', \ "('", options_id, "')"]) body = '{"uri": "' + uri + '"}' return do_ams_post(endpoint, full_path_encoded, body, access_token, "json_only", "1.0;NetFx")
def link_contentkey_authorization_policy(access_token, ckap_id, options_id, \ ams_redirected_rest_endpoint)
Link Media Service Content Key Authorization Policy. Args: access_token (str): A valid Azure authentication token. ckap_id (str): A Media Service Asset Content Key Authorization Policy ID. options_id (str): A Media Service Content Key Authorization Policy Options . ams_redirected_rest_endpoint (str): A Media Service Redirected Endpoint. Returns: HTTP response. JSON body.
3.702201
2.745908
1.348261
'''Add Media Service Authorization Policy. Args: access_token (str): A valid Azure authentication token. ck_id (str): A Media Service Asset Content Key ID. options_id (str): A Media Service OID. Returns: HTTP response. JSON body. ''' path = '/ContentKeys' body = '{"AuthorizationPolicyId":"' + oid + '"}' return helper_add(access_token, ck_id, path, body)
def add_authorization_policy(access_token, ck_id, oid)
Add Media Service Authorization Policy. Args: access_token (str): A valid Azure authentication token. ck_id (str): A Media Service Asset Content Key ID. options_id (str): A Media Service OID. Returns: HTTP response. JSON body.
5.660378
2.599818
2.177221
'''Update Media Service Asset File. Args: access_token (str): A valid Azure authentication token. parent_asset_id (str): A Media Service Asset Parent Asset ID. asset_id (str): A Media Service Asset Asset ID. content_length (str): A Media Service Asset Content Length. name (str): A Media Service Asset name. Returns: HTTP response. JSON body. ''' path = '/Files' full_path = ''.join([path, "('", asset_id, "')"]) full_path_encoded = urllib.parse.quote(full_path, safe='') endpoint = ''.join([ams_rest_endpoint, full_path_encoded]) body = '{ \ "ContentFileSize": "' + str(content_length) + '", \ "Id": "' + asset_id + '", \ "MimeType": "video/mp4", \ "Name": "' + name + '", \ "ParentAssetId": "' + parent_asset_id + '" \ }' return do_ams_patch(endpoint, full_path_encoded, body, access_token)
def update_media_assetfile(access_token, parent_asset_id, asset_id, content_length, name)
Update Media Service Asset File. Args: access_token (str): A valid Azure authentication token. parent_asset_id (str): A Media Service Asset Parent Asset ID. asset_id (str): A Media Service Asset Asset ID. content_length (str): A Media Service Asset Content Length. name (str): A Media Service Asset name. Returns: HTTP response. JSON body.
2.783747
2.228632
1.249083
'''Get Media Services Key Delivery URL. Args: access_token (str): A valid Azure authentication token. ck_id (str): A Media Service Content Key ID. key_type (str): A Media Service key Type. Returns: HTTP response. JSON body. ''' path = '/ContentKeys' full_path = ''.join([path, "('", ck_id, "')", "/GetKeyDeliveryUrl"]) endpoint = ''.join([ams_rest_endpoint, full_path]) body = '{"keyDeliveryType": "' + key_type + '"}' return do_ams_post(endpoint, full_path, body, access_token)
def get_key_delivery_url(access_token, ck_id, key_type)
Get Media Services Key Delivery URL. Args: access_token (str): A valid Azure authentication token. ck_id (str): A Media Service Content Key ID. key_type (str): A Media Service key Type. Returns: HTTP response. JSON body.
4.172739
2.857602
1.460224
'''Get Media Service Encode Mezanine Asset. Args: access_token (str): A valid Azure authentication token. processor_id (str): A Media Service Processor ID. asset_id (str): A Media Service Asset ID. output_assetname (str): A Media Service Asset Name. json_profile (str): A Media Service JSON Profile. Returns: HTTP response. JSON body. ''' path = '/Jobs' endpoint = ''.join([ams_rest_endpoint, path]) assets_path = ''.join(["/Assets", "('", asset_id, "')"]) assets_path_encoded = urllib.parse.quote(assets_path, safe='') endpoint_assets = ''.join([ams_rest_endpoint, assets_path_encoded]) body = '{ \ "Name":"' + output_assetname + '", \ "InputMediaAssets":[{ \ "__metadata":{ \ "uri":"' + endpoint_assets + '" \ } \ }], \ "Tasks":[{ \ "Configuration":\'' + json_profile + '\', \ "MediaProcessorId":"' + processor_id + '", \ "TaskBody":"<?xml version=\\"1.0\\" encoding=\\"utf-16\\"?><taskBody><inputAsset>JobInputAsset(0)</inputAsset><outputAsset assetCreationOptions=\\"0\\" assetName=\\"' + output_assetname + '\\">JobOutputAsset(0)</outputAsset></taskBody>" \ }] \ }' return do_ams_post(endpoint, path, body, access_token)
def encode_mezzanine_asset(access_token, processor_id, asset_id, output_assetname, json_profile)
Get Media Service Encode Mezanine Asset. Args: access_token (str): A valid Azure authentication token. processor_id (str): A Media Service Processor ID. asset_id (str): A Media Service Asset ID. output_assetname (str): A Media Service Asset Name. json_profile (str): A Media Service JSON Profile. Returns: HTTP response. JSON body.
3.660153
3.058254
1.196812
'''Helper Function to add strings to a URL path. Args: access_token (str): A valid Azure authentication token. ck_id (str): A CK ID. path (str): A URL Path. body (str): A Body. Returns: HTTP response. JSON body. ''' full_path = ''.join([path, "('", ck_id, "')"]) full_path_encoded = urllib.parse.quote(full_path, safe='') endpoint = ''.join([ams_rest_endpoint, full_path_encoded]) return do_ams_put(endpoint, full_path_encoded, body, access_token, "json_only", "1.0;NetFx")
def helper_add(access_token, ck_id, path, body)
Helper Function to add strings to a URL path. Args: access_token (str): A valid Azure authentication token. ck_id (str): A CK ID. path (str): A URL Path. body (str): A Body. Returns: HTTP response. JSON body.
4.771708
3.028078
1.575821
'''Helper Function to list a URL path. Args: access_token (str): A valid Azure authentication token. oid (str): An OID. path (str): A URL Path. Returns: HTTP response. JSON body. ''' if oid != "": path = ''.join([path, "('", oid, "')"]) endpoint = ''.join([ams_rest_endpoint, path]) return do_ams_get(endpoint, path, access_token)
def helper_list(access_token, oid, path)
Helper Function to list a URL path. Args: access_token (str): A valid Azure authentication token. oid (str): An OID. path (str): A URL Path. Returns: HTTP response. JSON body.
5.051048
2.952135
1.710982
'''Helper Function to delete a Object at a URL path. Args: access_token (str): A valid Azure authentication token. oid (str): An OID. path (str): A URL Path. Returns: HTTP response. JSON body. ''' full_path = ''.join([path, "('", oid, "')"]) full_path_encoded = urllib.parse.quote(full_path, safe='') endpoint = ''.join([ams_rest_endpoint, full_path_encoded]) return do_ams_delete(endpoint, full_path_encoded, access_token)
def helper_delete(access_token, oid, path)
Helper Function to delete a Object at a URL path. Args: access_token (str): A valid Azure authentication token. oid (str): An OID. path (str): A URL Path. Returns: HTTP response. JSON body.
4.273167
2.618536
1.631891
'''AUX Function to translate the (numeric) state of a Job. Args: nr (int): A valid number to translate. Returns: HTTP response. JSON body. ''' code_description = "" if code == "0": code_description = "Queued" if code == "1": code_description = "Scheduled" if code == "2": code_description = "Processing" if code == "3": code_description = "Finished" if code == "4": code_description = "Error" if code == "5": code_description = "Canceled" if code == "6": code_description = "Canceling" return code_description
def translate_job_state(code)
AUX Function to translate the (numeric) state of a Job. Args: nr (int): A valid number to translate. Returns: HTTP response. JSON body.
3.263705
1.88148
1.734648
'''List all operations involved in a given deployment. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. rg_name (str): Azure resource group name. Returns: HTTP response. JSON body. ''' endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourcegroups/', rg_name, '/providers/Microsoft.Resources/deployments/', deployment_name, '/operations', '?api-version=', BASE_API]) return do_get(endpoint, access_token)
def list_deployment_operations(access_token, subscription_id, rg_name, deployment_name)
List all operations involved in a given deployment. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. rg_name (str): Azure resource group name. Returns: HTTP response. JSON body.
2.674413
2.037684
1.312477
'''Create a load balancer with inbound NAT pools. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. lb_name (str): Name of the new load balancer. public_ip_id (str): Public IP address resource id. fe_start_port (int): Start of front-end port range. fe_end_port (int): End of front-end port range. backend_port (int): Back end port for VMs. location (str): Azure data center location. E.g. westus. Returns: HTTP response. Load Balancer JSON body. ''' endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourceGroups/', resource_group, '/providers/Microsoft.Network/loadBalancers/', lb_name, '?api-version=', NETWORK_API]) lb_body = {'location': location} frontendipcconfig = {'name': 'LoadBalancerFrontEnd'} fipc_properties = {'publicIPAddress': {'id': public_ip_id}} frontendipcconfig['properties'] = fipc_properties properties = {'frontendIPConfigurations': [frontendipcconfig]} properties['backendAddressPools'] = [{'name': 'bepool'}] inbound_natpool = {'name': 'natpool'} lbfe_id = '/subscriptions/' + subscription_id + '/resourceGroups/' + resource_group + \ '/providers/Microsoft.Network/loadBalancers/' + lb_name + \ '/frontendIPConfigurations/LoadBalancerFrontEnd' ibnp_properties = {'frontendIPConfiguration': {'id': lbfe_id}} ibnp_properties['protocol'] = 'tcp' ibnp_properties['frontendPortRangeStart'] = fe_start_port ibnp_properties['frontendPortRangeEnd'] = fe_end_port ibnp_properties['backendPort'] = backend_port inbound_natpool['properties'] = ibnp_properties properties['inboundNatPools'] = [inbound_natpool] lb_body['properties'] = properties body = json.dumps(lb_body) return do_put(endpoint, body, access_token)
def create_lb_with_nat_pool(access_token, subscription_id, resource_group, lb_name, public_ip_id, fe_start_port, fe_end_port, backend_port, location)
Create a load balancer with inbound NAT pools. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. lb_name (str): Name of the new load balancer. public_ip_id (str): Public IP address resource id. fe_start_port (int): Start of front-end port range. fe_end_port (int): End of front-end port range. backend_port (int): Back end port for VMs. location (str): Azure data center location. E.g. westus. Returns: HTTP response. Load Balancer JSON body.
2.195898
1.813532
1.210841
'''Create a network interface with an associated public ip address. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. nic_name (str): Name of the new NIC. public_ip_id (str): Public IP address resource id. subnetid (str): Subnet resource id. location (str): Azure data center location. E.g. westus. nsg_id (str): Optional Network Secruity Group resource id. Returns: HTTP response. NIC JSON body. ''' endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourceGroups/', resource_group, '/providers/Microsoft.Network/networkInterfaces/', nic_name, '?api-version=', NETWORK_API]) nic_body = {'location': location} ipconfig = {'name': 'ipconfig1'} ipc_properties = {'privateIPAllocationMethod': 'Dynamic'} ipc_properties['publicIPAddress'] = {'id': public_ip_id} ipc_properties['subnet'] = {'id': subnet_id} ipconfig['properties'] = ipc_properties properties = {'ipConfigurations': [ipconfig]} if nsg_id is not None: properties['networkSecurityGroup'] = {'id': nsg_id} nic_body['properties'] = properties body = json.dumps(nic_body) return do_put(endpoint, body, access_token)
def create_nic(access_token, subscription_id, resource_group, nic_name, public_ip_id, subnet_id, location, nsg_id=None)
Create a network interface with an associated public ip address. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. nic_name (str): Name of the new NIC. public_ip_id (str): Public IP address resource id. subnetid (str): Subnet resource id. location (str): Azure data center location. E.g. westus. nsg_id (str): Optional Network Secruity Group resource id. Returns: HTTP response. NIC JSON body.
2.217839
1.699425
1.305053
'''Create network security group (use create_nsg_rule() to add rules to it). Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. nsg_name (str): Name of the new NSG. location (str): Azure data center location. E.g. westus. Returns: HTTP response. NSG JSON body. ''' endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourceGroups/', resource_group, '/providers/Microsoft.Network/networkSecurityGroups/', nsg_name, '?api-version=', NETWORK_API]) nsg_body = {'location': location} body = json.dumps(nsg_body) return do_put(endpoint, body, access_token)
def create_nsg(access_token, subscription_id, resource_group, nsg_name, location)
Create network security group (use create_nsg_rule() to add rules to it). Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. nsg_name (str): Name of the new NSG. location (str): Azure data center location. E.g. westus. Returns: HTTP response. NSG JSON body.
2.555542
1.717314
1.488104
'''Create network security group rule. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. nsg_name (str): Name of the Network Security Group. nsg_rule_name (str): Name of the new rule. description (str): Description. protocol (str): Optional protocol. Default Tcp. source_range (str): Optional source IP range. Default '*'. destination_range (str): Destination IP range. Default *'. source_prefix (str): Source DNS prefix. Default '*'. destination_prefix (str): Destination prefix. Default '*'. access (str): Allow or deny rule. Default Allow. priority: Relative priority. Default 100. direction: Inbound or Outbound. Default Inbound. Returns: HTTP response. NSG JSON rule body. ''' endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourceGroups/', resource_group, '/providers/Microsoft.Network/networkSecurityGroups/', nsg_name, '/securityRules/', nsg_rule_name, '?api-version=', NETWORK_API]) properties = {'description': description} properties['protocol'] = protocol properties['sourcePortRange'] = source_range properties['destinationPortRange'] = destination_range properties['sourceAddressPrefix'] = source_prefix properties['destinationAddressPrefix'] = destination_prefix properties['access'] = access properties['priority'] = priority properties['direction'] = direction ip_body = {'properties': properties} body = json.dumps(ip_body) return do_put(endpoint, body, access_token)
def create_nsg_rule(access_token, subscription_id, resource_group, nsg_name, nsg_rule_name, description, protocol='Tcp', source_range='*', destination_range='*', source_prefix='*', destination_prefix='*', access='Allow', priority=100, direction='Inbound')
Create network security group rule. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. nsg_name (str): Name of the Network Security Group. nsg_rule_name (str): Name of the new rule. description (str): Description. protocol (str): Optional protocol. Default Tcp. source_range (str): Optional source IP range. Default '*'. destination_range (str): Destination IP range. Default *'. source_prefix (str): Source DNS prefix. Default '*'. destination_prefix (str): Destination prefix. Default '*'. access (str): Allow or deny rule. Default Allow. priority: Relative priority. Default 100. direction: Inbound or Outbound. Default Inbound. Returns: HTTP response. NSG JSON rule body.
2.088711
1.433322
1.457252
'''Create a public ip address. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. public_ip_name (str): Name of the new public ip address resource. dns_label (str): DNS label to apply to the IP address. location (str): Azure data center location. E.g. westus. Returns: HTTP response. Public IP address JSON body. ''' endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourceGroups/', resource_group, '/providers/Microsoft.Network/publicIPAddresses/', public_ip_name, '?api-version=', NETWORK_API]) ip_body = {'location': location} properties = {'publicIPAllocationMethod': 'Dynamic'} properties['dnsSettings'] = {'domainNameLabel': dns_label} ip_body['properties'] = properties body = json.dumps(ip_body) return do_put(endpoint, body, access_token)
def create_public_ip(access_token, subscription_id, resource_group, public_ip_name, dns_label, location)
Create a public ip address. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. public_ip_name (str): Name of the new public ip address resource. dns_label (str): DNS label to apply to the IP address. location (str): Azure data center location. E.g. westus. Returns: HTTP response. Public IP address JSON body.
2.242872
1.676966
1.337458
'''Create a VNet with specified name and location. Optional subnet address prefix.. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. name (str): Name of the new VNet. location (str): Azure data center location. E.g. westus. address_prefix (str): Optional VNet address prefix. Default '10.0.0.0/16'. subnet_prefix (str): Optional subnet address prefix. Default '10.0.0.0/16'. nsg_id (str): Optional Netwrok Security Group resource Id. Default None. Returns: HTTP response. VNet JSON body. ''' endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourceGroups/', resource_group, '/providers/Microsoft.Network/virtualNetworks/', name, '?api-version=', NETWORK_API]) vnet_body = {'location': location} properties = {'addressSpace': {'addressPrefixes': [address_prefix]}} subnet = {'name': 'subnet'} subnet['properties'] = {'addressPrefix': subnet_prefix} if nsg_id is not None: subnet['properties']['networkSecurityGroup'] = {'id': nsg_id} properties['subnets'] = [subnet] vnet_body['properties'] = properties body = json.dumps(vnet_body) return do_put(endpoint, body, access_token)
def create_vnet(access_token, subscription_id, resource_group, name, location, address_prefix='10.0.0.0/16', subnet_prefix='10.0.0.0/16', nsg_id=None)
Create a VNet with specified name and location. Optional subnet address prefix.. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. name (str): Name of the new VNet. location (str): Azure data center location. E.g. westus. address_prefix (str): Optional VNet address prefix. Default '10.0.0.0/16'. subnet_prefix (str): Optional subnet address prefix. Default '10.0.0.0/16'. nsg_id (str): Optional Netwrok Security Group resource Id. Default None. Returns: HTTP response. VNet JSON body.
2.128733
1.517082
1.403176
'''Delete a load balancer. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. lb_name (str): Name of the load balancer. Returns: HTTP response. ''' endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourceGroups/', resource_group, '/providers/Microsoft.Network/loadBalancers/', lb_name, '?api-version=', NETWORK_API]) return do_delete(endpoint, access_token)
def delete_load_balancer(access_token, subscription_id, resource_group, lb_name)
Delete a load balancer. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. lb_name (str): Name of the load balancer. Returns: HTTP response.
2.097383
1.977217
1.060775
'''Delete a network interface. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. nic_name (str): Name of the NIC. Returns: HTTP response. ''' endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourceGroups/', resource_group, '/providers/Microsoft.Network/networkInterfaces/', nic_name, '?api-version=', NETWORK_API]) return do_delete(endpoint, access_token)
def delete_nic(access_token, subscription_id, resource_group, nic_name)
Delete a network interface. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. nic_name (str): Name of the NIC. Returns: HTTP response.
2.116684
1.945487
1.087997
'''Delete network security group. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. nsg_name (str): Name of the NSG. Returns: HTTP response. ''' endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourceGroups/', resource_group, '/providers/Microsoft.Network/networkSecurityGroups/', nsg_name, '?api-version=', NETWORK_API]) return do_delete(endpoint, access_token)
def delete_nsg(access_token, subscription_id, resource_group, nsg_name)
Delete network security group. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. nsg_name (str): Name of the NSG. Returns: HTTP response.
2.166039
1.913359
1.132061
'''Delete network security group rule. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. nsg_name (str): Name of the Network Security Group. nsg_rule_name (str): Name of the NSG rule. Returns: HTTP response. ''' endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourceGroups/', resource_group, '/providers/Microsoft.Network/networkSecurityGroups/', nsg_name, '/securityRules/', nsg_rule_name, '?api-version=', NETWORK_API]) return do_delete(endpoint, access_token)
def delete_nsg_rule(access_token, subscription_id, resource_group, nsg_name, nsg_rule_name)
Delete network security group rule. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. nsg_name (str): Name of the Network Security Group. nsg_rule_name (str): Name of the NSG rule. Returns: HTTP response.
1.96787
1.730457
1.137197
'''Delete a public ip addresses associated with a resource group. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. public_ip_name (str): Name of the public ip address resource. Returns: HTTP response. ''' endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourceGroups/', resource_group, '/providers/Microsoft.Network/publicIPAddresses/', public_ip_name, '?api-version=', NETWORK_API]) return do_delete(endpoint, access_token)
def delete_public_ip(access_token, subscription_id, resource_group, public_ip_name)
Delete a public ip addresses associated with a resource group. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. public_ip_name (str): Name of the public ip address resource. Returns: HTTP response.
2.26928
1.842129
1.231879
'''Delete a virtual network. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. name (str): Name of the VNet. Returns: HTTP response. VNet JSON body. ''' endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourceGroups/', resource_group, '/providers/Microsoft.Network/virtualNetworks/', name, '?api-version=', NETWORK_API]) return do_delete(endpoint, access_token)
def delete_vnet(access_token, subscription_id, resource_group, name)
Delete a virtual network. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. name (str): Name of the VNet. Returns: HTTP response. VNet JSON body.
2.393671
1.878664
1.274135
'''Get details about a load balancer inbound NAT rule. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. lb_name (str): Name of the load balancer. rule_name (str): Name of the NAT rule. Returns: HTTP response. JSON body of rule. ''' endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourceGroups/', resource_group, '/providers/Microsoft.Network/loadBalancers/', lb_name, '/inboundNatRules/', rule_name, '?api-version=', NETWORK_API]) return do_get(endpoint, access_token)
def get_lb_nat_rule(access_token, subscription_id, resource_group, lb_name, rule_name)
Get details about a load balancer inbound NAT rule. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. lb_name (str): Name of the load balancer. rule_name (str): Name of the NAT rule. Returns: HTTP response. JSON body of rule.
2.181256
1.749252
1.246965
'''List network usage and limits for a location. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. location (str): Azure data center location. E.g. westus. Returns: HTTP response. JSON body of network usage. ''' endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/providers/Microsoft.Network/locations/', location, '/usages?api-version=', NETWORK_API]) return do_get(endpoint, access_token)
def get_network_usage(access_token, subscription_id, location)
List network usage and limits for a location. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. location (str): Azure data center location. E.g. westus. Returns: HTTP response. JSON body of network usage.
3.029631
2.145551
1.412053
'''Get details about a network interface. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. nic_name (str): Name of the NIC. Returns: HTTP response. NIC JSON body. ''' endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourceGroups/', resource_group, '/providers/Microsoft.Network/networkInterfaces/', nic_name, '?api-version=', NETWORK_API]) return do_get(endpoint, access_token)
def get_nic(access_token, subscription_id, resource_group, nic_name)
Get details about a network interface. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. nic_name (str): Name of the NIC. Returns: HTTP response. NIC JSON body.
2.313424
1.840823
1.256733
'''Get details about the named public ip address. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. public_ip_name (str): Name of the public ip address resource. Returns: HTTP response. Public IP address JSON body. ''' endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourceGroups/', resource_group, '/providers/Microsoft.Network/', 'publicIPAddresses/', ip_name, '?api-version=', NETWORK_API]) return do_get(endpoint, access_token)
def get_public_ip(access_token, subscription_id, resource_group, ip_name)
Get details about the named public ip address. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. public_ip_name (str): Name of the public ip address resource. Returns: HTTP response. Public IP address JSON body.
2.716896
1.876461
1.447883
'''Get details about the named virtual network. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. vnet_name (str): Name of the VNet. Returns: HTTP response. VNet JSON body. ''' endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourceGroups/', resource_group, '/providers/Microsoft.Network/virtualNetworks/', vnet_name, '?api-version=', NETWORK_API]) return do_get(endpoint, access_token)
def get_vnet(access_token, subscription_id, resource_group, vnet_name)
Get details about the named virtual network. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. vnet_name (str): Name of the VNet. Returns: HTTP response. VNet JSON body.
2.416267
1.801069
1.341574
'''Get details about the application security groups for a resource group. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. Returns: HTTP response. ASG JSON body. ''' endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourceGroups/', resource_group, '/providers/Microsoft.Network/virtualNetworks/', '?api-version=', NETWORK_API]) return do_get(endpoint, access_token)
def list_asgs(access_token, subscription_id, resource_group)
Get details about the application security groups for a resource group. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. Returns: HTTP response. ASG JSON body.
3.228041
2.240201
1.44096
'''Get details about the application security groups for a resource group. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. Returns: HTTP response. ASG JSON body. ''' endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/providers/Microsoft.Network/virtualNetworks/', '?api-version=', NETWORK_API]) return do_get(endpoint, access_token)
def list_asgs_all(access_token, subscription_id)
Get details about the application security groups for a resource group. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. Returns: HTTP response. ASG JSON body.
3.987226
2.548961
1.564255
'''List the inbound NAT rules for a load balancer. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. lb_name (str): Name of the load balancer. Returns: HTTP response. JSON body of load balancer NAT rules. ''' endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourceGroups/', resource_group, '/providers/Microsoft.Network/loadBalancers/', lb_name, 'inboundNatRules?api-version=', NETWORK_API]) return do_get(endpoint, access_token)
def list_lb_nat_rules(access_token, subscription_id, resource_group, lb_name)
List the inbound NAT rules for a load balancer. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. lb_name (str): Name of the load balancer. Returns: HTTP response. JSON body of load balancer NAT rules.
2.422911
1.962223
1.234778
'''List the load balancers in a subscription. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. Returns: HTTP response. JSON body of load balancer list with properties. ''' endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/providers/Microsoft.Network/', '/loadBalancers?api-version=', NETWORK_API]) return do_get(endpoint, access_token)
def list_load_balancers(access_token, subscription_id)
List the load balancers in a subscription. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. Returns: HTTP response. JSON body of load balancer list with properties.
3.261981
2.383748
1.368425
'''List the network interfaces in a subscription. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. Returns: HTTP response. JSON body of NICs list with properties. ''' endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/providers/Microsoft.Network/', '/networkInterfaces?api-version=', NETWORK_API]) return do_get(endpoint, access_token)
def list_nics(access_token, subscription_id)
List the network interfaces in a subscription. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. Returns: HTTP response. JSON body of NICs list with properties.
3.41891
2.373737
1.440307
'''List all network security groups in a subscription. Args: access_token (str): a valid Azure Authentication token. subscription_id (str): Azure subscription id. Returns: HTTP response. JSON body of all network security groups in a subscription. ''' endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/providers/Microsoft.Network/', 'networkSEcurityGroups?api-version=', NETWORK_API]) return do_get(endpoint, access_token)
def list_nsgs_all(access_token, subscription_id)
List all network security groups in a subscription. Args: access_token (str): a valid Azure Authentication token. subscription_id (str): Azure subscription id. Returns: HTTP response. JSON body of all network security groups in a subscription.
4.311538
2.713025
1.5892
'''List the VNETs in a subscription . Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. Returns: HTTP response. JSON body of VNets list with properties. ''' endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/providers/Microsoft.Network/', '/virtualNetworks?api-version=', NETWORK_API]) return do_get(endpoint, access_token)
def list_vnets(access_token, subscription_id)
List the VNETs in a subscription . Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. Returns: HTTP response. JSON body of VNets list with properties.
3.975682
2.367407
1.67934