def list_iot_hubs(self, resource_group): self.output.header(f("Listing IoT Hubs in {resource_group}")) return self.invoke_az_cli_outproc([ "iot", "hub", "list", "--resource-group", resource_group, "--out", "table" ], f("Could not list the IoT Hubs in {resource_group}."))
def list_edge_devices(self, iothub): self.output.header(f("Listing edge devices in {iothub} IoT Hub")) return self.invoke_az_cli_outproc([ "iot", "hub", "device-identity", "list", "--hub-name", iothub, "--edge-enabled", "--output", "table" ], f("Could not list the edge devices in {iothub} IoT Hub."))
def create_edge_device(self, value, iothub, resource_group): self.output.status( f("Creating '{value}' edge device in '{iothub}'...")) return self.invoke_az_cli_outproc(["iot", "hub", "device-identity", "create", "--device-id", value, "--hub-name", iothub, "--resource-group", resource_group, "--edge-enabled", "--query", "[].{\"Device Id\":deviceId}", "--output", "table"], f("Could not locate the {value} device in {iothub} IoT Hub in {resource_group}."))
def raw(self, command, required_shell): '''Append a raw command to the scrim. This text will be appeneded to the output of :meth:`scrim.to_string` verbatim. Use required_shell to specify the shell which this raw command is applicable to. Examples: >>> scrim = Scrim() >>> scrim.raw('cat text.txt', 'bash') >>> scrim.raw('type text.txt', 'cmd.exe') >>> scrim.raw('Get-Content text.txt', 'powershell.exe') >>> scrim.to_bash() 'cat text.txt' >>> scrim.to_cmd() 'type text.txt' >>> scrim.to_powershell() 'Get-Content text.txt' ''' if not isinstance(command, basestring): raise TypeError(f('{command} must be a string')) if required_shell not in SHELLS: raise ValueError(f('{required_shell} must be one of {SHELLS}')) self.commands.append(RawCommand(command, required_shell))
def set_modules(self, device_id, connection_string, config): self.output.status(f("Deploying '{config}' to '{device_id}'...")) config = os.path.join(os.getcwd(), config) if not os.path.exists(config): raise FileNotFoundError( 'Deployment manifest file "{0}" not found. Please run `iotedgedev build` first' .format(config)) telemetry.add_extra_props({ 'iothubhostname': connection_string.iothub_host.name_hash, 'iothubhostnamesuffix': connection_string.iothub_host.name_suffix }) return self.invoke_az_cli_outproc( [ "iot", "edge", "set-modules", "-d", device_id, "-n", connection_string.iothub_host.hub_name, "-k", config, "-l", connection_string.connection_string ], error_message=f("Failed to deploy '{config}' to '{device_id}'..."), suppress_output=True)
def create_iothub(self, value, resource_group, sku): self.output.status( f("Creating '{value}' in '{resource_group}' with '{sku}' sku...")) with output_io_cls() as io: with output_io_cls() as error_io: self.output.prompt( "Creating IoT Hub. Please wait as this could take a few minutes to complete..." ) result = self.invoke_az_cli_outproc( [ "iot", "hub", "create", "--name", value, "--resource-group", resource_group, "--sku", sku, "--query", "[].{\"IoT Hub\":name}", "--out", "table" ], f("Could not create the IoT Hub {value} in {resource_group} with sku {sku}." ), stdout_io=io, stderr_io=error_io) if not result and error_io.getvalue(): self.output.error(error_io.getvalue()) self.output.line() elif io.getvalue(): self.output.prompt(io.getvalue()) self.output.line() return result
def list_iot_hubs(self, resource_group): self.output.header("IOT HUB") self.output.status(f("Retrieving IoT Hubs in '{resource_group}'...")) return self.invoke_az_cli_outproc([ "iot", "hub", "list", "--resource-group", resource_group, "--query", "[].{\"IoT Hub\":name}", "--out", "table" ], f("Could not list the IoT Hubs in {resource_group}."))
def list_edge_devices(self, iothub): self.output.header("EDGE DEVICE") self.output.status( f("Retrieving edge devices in '{iothub}'...")) return self.invoke_az_cli_outproc(["iot", "hub", "device-identity", "list", "--hub-name", iothub, "--edge-enabled", "--query", "[].{\"Device Id\":deviceId}", "--output", "table"], f("Could not list the edge devices in {iothub} IoT Hub."))
def set_modules(self, device_id, connection_string, config): self.output.status(f("Deploying '{config}' to '{device_id}'...")) telemetry.add_extra_props({'iothubhostname': connection_string.iothub_host.name_hash, 'iothubhostnamesuffix': connection_string.iothub_host.name_suffix}) config = os.path.join(os.getcwd(), config) return self.invoke_az_cli_outproc(["iot", "edge", "set-modules", "-d", device_id, "-n", connection_string.iothub_host.hub_name, "-k", config, "-l", connection_string.connection_string], error_message=f("Failed to deploy '{config}' to '{device_id}'..."), suppress_output=True)
def create_resource_group(self, name, location): self.output.status( f("Creating Resource Group '{name}' at '{location}'...")) with output_io_cls() as io: result = self.invoke_az_cli_outproc(["group", "create", "--name", name, "--location", location], f("Could not create the new Resource Group {name} at location:{location}."), io) return result
def apply_configuration(self, deviceId, connection_string, config): self.output.status(f("Deploying '{config}' to '{deviceId}'...")) return self.invoke_az_cli_outproc( [ "iot", "hub", "apply-configuration", "-d", deviceId, "-k", config, "-l", connection_string ], error_message=f("Failed to deploy '{config}' to '{deviceId}'..."), suppress_output=True)
def get_resource_group_location(self, name): self.output.status(f("Retrieving Resource Group '{name}' location...")) with output_io_cls() as io: result = self.invoke_az_cli_outproc(["group", "show", "-n", name, "--query", "location", "--output", "tsv"], f("Could not retrieve Resource Group {name}'s location."), io) if result: return io.getvalue() else: return ''
def edge_device_exists(self, value, iothub, resource_group): self.output.status( f("Checking if '{value}' device exists in '{iothub}'...")) with output_io_cls() as io: result = self.invoke_az_cli_outproc(["iot", "hub", "device-identity", "show", "--device-id", value, "--hub-name", iothub, "--resource-group", resource_group, "--out", "table"], stderr_io=io) if not result: self.output.prompt( f("Could not locate the {value} device in {iothub} IoT Hub in {resource_group}.")) return result
def set_modules(self, device_id, connection_string, hub_name, config): self.output.status(f("Deploying '{config}' to '{device_id}'...")) config = os.path.join(os.getcwd(), config) return self.invoke_az_cli_outproc( [ "iot", "edge", "set-modules", "-d", device_id, "-n", hub_name, "-k", config, "-l", connection_string ], error_message=f("Failed to deploy '{config}' to '{device_id}'..."), suppress_output=True)
def iothub_exists(self, value, resource_group): self.output.status( f("Checking if '{value}' IoT Hub exists...")) with output_io_cls() as io: result = self.invoke_az_cli_outproc(["iot", "hub", "show", "--name", value, "--resource-group", resource_group, "--out", "table"], stderr_io=io) if not result: self.output.prompt( f("Could not locate the {value} in {resource_group}.")) return result
def validate_kwargs(parameters, kwargs): '''Validate kwargs using Action parameters dict: >>> parameters = {'arg': {'name': 'Arg', 'default': 1.0, 'type': float}} >>> kwargs = {'arg': 10.0} >>> validate_kwargs(parameters, kwargs) True Arguments: parameters (dict): describes parameters of a callable: kwargs (dict): function arguments as keyword arguments: Returns: True Raises: ArgumentError: describing why kwargs is invalid ''' if not parameters and kwargs: raise ArgumentError(f('Got additional arguments: {kwargs}')) for name, options in parameters.items(): validator = options.get('validator', None) required = options.get('required', False) type_ = options['type'] value = kwargs.get(name, None) valid_values = options.get('options', None) if value is None and required: raise ArgumentError(f('Missing required argument: {name}')) elif value is None and not required: continue if not isinstance(value, options['type']): raise ArgumentError(f('{name} must be {type_} not {value}.')) if valid_values: exc_msg = f('{name} must be one of: {valid_values}') if value not in valid_values: raise ArgumentError(exc_msg) if validator: exc_msg = f('{name} failed custom validator: {value}') try: if validator(value) is False: raise ArgumentError(exc_msg) except: raise ArgumentError(exc_msg) return True
def get_iothub_connection_string(self, value, resource_group): self.output.status( f("Retrieving '{value}' connection string...")) with output_io_cls() as io: result = self.invoke_az_cli_outproc(["iot", "hub", "show-connection-string", "--hub-name", value, "--resource-group", resource_group], f("Could not create the IoT Hub {value} in {resource_group}."), stdout_io=io) if result: out_string = io.getvalue() data = json.loads(out_string) return data["cs"] return ''
def create_edge_device(self, value, iothub, resource_group): self.output.header( f("Creating {value} edge device in {iothub} IoT Hub in {resource_group}" )) return self.invoke_az_cli_outproc( [ "iot", "hub", "device-identity", "create", "--device-id", value, "--hub-name", iothub, "--resource-group", resource_group, "--edge-enabled", "--output", "table" ], f("Could not locate the {value} device in {iothub} IoT Hub in {resource_group}." ))
def backup_dotenv(self): dotenv_path = self.get_dotenv_file_path() dotenv_backup_path = dotenv_path + ".backup" try: copyfile(dotenv_path, dotenv_backup_path) self.output.info( f("Successfully backed up {dotenv_path} to {dotenv_backup_path}" )) return True except Exception as e: self.output.error( f("Could not backup {dotenv_path} to {dotenv_backup_path}")) self.output.error(str(e)) return False
def resource_group_exists(self, name): self.output.status(f("Checking if Resource Group '{name}' exists...")) with output_io_cls() as io: result = self.invoke_az_cli_outproc(["group", "exists", "-n", name], f("Resource Group {name} does not exist."), io) if result: out_string = io.getvalue() if out_string == "true": return True self.output.prompt(f("Resource Group {name} does not exist.")) return False
def _fetch_db_value(self, table): "Fetches the DB values via low-level SQL." select_query = sqlalchemy.text(f('SELECT * FROM {table.name} LIMIT 1')) rows = self.connection.execute(select_query) row = tuple(rows)[0] assert len(row) == 2 return row[-1]
def get_device_connection_string(self, value, iothub, resource_group): self.output.status( f("Retrieving '{value}' connection string...")) with output_io_cls() as io: result = self.invoke_az_cli_outproc(["iot", "hub", "device-identity", "show-connection-string", "--device-id", value, "--hub-name", iothub, "--resource-group", resource_group], f("Could not locate the {value} device in {iothub} IoT Hub in {resource_group}."), stdout_io=io) if result: out_string = io.getvalue() data = json.loads(out_string) if "cs" in data: return data["cs"] else: return data["connectionString"] return ''
def get_free_iothub(self): self.output.header( f("Checking if an F1 (free) IoT Hub exists in the subscription")) with output_io_cls() as io: result = self.invoke_az_cli_outproc( ["iot", "hub", "list"], f("Could not list IoT Hubs in subscription."), stdout_io=io) if result: out_string = io.getvalue() data = json.loads(out_string) for iot in data: if iot["sku"]["name"] == "F1": return (iot["name"], iot["resourceGroup"]) return (None, None)
def __repr__(self): args = ( repr(self.path), repr(self.auto_write), repr(self.shell), repr(self.script) ) return f("<{}>({}, {}, {}, {})", self.__class__.__name__, *args)
def save_envvar(self, key, value): try: dotenv_file = self.get_dotenv_file() dotenv_path = os.path.join(os.getcwd(), dotenv_file) set_key(dotenv_path, key, value) except Exception: raise IOError( f("Could not update the environment variable {key} in file {dotenv_path}" ))
def valid_chain(self, chain): last_block = chain[0] current_index = 1 while current_index < len(chain): block = chain[current_index] print(f('{last_block}')) print(f('{block}')) print("\n ------ \n") last_block_hash = self.hash(last_block) if block['previous_hash'] != last_block_hash: return False # validate proof of work if not self.valid_proof(last_block['proof'], block['proof'], last_block_hash): return False last_block = block current_index += 1 return True
def delete(root, remove_root): '''Delete an entry''' entry = fsfs.get_entry(root) if not entry.exists: raise UsageError(f('{root} is not an Entry.')) if click.confirm('Are you sure you want to delete {}?'.format(entry.name)): fsfs.delete(root, remove_root=remove_root)
def set_subscription(self, subscription): if len(subscription) < 36: subscription = self.get_subscription_id_starts_with(subscription) self.output.status(f("Setting Subscription to '{subscription}'...")) return self.invoke_az_cli_outproc( ["account", "set", "--subscription", subscription], "Error while trying to set Azure subscription.")
def new_transaction(): values = request.get_json() required = ['sender', 'recipient', 'amount'] if not all(k in values for k in required): return 'Missing values', 400 index = blockchain.new_transaction(values['sender'], values['recipient'], values['amount']) response = {'message': f('Transaction will be added to Block {index}')} return jsonify(response), 201
def main(): #this will block execution until a debugger attaches #ptvsd.wait_for_attach() i = 1 while True: sleep(1) i = i + 1 print(f('looped:{i}'))