idx int64 0 63k | question stringlengths 61 4.03k | target stringlengths 6 1.23k |
|---|---|---|
45,800 | def reflash_firmware ( self , hardware_id , ipmi = True , raid_controller = True , bios = True ) : return self . hardware . createFirmwareReflashTransaction ( bool ( ipmi ) , bool ( raid_controller ) , bool ( bios ) , id = hardware_id ) | Reflash hardware firmware . |
45,801 | def wait_for_ready ( self , instance_id , limit = 14400 , delay = 10 , pending = False ) : now = time . time ( ) until = now + limit mask = "mask[id, lastOperatingSystemReload[id], activeTransaction, provisionDate]" instance = self . get_hardware ( instance_id , mask = mask ) while now <= until : if utils . is_ready ( instance , pending ) : return True transaction = utils . lookup ( instance , 'activeTransaction' , 'transactionStatus' , 'friendlyName' ) snooze = min ( delay , until - now ) LOGGER . info ( "%s - %d not ready. Auto retry in %ds" , transaction , instance_id , snooze ) time . sleep ( snooze ) instance = self . get_hardware ( instance_id , mask = mask ) now = time . time ( ) LOGGER . info ( "Waiting for %d expired." , instance_id ) return False | Determine if a Server is ready . |
45,802 | def cli ( env , identifier , immediate , comment , reason ) : mgr = SoftLayer . HardwareManager ( env . client ) hw_id = helpers . resolve_id ( mgr . resolve_ids , identifier , 'hardware' ) if not ( env . skip_confirmations or formatting . no_going_back ( hw_id ) ) : raise exceptions . CLIAbort ( 'Aborted' ) mgr . cancel_hardware ( hw_id , reason , comment , immediate ) | Cancel a dedicated server . |
45,803 | def cli ( env , identifier , postinstall , key , image ) : vsi = SoftLayer . VSManager ( env . client ) vs_id = helpers . resolve_id ( vsi . resolve_ids , identifier , 'VS' ) keys = [ ] if key : for single_key in key : resolver = SoftLayer . SshKeyManager ( env . client ) . resolve_ids key_id = helpers . resolve_id ( resolver , single_key , 'SshKey' ) keys . append ( key_id ) if not ( env . skip_confirmations or formatting . no_going_back ( vs_id ) ) : raise exceptions . CLIAbort ( 'Aborted' ) vsi . reload_instance ( vs_id , post_uri = postinstall , ssh_keys = keys , image_id = image ) | Reload operating system on a virtual server . |
45,804 | def cli ( env , identifier , columns ) : manager = CapacityManager ( env . client ) mask = result = manager . get_object ( identifier , mask ) try : flavor = result [ 'instances' ] [ 0 ] [ 'billingItem' ] [ 'description' ] except KeyError : flavor = "Pending Approval..." table = formatting . Table ( columns . columns , title = "%s - %s" % ( result . get ( 'name' ) , flavor ) ) for rci in result [ 'instances' ] : guest = rci . get ( 'guest' , None ) if guest is not None : table . add_row ( [ value or formatting . blank ( ) for value in columns . row ( guest ) ] ) else : table . add_row ( [ '-' for value in columns . columns ] ) env . fout ( table ) | Reserved Capacity Group details . Will show which guests are assigned to a reservation . |
45,805 | def get_client_settings_args ( ** kwargs ) : timeout = kwargs . get ( 'timeout' ) if timeout is not None : timeout = float ( timeout ) return { 'endpoint_url' : kwargs . get ( 'endpoint_url' ) , 'timeout' : timeout , 'proxy' : kwargs . get ( 'proxy' ) , 'username' : kwargs . get ( 'username' ) , 'api_key' : kwargs . get ( 'api_key' ) , } | Retrieve client settings from user - supplied arguments . |
45,806 | def get_client_settings_env ( ** _ ) : return { 'proxy' : os . environ . get ( 'https_proxy' ) , 'username' : os . environ . get ( 'SL_USERNAME' ) , 'api_key' : os . environ . get ( 'SL_API_KEY' ) , } | Retrieve client settings from environment settings . |
45,807 | def get_client_settings_config_file ( ** kwargs ) : config_files = [ '/etc/softlayer.conf' , '~/.softlayer' ] if kwargs . get ( 'config_file' ) : config_files . append ( kwargs . get ( 'config_file' ) ) config_files = [ os . path . expanduser ( f ) for f in config_files ] config = utils . configparser . RawConfigParser ( { 'username' : '' , 'api_key' : '' , 'endpoint_url' : '' , 'timeout' : '0' , 'proxy' : '' , } ) config . read ( config_files ) if config . has_section ( 'softlayer' ) : return { 'endpoint_url' : config . get ( 'softlayer' , 'endpoint_url' ) , 'timeout' : config . getfloat ( 'softlayer' , 'timeout' ) , 'proxy' : config . get ( 'softlayer' , 'proxy' ) , 'username' : config . get ( 'softlayer' , 'username' ) , 'api_key' : config . get ( 'softlayer' , 'api_key' ) , } | Retrieve client settings from the possible config file locations . |
45,808 | def get_client_settings ( ** kwargs ) : all_settings = { } for setting_method in SETTING_RESOLVERS : settings = setting_method ( ** kwargs ) if settings : settings . update ( ( k , v ) for k , v in all_settings . items ( ) if v ) all_settings = settings return all_settings | Parse client settings . |
45,809 | def cli ( env , package_keyname , required ) : client = env . client manager = ordering . OrderingManager ( client ) table = formatting . Table ( COLUMNS ) categories = manager . list_categories ( package_keyname ) if required : categories = [ cat for cat in categories if cat [ 'isRequired' ] ] for cat in categories : table . add_row ( [ cat [ 'itemCategory' ] [ 'name' ] , cat [ 'itemCategory' ] [ 'categoryCode' ] , 'Y' if cat [ 'isRequired' ] else 'N' ] ) env . fout ( table ) | List the categories of a package . |
45,810 | def list_certs ( self , method = 'all' ) : ssl = self . client [ 'Account' ] methods = { 'all' : 'getSecurityCertificates' , 'expired' : 'getExpiredSecurityCertificates' , 'valid' : 'getValidSecurityCertificates' } mask = "mask[id, commonName, validityDays, notes]" func = getattr ( ssl , methods [ method ] ) return func ( mask = mask ) | List all certificates . |
45,811 | def cli ( env ) : manager = SoftLayer . DNSManager ( env . client ) zones = manager . list_zones ( ) table = formatting . Table ( [ 'id' , 'zone' , 'serial' , 'updated' ] ) table . align [ 'serial' ] = 'c' table . align [ 'updated' ] = 'c' for zone in zones : table . add_row ( [ zone [ 'id' ] , zone [ 'name' ] , zone [ 'serial' ] , zone [ 'updateDate' ] , ] ) env . fout ( table ) | List all zones . |
45,812 | def list_file_volumes ( self , datacenter = None , username = None , storage_type = None , ** kwargs ) : if 'mask' not in kwargs : items = [ 'id' , 'username' , 'capacityGb' , 'bytesUsed' , 'serviceResource.datacenter[name]' , 'serviceResourceBackendIpAddress' , 'activeTransactionCount' , 'fileNetworkMountAddress' , 'replicationPartnerCount' ] kwargs [ 'mask' ] = ',' . join ( items ) _filter = utils . NestedDict ( kwargs . get ( 'filter' ) or { } ) _filter [ 'nasNetworkStorage' ] [ 'serviceResource' ] [ 'type' ] [ 'type' ] = ( utils . query_filter ( '!~ NAS' ) ) _filter [ 'nasNetworkStorage' ] [ 'storageType' ] [ 'keyName' ] = ( utils . query_filter ( '*FILE_STORAGE*' ) ) if storage_type : _filter [ 'nasNetworkStorage' ] [ 'storageType' ] [ 'keyName' ] = ( utils . query_filter ( '%s_FILE_STORAGE*' % storage_type . upper ( ) ) ) if datacenter : _filter [ 'nasNetworkStorage' ] [ 'serviceResource' ] [ 'datacenter' ] [ 'name' ] = ( utils . query_filter ( datacenter ) ) if username : _filter [ 'nasNetworkStorage' ] [ 'username' ] = ( utils . query_filter ( username ) ) kwargs [ 'filter' ] = _filter . to_dict ( ) return self . client . call ( 'Account' , 'getNasNetworkStorage' , ** kwargs ) | Returns a list of file volumes . |
45,813 | def get_file_volume_details ( self , volume_id , ** kwargs ) : if 'mask' not in kwargs : items = [ 'id' , 'username' , 'password' , 'capacityGb' , 'bytesUsed' , 'snapshotCapacityGb' , 'parentVolume.snapshotSizeBytes' , 'storageType.keyName' , 'serviceResource.datacenter[name]' , 'serviceResourceBackendIpAddress' , 'fileNetworkMountAddress' , 'storageTierLevel' , 'provisionedIops' , 'lunId' , 'originalVolumeName' , 'originalSnapshotName' , 'originalVolumeSize' , 'activeTransactionCount' , 'activeTransactions.transactionStatus[friendlyName]' , 'replicationPartnerCount' , 'replicationStatus' , 'replicationPartners[id,username,' 'serviceResourceBackendIpAddress,' 'serviceResource[datacenter[name]],' 'replicationSchedule[type[keyname]]]' , ] kwargs [ 'mask' ] = ',' . join ( items ) return self . client . call ( 'Network_Storage' , 'getObject' , id = volume_id , ** kwargs ) | Returns details about the specified volume . |
45,814 | def order_replicant_volume ( self , volume_id , snapshot_schedule , location , tier = None ) : file_mask = 'billingItem[activeChildren,hourlyFlag],' 'storageTierLevel,osType,staasVersion,' 'hasEncryptionAtRest,snapshotCapacityGb,schedules,' 'intervalSchedule,hourlySchedule,dailySchedule,' 'weeklySchedule,storageType[keyName],provisionedIops' file_volume = self . get_file_volume_details ( volume_id , mask = file_mask ) order = storage_utils . prepare_replicant_order_object ( self , snapshot_schedule , location , tier , file_volume , 'file' ) return self . client . call ( 'Product_Order' , 'placeOrder' , order ) | Places an order for a replicant file volume . |
45,815 | def order_duplicate_volume ( self , origin_volume_id , origin_snapshot_id = None , duplicate_size = None , duplicate_iops = None , duplicate_tier_level = None , duplicate_snapshot_size = None , hourly_billing_flag = False ) : file_mask = 'id,billingItem[location,hourlyFlag],snapshotCapacityGb,' 'storageType[keyName],capacityGb,originalVolumeSize,' 'provisionedIops,storageTierLevel,' 'staasVersion,hasEncryptionAtRest' origin_volume = self . get_file_volume_details ( origin_volume_id , mask = file_mask ) order = storage_utils . prepare_duplicate_order_object ( self , origin_volume , duplicate_iops , duplicate_tier_level , duplicate_size , duplicate_snapshot_size , 'file' , hourly_billing_flag ) if origin_snapshot_id is not None : order [ 'duplicateOriginSnapshotId' ] = origin_snapshot_id return self . client . call ( 'Product_Order' , 'placeOrder' , order ) | Places an order for a duplicate file volume . |
45,816 | def order_modified_volume ( self , volume_id , new_size = None , new_iops = None , new_tier_level = None ) : mask_items = [ 'id' , 'billingItem' , 'storageType[keyName]' , 'capacityGb' , 'provisionedIops' , 'storageTierLevel' , 'staasVersion' , 'hasEncryptionAtRest' , ] file_mask = ',' . join ( mask_items ) volume = self . get_file_volume_details ( volume_id , mask = file_mask ) order = storage_utils . prepare_modify_order_object ( self , volume , new_iops , new_tier_level , new_size ) return self . client . call ( 'Product_Order' , 'placeOrder' , order ) | Places an order for modifying an existing file volume . |
45,817 | def order_snapshot_space ( self , volume_id , capacity , tier , upgrade , ** kwargs ) : file_mask = 'id,billingItem[location,hourlyFlag],' 'storageType[keyName],storageTierLevel,provisionedIops,' 'staasVersion,hasEncryptionAtRest' file_volume = self . get_file_volume_details ( volume_id , mask = file_mask , ** kwargs ) order = storage_utils . prepare_snapshot_order_object ( self , file_volume , capacity , tier , upgrade ) return self . client . call ( 'Product_Order' , 'placeOrder' , order ) | Orders snapshot space for the given file volume . |
45,818 | def cli ( env , zone ) : manager = SoftLayer . DNSManager ( env . client ) zone_id = helpers . resolve_id ( manager . resolve_ids , zone , name = 'zone' ) env . fout ( manager . dump_zone ( zone_id ) ) | Print zone in BIND format . |
45,819 | def rescue ( env , identifier ) : vsi = SoftLayer . VSManager ( env . client ) vs_id = helpers . resolve_id ( vsi . resolve_ids , identifier , 'VS' ) if not ( env . skip_confirmations or formatting . confirm ( "This action will reboot this VSI. Continue?" ) ) : raise exceptions . CLIAbort ( 'Aborted' ) vsi . rescue ( vs_id ) | Reboot into a rescue image . |
45,820 | def reboot ( env , identifier , hard ) : virtual_guest = env . client [ 'Virtual_Guest' ] mgr = SoftLayer . HardwareManager ( env . client ) vs_id = helpers . resolve_id ( mgr . resolve_ids , identifier , 'VS' ) if not ( env . skip_confirmations or formatting . confirm ( 'This will reboot the VS with id %s. ' 'Continue?' % vs_id ) ) : raise exceptions . CLIAbort ( 'Aborted.' ) if hard is True : virtual_guest . rebootHard ( id = vs_id ) elif hard is False : virtual_guest . rebootSoft ( id = vs_id ) else : virtual_guest . rebootDefault ( id = vs_id ) | Reboot an active virtual server . |
45,821 | def power_off ( env , identifier , hard ) : virtual_guest = env . client [ 'Virtual_Guest' ] vsi = SoftLayer . VSManager ( env . client ) vs_id = helpers . resolve_id ( vsi . resolve_ids , identifier , 'VS' ) if not ( env . skip_confirmations or formatting . confirm ( 'This will power off the VS with id %s. ' 'Continue?' % vs_id ) ) : raise exceptions . CLIAbort ( 'Aborted.' ) if hard : virtual_guest . powerOff ( id = vs_id ) else : virtual_guest . powerOffSoft ( id = vs_id ) | Power off an active virtual server . |
45,822 | def power_on ( env , identifier ) : vsi = SoftLayer . VSManager ( env . client ) vs_id = helpers . resolve_id ( vsi . resolve_ids , identifier , 'VS' ) env . client [ 'Virtual_Guest' ] . powerOn ( id = vs_id ) | Power on a virtual server . |
45,823 | def pause ( env , identifier ) : vsi = SoftLayer . VSManager ( env . client ) vs_id = helpers . resolve_id ( vsi . resolve_ids , identifier , 'VS' ) if not ( env . skip_confirmations or formatting . confirm ( 'This will pause the VS with id %s. Continue?' % vs_id ) ) : raise exceptions . CLIAbort ( 'Aborted.' ) env . client [ 'Virtual_Guest' ] . pause ( id = vs_id ) | Pauses an active virtual server . |
45,824 | def resume ( env , identifier ) : vsi = SoftLayer . VSManager ( env . client ) vs_id = helpers . resolve_id ( vsi . resolve_ids , identifier , 'VS' ) env . client [ 'Virtual_Guest' ] . resume ( id = vs_id ) | Resumes a paused virtual server . |
45,825 | def cli ( env ) : manager = AccountManager ( env . client ) summary = manager . get_summary ( ) env . fout ( get_snapshot_table ( summary ) ) | Prints some various bits of information about an account |
45,826 | def get_snapshot_table ( account ) : table = formatting . KeyValueTable ( [ "Name" , "Value" ] , title = "Account Snapshot" ) table . align [ 'Name' ] = 'r' table . align [ 'Value' ] = 'l' table . add_row ( [ 'Company Name' , account . get ( 'companyName' , '-' ) ] ) table . add_row ( [ 'Balance' , utils . lookup ( account , 'pendingInvoice' , 'startingBalance' ) ] ) table . add_row ( [ 'Upcoming Invoice' , utils . lookup ( account , 'pendingInvoice' , 'invoiceTotalAmount' ) ] ) table . add_row ( [ 'Image Templates' , account . get ( 'blockDeviceTemplateGroupCount' , '-' ) ] ) table . add_row ( [ 'Dedicated Hosts' , account . get ( 'dedicatedHostCount' , '-' ) ] ) table . add_row ( [ 'Hardware' , account . get ( 'hardwareCount' , '-' ) ] ) table . add_row ( [ 'Virtual Guests' , account . get ( 'virtualGuestCount' , '-' ) ] ) table . add_row ( [ 'Domains' , account . get ( 'domainCount' , '-' ) ] ) table . add_row ( [ 'Network Storage Volumes' , account . get ( 'networkStorageCount' , '-' ) ] ) table . add_row ( [ 'Open Tickets' , account . get ( 'openTicketCount' , '-' ) ] ) table . add_row ( [ 'Network Vlans' , account . get ( 'networkVlanCount' , '-' ) ] ) table . add_row ( [ 'Subnets' , account . get ( 'subnetCount' , '-' ) ] ) table . add_row ( [ 'Users' , account . get ( 'userCount' , '-' ) ] ) return table | Generates a table for printing account summary data |
45,827 | def cli ( env , prop ) : try : if prop == 'network' : env . fout ( get_network ( ) ) return meta_prop = META_MAPPING . get ( prop ) or prop env . fout ( SoftLayer . MetadataManager ( ) . get ( meta_prop ) ) except SoftLayer . TransportError : raise exceptions . CLIAbort ( 'Cannot connect to the backend service address. Make sure ' 'this command is being ran from a device on the backend ' 'network.' ) | Find details about this machine . |
45,828 | def get_network ( ) : meta = SoftLayer . MetadataManager ( ) network_tables = [ ] for network_func in [ meta . public_network , meta . private_network ] : network = network_func ( ) table = formatting . KeyValueTable ( [ 'name' , 'value' ] ) table . align [ 'name' ] = 'r' table . align [ 'value' ] = 'l' table . add_row ( [ 'mac addresses' , formatting . listing ( network [ 'mac_addresses' ] , separator = ',' ) ] ) table . add_row ( [ 'router' , network [ 'router' ] ] ) table . add_row ( [ 'vlans' , formatting . listing ( network [ 'vlans' ] , separator = ',' ) ] ) table . add_row ( [ 'vlan ids' , formatting . listing ( network [ 'vlan_ids' ] , separator = ',' ) ] ) network_tables . append ( table ) return network_tables | Returns a list of tables with public and private network details . |
45,829 | def get_formatter ( columns ) : column_map = dict ( ( column . name , column ) for column in columns ) def validate ( ctx , param , value ) : if value == '' : raise click . BadParameter ( 'At least one column is required.' ) formatter = ColumnFormatter ( ) for column in [ col . strip ( ) for col in value . split ( ',' ) ] : if column in column_map : formatter . add_column ( column_map [ column ] ) else : formatter . add_column ( Column ( column , column . split ( '.' ) ) ) return formatter return validate | This function returns a callback to use with click options . |
45,830 | def add_column ( self , column ) : self . columns . append ( column . name ) self . column_funcs . append ( column . path ) if column . mask is not None : self . mask_parts . add ( column . mask ) | Add a new column along with a formatting function . |
45,831 | def row ( self , data ) : for column in self . column_funcs : if callable ( column ) : yield column ( data ) else : yield utils . lookup ( data , * column ) | Return a formatted row for the given data . |
45,832 | def cli ( env , account_id , origin_id ) : manager = SoftLayer . CDNManager ( env . client ) manager . remove_origin ( account_id , origin_id ) | Remove an origin pull mapping . |
45,833 | def cli ( env , sortby ) : manager = SoftLayer . CDNManager ( env . client ) accounts = manager . list_accounts ( ) table = formatting . Table ( [ 'id' , 'account_name' , 'type' , 'created' , 'notes' ] ) for account in accounts : table . add_row ( [ account [ 'id' ] , account [ 'cdnAccountName' ] , account [ 'cdnSolutionName' ] , account [ 'createDate' ] , account . get ( 'cdnAccountNote' , formatting . blank ( ) ) ] ) table . sortby = sortby env . fout ( table ) | List all CDN accounts . |
45,834 | def cli ( env , volume_id , sortby , columns ) : file_manager = SoftLayer . FileStorageManager ( env . client ) snapshots = file_manager . get_file_volume_snapshot_list ( volume_id , mask = columns . mask ( ) ) table = formatting . Table ( columns . columns ) table . sortby = sortby for snapshot in snapshots : table . add_row ( [ value or formatting . blank ( ) for value in columns . row ( snapshot ) ] ) env . fout ( table ) | List file storage snapshots . |
45,835 | def list_instances ( self , hourly = True , monthly = True , tags = None , cpus = None , memory = None , hostname = None , domain = None , local_disk = None , datacenter = None , nic_speed = None , public_ip = None , private_ip = None , ** kwargs ) : if 'mask' not in kwargs : items = [ 'id' , 'globalIdentifier' , 'hostname' , 'domain' , 'fullyQualifiedDomainName' , 'primaryBackendIpAddress' , 'primaryIpAddress' , 'lastKnownPowerState.name' , 'powerState' , 'maxCpu' , 'maxMemory' , 'datacenter' , 'activeTransaction.transactionStatus[friendlyName,name]' , 'status' , ] kwargs [ 'mask' ] = "mask[%s]" % ',' . join ( items ) call = 'getVirtualGuests' if not all ( [ hourly , monthly ] ) : if hourly : call = 'getHourlyVirtualGuests' elif monthly : call = 'getMonthlyVirtualGuests' _filter = utils . NestedDict ( kwargs . get ( 'filter' ) or { } ) if tags : _filter [ 'virtualGuests' ] [ 'tagReferences' ] [ 'tag' ] [ 'name' ] = { 'operation' : 'in' , 'options' : [ { 'name' : 'data' , 'value' : tags } ] , } if cpus : _filter [ 'virtualGuests' ] [ 'maxCpu' ] = utils . query_filter ( cpus ) if memory : _filter [ 'virtualGuests' ] [ 'maxMemory' ] = utils . query_filter ( memory ) if hostname : _filter [ 'virtualGuests' ] [ 'hostname' ] = utils . query_filter ( hostname ) if domain : _filter [ 'virtualGuests' ] [ 'domain' ] = utils . query_filter ( domain ) if local_disk is not None : _filter [ 'virtualGuests' ] [ 'localDiskFlag' ] = ( utils . query_filter ( bool ( local_disk ) ) ) if datacenter : _filter [ 'virtualGuests' ] [ 'datacenter' ] [ 'name' ] = ( utils . query_filter ( datacenter ) ) if nic_speed : _filter [ 'virtualGuests' ] [ 'networkComponents' ] [ 'maxSpeed' ] = ( utils . query_filter ( nic_speed ) ) if public_ip : _filter [ 'virtualGuests' ] [ 'primaryIpAddress' ] = ( utils . query_filter ( public_ip ) ) if private_ip : _filter [ 'virtualGuests' ] [ 'primaryBackendIpAddress' ] = ( utils . query_filter ( private_ip ) ) kwargs [ 'filter' ] = _filter . to_dict ( ) kwargs [ 'iter' ] = True return self . client . call ( 'Account' , call , ** kwargs ) | Retrieve a list of all virtual servers on the account . |
45,836 | def get_instance ( self , instance_id , ** kwargs ) : if 'mask' not in kwargs : kwargs [ 'mask' ] = ( 'id,' 'globalIdentifier,' 'fullyQualifiedDomainName,' 'hostname,' 'domain,' 'createDate,' 'modifyDate,' 'provisionDate,' 'notes,' 'dedicatedAccountHostOnlyFlag,' 'privateNetworkOnlyFlag,' 'primaryBackendIpAddress,' 'primaryIpAddress,' 'lastKnownPowerState.name,' 'powerState,' 'status,' 'maxCpu,' 'maxMemory,' 'datacenter,' 'activeTransaction[id, transactionStatus[friendlyName,name]],' 'lastTransaction[transactionStatus],' 'lastOperatingSystemReload.id,' 'blockDevices,' 'blockDeviceTemplateGroup[id, name, globalIdentifier],' 'postInstallScriptUri,' 'hourlyBillingFlag,' 'userData,' 'tagReferences[id,tag[name,id]],' 'networkVlans[id,vlanNumber,networkSpace],' 'dedicatedHost.id,' 'placementGroupId' ) return self . guest . getObject ( id = instance_id , ** kwargs ) | Get details about a virtual server instance . |
45,837 | def reload_instance ( self , instance_id , post_uri = None , ssh_keys = None , image_id = None ) : config = { } if post_uri : config [ 'customProvisionScriptUri' ] = post_uri if ssh_keys : config [ 'sshKeyIds' ] = [ key_id for key_id in ssh_keys ] if image_id : config [ 'imageTemplateId' ] = image_id return self . client . call ( 'Virtual_Guest' , 'reloadOperatingSystem' , 'FORCE' , config , id = instance_id ) | Perform an OS reload of an instance . |
45,838 | def wait_for_transaction ( self , instance_id , limit , delay = 10 ) : return self . wait_for_ready ( instance_id , limit , delay = delay , pending = True ) | Waits on a VS transaction for the specified amount of time . |
45,839 | def verify_create_instance ( self , ** kwargs ) : kwargs . pop ( 'tags' , None ) create_options = self . _generate_create_dict ( ** kwargs ) return self . guest . generateOrderTemplate ( create_options ) | Verifies an instance creation command . |
45,840 | def create_instance ( self , ** kwargs ) : tags = kwargs . pop ( 'tags' , None ) inst = self . guest . createObject ( self . _generate_create_dict ( ** kwargs ) ) if tags is not None : self . set_tags ( tags , guest_id = inst [ 'id' ] ) return inst | Creates a new virtual server instance . |
45,841 | def set_tags ( self , tags , guest_id ) : self . guest . setTags ( tags , id = guest_id ) | Sets tags on a guest with a retry decorator |
45,842 | def create_instances ( self , config_list ) : tags = [ conf . pop ( 'tags' , None ) for conf in config_list ] resp = self . guest . createObjects ( [ self . _generate_create_dict ( ** kwargs ) for kwargs in config_list ] ) for instance , tag in zip ( resp , tags ) : if tag is not None : self . set_tags ( tag , guest_id = instance [ 'id' ] ) return resp | Creates multiple virtual server instances . |
45,843 | def change_port_speed ( self , instance_id , public , speed ) : if public : return self . client . call ( 'Virtual_Guest' , 'setPublicNetworkInterfaceSpeed' , speed , id = instance_id ) else : return self . client . call ( 'Virtual_Guest' , 'setPrivateNetworkInterfaceSpeed' , speed , id = instance_id ) | Allows you to change the port speed of a virtual server s NICs . |
45,844 | def _get_ids_from_hostname ( self , hostname ) : results = self . list_instances ( hostname = hostname , mask = "id" ) return [ result [ 'id' ] for result in results ] | List VS ids which match the given hostname . |
45,845 | def _get_ids_from_ip ( self , ip_address ) : try : socket . inet_aton ( ip_address ) except socket . error : return [ ] results = self . list_instances ( public_ip = ip_address , mask = "id" ) if results : return [ result [ 'id' ] for result in results ] results = self . list_instances ( private_ip = ip_address , mask = "id" ) if results : return [ result [ 'id' ] for result in results ] | List VS ids which match the given ip address . |
45,846 | def upgrade ( self , instance_id , cpus = None , memory = None , nic_speed = None , public = True , preset = None ) : upgrade_prices = self . _get_upgrade_prices ( instance_id ) prices = [ ] data = { 'nic_speed' : nic_speed } if cpus is not None and preset is not None : raise ValueError ( "Do not use cpu, private and memory if you are using flavors" ) data [ 'cpus' ] = cpus if memory is not None and preset is not None : raise ValueError ( "Do not use memory, private or cpu if you are using flavors" ) data [ 'memory' ] = memory maintenance_window = datetime . datetime . now ( utils . UTC ( ) ) order = { 'complexType' : 'SoftLayer_Container_Product_Order_Virtual_Guest_Upgrade' , 'properties' : [ { 'name' : 'MAINTENANCE_WINDOW' , 'value' : maintenance_window . strftime ( "%Y-%m-%d %H:%M:%S%z" ) } ] , 'virtualGuests' : [ { 'id' : int ( instance_id ) } ] , } for option , value in data . items ( ) : if not value : continue price_id = self . _get_price_id_for_upgrade_option ( upgrade_prices , option , value , public ) if not price_id : raise exceptions . SoftLayerError ( "Unable to find %s option with value %s" % ( option , value ) ) prices . append ( { 'id' : price_id } ) order [ 'prices' ] = prices if preset is not None : vs_object = self . get_instance ( instance_id ) [ 'billingItem' ] [ 'package' ] order [ 'presetId' ] = self . ordering_manager . get_preset_by_key ( vs_object [ 'keyName' ] , preset ) [ 'id' ] if prices or preset : self . client [ 'Product_Order' ] . placeOrder ( order ) return True return False | Upgrades a VS instance . |
45,847 | def _get_package_items ( self ) : warnings . warn ( "use _get_upgrade_prices() instead" , DeprecationWarning ) mask = [ 'description' , 'capacity' , 'units' , 'prices[id,locationGroupId,categories[name,id,categoryCode]]' ] mask = "mask[%s]" % ',' . join ( mask ) package_keyname = "CLOUD_SERVER" package = self . ordering_manager . get_package_by_key ( package_keyname ) package_service = self . client [ 'Product_Package' ] return package_service . getItems ( id = package [ 'id' ] , mask = mask ) | Following Method gets all the item ids related to VS . |
45,848 | def _get_upgrade_prices ( self , instance_id , include_downgrade_options = True ) : mask = [ 'id' , 'locationGroupId' , 'categories[name,id,categoryCode]' , 'item[description,capacity,units]' ] mask = "mask[%s]" % ',' . join ( mask ) return self . guest . getUpgradeItemPrices ( include_downgrade_options , id = instance_id , mask = mask ) | Following Method gets all the price ids related to upgrading a VS . |
45,849 | def _get_price_id_for_upgrade_option ( self , upgrade_prices , option , value , public = True ) : option_category = { 'memory' : 'ram' , 'cpus' : 'guest_core' , 'nic_speed' : 'port_speed' } category_code = option_category . get ( option ) for price in upgrade_prices : if price . get ( 'categories' ) is None or price . get ( 'item' ) is None : continue product = price . get ( 'item' ) is_private = ( product . get ( 'units' ) == 'PRIVATE_CORE' or product . get ( 'units' ) == 'DEDICATED_CORE' ) for category in price . get ( 'categories' ) : if not ( category . get ( 'categoryCode' ) == category_code and str ( product . get ( 'capacity' ) ) == str ( value ) ) : continue if option == 'cpus' : if public and not is_private : return price . get ( 'id' ) elif not public and is_private : return price . get ( 'id' ) elif option == 'nic_speed' : if 'Public' in product . get ( 'description' ) : return price . get ( 'id' ) else : return price . get ( 'id' ) | Find the price id for the option and value to upgrade . This |
45,850 | def _get_price_id_for_upgrade ( self , package_items , option , value , public = True ) : warnings . warn ( "use _get_price_id_for_upgrade_option() instead" , DeprecationWarning ) option_category = { 'memory' : 'ram' , 'cpus' : 'guest_core' , 'nic_speed' : 'port_speed' } category_code = option_category [ option ] for item in package_items : is_private = ( item . get ( 'units' ) == 'PRIVATE_CORE' ) for price in item [ 'prices' ] : if 'locationGroupId' in price and price [ 'locationGroupId' ] : continue if 'categories' not in price : continue categories = price [ 'categories' ] for category in categories : if not ( category [ 'categoryCode' ] == category_code and str ( item [ 'capacity' ] ) == str ( value ) ) : continue if option == 'cpus' : if public and not is_private : return price [ 'id' ] elif not public and is_private : return price [ 'id' ] elif option == 'nic_speed' : if 'Public' in item [ 'description' ] : return price [ 'id' ] else : return price [ 'id' ] | Find the price id for the option and value to upgrade . |
45,851 | def interface_list ( env , securitygroup_id , sortby ) : mgr = SoftLayer . NetworkManager ( env . client ) table = formatting . Table ( COLUMNS ) table . sortby = sortby mask = ( ) secgroup = mgr . get_securitygroup ( securitygroup_id , mask = mask ) for binding in secgroup . get ( 'networkComponentBindings' , [ ] ) : interface_id = binding [ 'networkComponentId' ] try : interface = binding [ 'networkComponent' ] vsi = interface [ 'guest' ] vsi_id = vsi [ 'id' ] hostname = vsi [ 'hostname' ] priv_pub = 'PRIVATE' if interface [ 'port' ] == 0 else 'PUBLIC' ip_address = ( vsi [ 'primaryBackendIpAddress' ] if interface [ 'port' ] == 0 else vsi [ 'primaryIpAddress' ] ) except KeyError : vsi_id = "N/A" hostname = "Not enough permission to view" priv_pub = "N/A" ip_address = "N/A" table . add_row ( [ interface_id , vsi_id , hostname , priv_pub , ip_address ] ) env . fout ( table ) | List interfaces associated with security groups . |
45,852 | def add ( env , securitygroup_id , network_component , server , interface ) : _validate_args ( network_component , server , interface ) mgr = SoftLayer . NetworkManager ( env . client ) component_id = _get_component_id ( env , network_component , server , interface ) ret = mgr . attach_securitygroup_component ( securitygroup_id , component_id ) if not ret : raise exceptions . CLIAbort ( "Could not attach network component" ) table = formatting . Table ( REQUEST_COLUMNS ) table . add_row ( [ ret [ 'requestId' ] ] ) env . fout ( table ) | Attach an interface to a security group . |
45,853 | def default_select ( identifier , all_entry_points ) : if len ( all_entry_points ) == 0 : raise PluginMissingError ( identifier ) elif len ( all_entry_points ) == 1 : return all_entry_points [ 0 ] elif len ( all_entry_points ) > 1 : raise AmbiguousPluginError ( all_entry_points ) | Raise an exception when we have ambiguous entry points . |
45,854 | def _load_class_entry_point ( cls , entry_point ) : class_ = entry_point . load ( ) setattr ( class_ , 'plugin_name' , entry_point . name ) return class_ | Load entry_point and set the entry_point . name as the attribute plugin_name on the loaded object |
45,855 | def load_class ( cls , identifier , default = None , select = None ) : identifier = identifier . lower ( ) key = ( cls . entry_point , identifier ) if key not in PLUGIN_CACHE : if select is None : select = default_select all_entry_points = list ( pkg_resources . iter_entry_points ( cls . entry_point , name = identifier ) ) for extra_identifier , extra_entry_point in cls . extra_entry_points : if identifier == extra_identifier : all_entry_points . append ( extra_entry_point ) try : selected_entry_point = select ( identifier , all_entry_points ) except PluginMissingError : if default is not None : return default raise PLUGIN_CACHE [ key ] = cls . _load_class_entry_point ( selected_entry_point ) return PLUGIN_CACHE [ key ] | Load a single class specified by identifier . |
45,856 | def load_classes ( cls , fail_silently = True ) : all_classes = itertools . chain ( pkg_resources . iter_entry_points ( cls . entry_point ) , ( entry_point for identifier , entry_point in cls . extra_entry_points ) , ) for class_ in all_classes : try : yield ( class_ . name , cls . _load_class_entry_point ( class_ ) ) except Exception : if fail_silently : log . warning ( 'Unable to load %s %r' , cls . __name__ , class_ . name , exc_info = True ) else : raise | Load all the classes for a plugin . |
45,857 | def register_temp_plugin ( cls , class_ , identifier = None , dist = 'xblock' ) : from mock import Mock if identifier is None : identifier = class_ . __name__ . lower ( ) entry_point = Mock ( dist = Mock ( key = dist ) , load = Mock ( return_value = class_ ) , ) entry_point . name = identifier def _decorator ( func ) : @ functools . wraps ( func ) def _inner ( * args , ** kwargs ) : global PLUGIN_CACHE old = list ( cls . extra_entry_points ) old_cache = PLUGIN_CACHE cls . extra_entry_points . append ( ( identifier , entry_point ) ) PLUGIN_CACHE = { } try : return func ( * args , ** kwargs ) finally : cls . extra_entry_points = old PLUGIN_CACHE = old_cache return _inner return _decorator | Decorate a function to run with a temporary plugin available . |
45,858 | def webob_to_django_response ( webob_response ) : from django . http import HttpResponse django_response = HttpResponse ( webob_response . app_iter , content_type = webob_response . content_type , status = webob_response . status_code , ) for name , value in webob_response . headerlist : django_response [ name ] = value return django_response | Returns a django response to the webob_response |
45,859 | def querydict_to_multidict ( query_dict , wrap = None ) : wrap = wrap or ( lambda val : val ) return MultiDict ( chain . from_iterable ( six . moves . zip ( repeat ( key ) , ( wrap ( v ) for v in vals ) ) for key , vals in six . iterlists ( query_dict ) ) ) | Returns a new webob . MultiDict from a django . http . QueryDict . |
45,860 | def _meta_name ( self , name ) : name = name . upper ( ) . replace ( '-' , '_' ) if name not in self . UNPREFIXED_HEADERS : name = 'HTTP_' + name return name | Translate HTTP header names to the format used by Django request objects . |
45,861 | def _un_meta_name ( self , name ) : if name . startswith ( 'HTTP_' ) : name = name [ 5 : ] return name . replace ( '_' , '-' ) . title ( ) | Reverse of _meta_name |
45,862 | def environ ( self ) : environ = dict ( self . _request . META ) environ [ 'PATH_INFO' ] = self . _request . path_info return environ | Add path_info to the request s META dictionary . |
45,863 | def _getfield ( self , block , name ) : block_field = getattr ( block . __class__ , name , None ) if block_field is not None and isinstance ( block_field , Field ) : return block_field raise KeyError ( name ) | Return the field with the given name from block . If no field with name exists in any namespace raises a KeyError . |
45,864 | def get ( self , block , name ) : return self . _kvs . get ( self . _key ( block , name ) ) | Retrieve the value for the field named name . |
45,865 | def set ( self , block , name , value ) : self . _kvs . set ( self . _key ( block , name ) , value ) | Set the value of the field named name |
45,866 | def delete ( self , block , name ) : self . _kvs . delete ( self . _key ( block , name ) ) | Reset the value of the field named name to the default |
45,867 | def has ( self , block , name ) : try : return self . _kvs . has ( self . _key ( block , name ) ) except KeyError : return False | Return whether or not the field named name has a non - default value |
45,868 | def set_many ( self , block , update_dict ) : updated_dict = { } for ( key , value ) in six . iteritems ( update_dict ) : updated_dict [ self . _key ( block , key ) ] = value self . _kvs . set_many ( updated_dict ) | Update the underlying model with the correct values . |
45,869 | def create_aside ( self , definition_id , usage_id , aside_type ) : return ( self . ASIDE_DEFINITION_ID ( definition_id , aside_type ) , self . ASIDE_USAGE_ID ( usage_id , aside_type ) , ) | Create the aside . |
45,870 | def create_usage ( self , def_id ) : usage_id = self . _next_id ( "u" ) self . _usages [ usage_id ] = def_id return usage_id | Make a usage storing its definition id . |
45,871 | def get_definition_id ( self , usage_id ) : try : return self . _usages [ usage_id ] except KeyError : raise NoSuchUsage ( repr ( usage_id ) ) | Get a definition_id by its usage id . |
45,872 | def create_definition ( self , block_type , slug = None ) : prefix = "d" if slug : prefix += "_" + slug def_id = self . _next_id ( prefix ) self . _definitions [ def_id ] = block_type return def_id | Make a definition storing its block type . |
45,873 | def get_block_type ( self , def_id ) : try : return self . _definitions [ def_id ] except KeyError : try : return def_id . aside_type except AttributeError : raise NoSuchDefinition ( repr ( def_id ) ) | Get a block_type by its definition id . |
45,874 | def field_data ( self , field_data ) : warnings . warn ( "Runtime.field_data is deprecated" , FieldDataDeprecationWarning , stacklevel = 2 ) self . _deprecated_per_instance_field_data = field_data | Set field_data . |
45,875 | def construct_xblock_from_class ( self , cls , scope_ids , field_data = None , * args , ** kwargs ) : return self . mixologist . mix ( cls ) ( runtime = self , field_data = field_data , scope_ids = scope_ids , * args , ** kwargs ) | Construct a new xblock of type cls mixing in the mixins defined for this application . |
45,876 | def get_block ( self , usage_id , for_parent = None ) : def_id = self . id_reader . get_definition_id ( usage_id ) try : block_type = self . id_reader . get_block_type ( def_id ) except NoSuchDefinition : raise NoSuchUsage ( repr ( usage_id ) ) keys = ScopeIds ( self . user_id , block_type , def_id , usage_id ) block = self . construct_xblock ( block_type , keys , for_parent = for_parent ) return block | Create an XBlock instance in this runtime . |
45,877 | def get_aside ( self , aside_usage_id ) : aside_type = self . id_reader . get_aside_type_from_usage ( aside_usage_id ) xblock_usage = self . id_reader . get_usage_id_from_aside ( aside_usage_id ) xblock_def = self . id_reader . get_definition_id ( xblock_usage ) aside_def_id , aside_usage_id = self . id_generator . create_aside ( xblock_def , xblock_usage , aside_type ) keys = ScopeIds ( self . user_id , aside_type , aside_def_id , aside_usage_id ) block = self . create_aside ( aside_type , keys ) return block | Create an XBlockAside in this runtime . |
45,878 | def parse_xml_string ( self , xml , id_generator = None ) : if id_generator is not None : warnings . warn ( "Passing an id_generator directly is deprecated " "in favor of constructing the Runtime with the id_generator" , DeprecationWarning , stacklevel = 2 , ) id_generator = id_generator or self . id_generator if isinstance ( xml , six . binary_type ) : io_type = BytesIO else : io_type = StringIO return self . parse_xml_file ( io_type ( xml ) , id_generator ) | Parse a string of XML returning a usage id . |
45,879 | def parse_xml_file ( self , fileobj , id_generator = None ) : root = etree . parse ( fileobj ) . getroot ( ) usage_id = self . _usage_id_from_node ( root , None , id_generator ) return usage_id | Parse an open XML file returning a usage id . |
45,880 | def _usage_id_from_node ( self , node , parent_id , id_generator = None ) : if id_generator is not None : warnings . warn ( "Passing an id_generator directly is deprecated " "in favor of constructing the Runtime with the id_generator" , DeprecationWarning , stacklevel = 3 , ) id_generator = id_generator or self . id_generator block_type = node . tag node . attrib . pop ( 'xblock-family' , None ) def_id = id_generator . create_definition ( block_type ) usage_id = id_generator . create_usage ( def_id ) keys = ScopeIds ( None , block_type , def_id , usage_id ) block_class = self . mixologist . mix ( self . load_block_type ( block_type ) ) aside_children = [ ] for child in node . iterchildren ( ) : xblock_family = child . attrib . pop ( 'xblock-family' , None ) if xblock_family : xblock_family = self . _family_id_to_superclass ( xblock_family ) if issubclass ( xblock_family , XBlockAside ) : aside_children . append ( child ) for child in aside_children : self . _aside_from_xml ( child , def_id , usage_id , id_generator ) node . remove ( child ) block = block_class . parse_xml ( node , self , keys , id_generator ) block . parent = parent_id block . save ( ) return usage_id | Create a new usage id from an XML dom node . |
45,881 | def _aside_from_xml ( self , node , block_def_id , block_usage_id , id_generator ) : id_generator = id_generator or self . id_generator aside_type = node . tag aside_class = self . load_aside_type ( aside_type ) aside_def_id , aside_usage_id = id_generator . create_aside ( block_def_id , block_usage_id , aside_type ) keys = ScopeIds ( None , aside_type , aside_def_id , aside_usage_id ) aside = aside_class . parse_xml ( node , self , keys , id_generator ) aside . save ( ) | Create an aside from the xml and attach it to the given block |
45,882 | def add_node_as_child ( self , block , node , id_generator = None ) : usage_id = self . _usage_id_from_node ( node , block . scope_ids . usage_id , id_generator ) block . children . append ( usage_id ) | Called by XBlock . parse_xml to treat a child node as a child block . |
45,883 | def export_to_xml ( self , block , xmlfile ) : root = etree . Element ( "unknown_root" , nsmap = XML_NAMESPACES ) tree = etree . ElementTree ( root ) block . add_xml_to_node ( root ) for aside in self . get_asides ( block ) : if aside . needs_serialization ( ) : aside_node = etree . Element ( "unknown_root" , nsmap = XML_NAMESPACES ) aside . add_xml_to_node ( aside_node ) block . append ( aside_node ) tree . write ( xmlfile , xml_declaration = True , pretty_print = True , encoding = 'utf-8' ) | Export the block to XML writing the XML to xmlfile . |
45,884 | def add_block_as_child_node ( self , block , node ) : child = etree . SubElement ( node , "unknown" ) block . add_xml_to_node ( child ) | Export block as a child node of node . |
45,885 | def render ( self , block , view_name , context = None ) : old_view_name = self . _view_name self . _view_name = view_name try : view_fn = getattr ( block , view_name , None ) if view_fn is None : view_fn = getattr ( block , "fallback_view" , None ) if view_fn is None : raise NoSuchViewError ( block , view_name ) view_fn = functools . partial ( view_fn , view_name ) frag = view_fn ( context ) block . save ( ) updated_frag = self . wrap_xblock ( block , view_name , frag , context ) return self . render_asides ( block , view_name , updated_frag , context ) finally : self . _view_name = old_view_name | Render a block by invoking its view . |
45,886 | def render_child ( self , child , view_name = None , context = None ) : return child . render ( view_name or self . _view_name , context ) | A shortcut to render a child block . |
45,887 | def render_children ( self , block , view_name = None , context = None ) : results = [ ] for child_id in block . children : child = self . get_block ( child_id ) result = self . render_child ( child , view_name , context ) results . append ( result ) return results | Render a block s children returning a list of results . |
45,888 | def wrap_xblock ( self , block , view , frag , context ) : if hasattr ( self , 'wrap_child' ) : log . warning ( "wrap_child is deprecated in favor of wrap_xblock and wrap_aside %s" , self . __class__ ) return self . wrap_child ( block , view , frag , context ) extra_data = { 'name' : block . name } if block . name else { } return self . _wrap_ele ( block , view , frag , extra_data ) | Creates a div which identifies the xblock and writes out the json_init_args into a script tag . |
45,889 | def wrap_aside ( self , block , aside , view , frag , context ) : return self . _wrap_ele ( aside , view , frag , { 'block_id' : block . scope_ids . usage_id , 'url_selector' : 'asideBaseUrl' , } ) | Creates a div which identifies the aside points to the original block and writes out the json_init_args into a script tag . |
45,890 | def _wrap_ele ( self , block , view , frag , extra_data = None ) : wrapped = Fragment ( ) data = { 'usage' : block . scope_ids . usage_id , 'block-type' : block . scope_ids . block_type , } data . update ( extra_data ) if frag . js_init_fn : data [ 'init' ] = frag . js_init_fn data [ 'runtime-version' ] = frag . js_init_version json_init = "" if hasattr ( frag , 'json_init_args' ) and frag . json_init_args is not None : json_init = ( '<script type="json/xblock-args" class="xblock_json_init_args">' '{data}</script>' ) . format ( data = json . dumps ( frag . json_init_args ) ) block_css_entrypoint = block . entry_point . replace ( '.' , '-' ) css_classes = [ block_css_entrypoint , '{}-{}' . format ( block_css_entrypoint , view ) , ] html = "<div class='{}'{properties}>{body}{js}</div>" . format ( markupsafe . escape ( ' ' . join ( css_classes ) ) , properties = "" . join ( " data-%s='%s'" % item for item in list ( data . items ( ) ) ) , body = frag . body_html ( ) , js = json_init ) wrapped . add_content ( html ) wrapped . add_fragment_resources ( frag ) return wrapped | Does the guts of the wrapping the same way for both xblocks and asides . Their wrappers provide other info in extra_data which gets put into the dom data - attrs . |
45,891 | def get_asides ( self , block ) : aside_instances = [ self . get_aside_of_type ( block , aside_type ) for aside_type in self . applicable_aside_types ( block ) ] return [ aside_instance for aside_instance in aside_instances if aside_instance . should_apply_to_block ( block ) ] | Return instances for all of the asides that will decorate this block . |
45,892 | def get_aside_of_type ( self , block , aside_type ) : if self . id_generator is None : raise Exception ( "Runtimes must be supplied with an IdGenerator to load XBlockAsides." ) usage_id = block . scope_ids . usage_id aside_cls = self . load_aside_type ( aside_type ) definition_id = self . id_reader . get_definition_id ( usage_id ) aside_def_id , aside_usage_id = self . id_generator . create_aside ( definition_id , usage_id , aside_type ) scope_ids = ScopeIds ( self . user_id , aside_type , aside_def_id , aside_usage_id ) return aside_cls ( runtime = self , scope_ids = scope_ids ) | Return the aside of the given aside_type which might be decorating this block . |
45,893 | def render_asides ( self , block , view_name , frag , context ) : aside_frag_fns = [ ] for aside in self . get_asides ( block ) : aside_view_fn = aside . aside_view_declaration ( view_name ) if aside_view_fn is not None : aside_frag_fns . append ( ( aside , aside_view_fn ) ) if aside_frag_fns : return self . layout_asides ( block , context , frag , view_name , aside_frag_fns ) return frag | Collect all of the asides add ons and format them into the frag . The frag already has the given block s rendering . |
45,894 | def layout_asides ( self , block , context , frag , view_name , aside_frag_fns ) : result = Fragment ( frag . content ) result . add_fragment_resources ( frag ) for aside , aside_fn in aside_frag_fns : aside_frag = self . wrap_aside ( block , aside , view_name , aside_fn ( block , context ) , context ) aside . save ( ) result . add_content ( aside_frag . content ) result . add_fragment_resources ( aside_frag ) return result | Execute and layout the aside_frags wrt the block s frag . Runtimes should feel free to override this method to control execution place and style the asides appropriately for their application |
45,895 | def handle ( self , block , handler_name , request , suffix = '' ) : handler = getattr ( block , handler_name , None ) if handler and getattr ( handler , '_is_xblock_handler' , False ) : results = handler ( request , suffix ) else : fallback_handler = getattr ( block , "fallback_handler" , None ) if fallback_handler and getattr ( fallback_handler , '_is_xblock_handler' , False ) : results = fallback_handler ( handler_name , request , suffix ) else : raise NoSuchHandlerError ( "Couldn't find handler %r for %r" % ( handler_name , block ) ) block . save ( ) return results | Handles any calls to the specified handler_name . |
45,896 | def service ( self , block , service_name ) : declaration = block . service_declaration ( service_name ) if declaration is None : raise NoSuchServiceError ( "Service {!r} was not requested." . format ( service_name ) ) service = self . _services . get ( service_name ) if service is None and declaration == "need" : raise NoSuchServiceError ( "Service {!r} is not available." . format ( service_name ) ) return service | Return a service or None . |
45,897 | def querypath ( self , block , path ) : class BadPath ( Exception ) : pass results = self . query ( block ) ROOT , SEP , WORD , FINAL = six . moves . range ( 4 ) state = ROOT lexer = RegexLexer ( ( "dotdot" , r"\.\." ) , ( "dot" , r"\." ) , ( "slashslash" , r"//" ) , ( "slash" , r"/" ) , ( "atword" , r"@\w+" ) , ( "word" , r"\w+" ) , ( "err" , r"." ) , ) for tokname , toktext in lexer . lex ( path ) : if state == FINAL : raise BadPath ( ) if tokname == "dotdot" : if state == WORD : raise BadPath ( ) results = results . parent ( ) state = WORD elif tokname == "dot" : if state == WORD : raise BadPath ( ) state = WORD elif tokname == "slashslash" : if state == SEP : raise BadPath ( ) if state == ROOT : raise NotImplementedError ( ) results = results . descendants ( ) state = SEP elif tokname == "slash" : if state == SEP : raise BadPath ( ) if state == ROOT : raise NotImplementedError ( ) state = SEP elif tokname == "atword" : if state != SEP : raise BadPath ( ) results = results . attr ( toktext [ 1 : ] ) state = FINAL elif tokname == "word" : if state != SEP : raise BadPath ( ) results = results . children ( ) . tagged ( toktext ) state = WORD else : raise BadPath ( "Invalid thing: %r" % toktext ) return results | An XPath - like interface to query . |
45,898 | def _object_with_attr ( self , name ) : for obj in self . _objects : if hasattr ( obj , name ) : return obj raise AttributeError ( "No object has attribute {!r}" . format ( name ) ) | Returns the first object that has the attribute name |
45,899 | def mix ( self , cls ) : if hasattr ( cls , 'unmixed_class' ) : base_class = cls . unmixed_class old_mixins = cls . __bases__ [ 1 : ] mixins = old_mixins + tuple ( mixin for mixin in self . _mixins if mixin not in old_mixins ) else : base_class = cls mixins = self . _mixins mixin_key = ( base_class , mixins ) if mixin_key not in _CLASS_CACHE : with _CLASS_CACHE_LOCK : return _CLASS_CACHE . setdefault ( mixin_key , type ( base_class . __name__ + str ( 'WithMixins' ) , ( base_class , ) + mixins , { 'unmixed_class' : base_class } ) ) else : return _CLASS_CACHE [ mixin_key ] | Returns a subclass of cls mixed with self . mixins . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.