idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
27,000
def flavor_extra_delete ( request , flavor_id , keys ) : flavor = _nova . novaclient ( request ) . flavors . get ( flavor_id ) return flavor . unset_keys ( keys )
Unset the flavor extra spec keys .
27,001
def flavor_extra_set ( request , flavor_id , metadata ) : flavor = _nova . novaclient ( request ) . flavors . get ( flavor_id ) if ( not metadata ) : return None return flavor . set_keys ( metadata )
Set the flavor extra spec keys .
27,002
def server_console_output ( request , instance_id , tail_length = None ) : nc = _nova . novaclient ( request ) return nc . servers . get_console_output ( instance_id , length = tail_length )
Gets console output of an instance .
27,003
def list_extensions ( request ) : blacklist = set ( getattr ( settings , 'OPENSTACK_NOVA_EXTENSIONS_BLACKLIST' , [ ] ) ) nova_api = _nova . novaclient ( request ) return tuple ( extension for extension in nova_list_extensions . ListExtManager ( nova_api ) . show_all ( ) if extension . name not in blacklist )
List all nova extensions except the ones in the blacklist .
27,004
def extension_supported ( extension_name , request ) : for ext in list_extensions ( request ) : if ext . name == extension_name : return True return False
Determine if nova supports a given extension name .
27,005
def call_functions_parallel ( * worker_defs ) : max_workers = len ( worker_defs ) futures = [ None ] * len ( worker_defs ) with futurist . ThreadPoolExecutor ( max_workers = max_workers ) as e : for index , func_def in enumerate ( worker_defs ) : if callable ( func_def ) : func_def = [ func_def ] args = func_def [ 1 ] ...
Call specified functions in parallel .
27,006
def generate_key ( key_length = 64 ) : if hasattr ( random , 'SystemRandom' ) : logging . info ( 'Generating a secure random key using SystemRandom.' ) choice = random . SystemRandom ( ) . choice else : msg = "WARNING: SystemRandom not present. Generating a random " "key using random.choice (NOT CRYPTOGRAPHICALLY SECUR...
Secret key generator .
27,007
def generate_or_read_from_file ( key_file = '.secret_key' , key_length = 64 ) : abspath = os . path . abspath ( key_file ) if os . path . exists ( key_file ) : key = read_from_file ( key_file ) return key lock = lockutils . external_lock ( key_file + ".lock" , lock_path = os . path . dirname ( abspath ) ) with lock : i...
Multiprocess - safe secret key file generator .
27,008
def register ( view ) : p = urls . url ( view . url_regex , view . as_view ( ) ) urlpatterns . append ( p ) return view
Register API views to respond to a regex pattern .
27,009
def shellfilter ( value ) : replacements = { '\\' : '\\\\' , '`' : '\\`' , "'" : "\\'" , '"' : '\\"' } for search , repl in replacements . items ( ) : value = value . replace ( search , repl ) return safestring . mark_safe ( value )
Replace HTML chars for shell usage .
27,010
def websso ( request ) : referer = request . META . get ( 'HTTP_REFERER' , settings . OPENSTACK_KEYSTONE_URL ) auth_url = utils . clean_up_auth_url ( referer ) token = request . POST . get ( 'token' ) try : request . user = auth . authenticate ( request = request , auth_url = auth_url , token = token ) except exception...
Logs a user in using a token from Keystone s POST .
27,011
def logout ( request , login_url = None , ** kwargs ) : msg = 'Logging out user "%(username)s".' % { 'username' : request . user . username } LOG . info ( msg ) if ( utils . is_websso_enabled and utils . is_websso_default_redirect ( ) and utils . get_websso_default_redirect_logout ( ) ) : auth_user . unset_session_user...
Logs out the user if he is logged in . Then redirects to the log - in page .
27,012
def switch ( request , tenant_id , redirect_field_name = auth . REDIRECT_FIELD_NAME ) : LOG . debug ( 'Switching to tenant %s for user "%s".' , tenant_id , request . user . username ) endpoint , __ = utils . fix_auth_url_version_prefix ( request . user . endpoint ) session = utils . get_session ( ) unscoped_token = req...
Switches an authenticated user from one project to another .
27,013
def switch_region ( request , region_name , redirect_field_name = auth . REDIRECT_FIELD_NAME ) : if region_name in request . user . available_services_regions : request . session [ 'services_region' ] = region_name LOG . debug ( 'Switching services region to %s for user "%s".' , region_name , request . user . username ...
Switches the user s region for all services except Identity service .
27,014
def switch_keystone_provider ( request , keystone_provider = None , redirect_field_name = auth . REDIRECT_FIELD_NAME ) : base_token = request . session . get ( 'k2k_base_unscoped_token' , None ) k2k_auth_url = request . session . get ( 'k2k_auth_url' , None ) keystone_providers = request . session . get ( 'keystone_pro...
Switches the user s keystone provider using K2K Federation
27,015
def get_link_url ( self , datum = None ) : if not self . url : raise NotImplementedError ( 'A LinkAction class must have a ' 'url attribute or define its own ' 'get_link_url method.' ) if callable ( self . url ) : return self . url ( datum , ** self . kwargs ) try : if datum : obj_id = self . table . get_object_id ( da...
Returns the final URL based on the value of url .
27,016
def get_param_name ( self ) : return "__" . join ( [ self . table . name , self . name , self . param_name ] )
Returns the full query parameter name for this action .
27,017
def is_api_filter ( self , filter_field ) : if self . filter_type == 'server' : for choice in self . filter_choices : if ( choice [ 0 ] == filter_field and len ( choice ) > 2 and choice [ 2 ] ) : return True return False
Determine if agiven filter field should be used as an API filter .
27,018
def get_select_options ( self ) : if self . filter_choices : return [ choice [ : 4 ] for choice in self . filter_choices if len ( choice ) < 5 or choice [ 4 ] ]
Provide the value string and help_text for the template to render .
27,019
def _get_action_name ( self , items = None , past = False ) : action_type = "past" if past else "present" if items is None : count = 1 else : count = len ( items ) action_attr = getattr ( self , "action_%s" % action_type ) ( count ) if isinstance ( action_attr , ( six . string_types , Promise ) ) : action = action_attr...
Retreive action name based on the number of items and past flag .
27,020
def update ( self , request , datum ) : if getattr ( self , 'action_present' , False ) : self . verbose_name = self . _get_action_name ( ) self . verbose_name_plural = self . _get_action_name ( 'plural' )
Switches the action verbose name if needed .
27,021
def get_default_attrs ( self ) : attrs = super ( BatchAction , self ) . get_default_attrs ( ) attrs . update ( { 'data-batch-action' : 'true' } ) return attrs
Returns a list of the default HTML attributes for the action .
27,022
def get_tabs ( self , request , ** kwargs ) : if self . _tab_group is None : self . _tab_group = self . tab_group_class ( request , ** kwargs ) return self . _tab_group
Returns the initialized tab group for this view .
27,023
def get_context_data ( self , ** kwargs ) : context = super ( TabView , self ) . get_context_data ( ** kwargs ) try : tab_group = self . get_tabs ( self . request , ** kwargs ) context [ "tab_group" ] = tab_group context [ "tab_group" ] . load_tab_data ( ) except Exception : exceptions . handle ( self . request ) retur...
Adds the tab_group variable to the context data .
27,024
def handle_tabbed_response ( self , tab_group , context ) : if self . request . is_ajax ( ) : if tab_group . selected : return http . HttpResponse ( tab_group . selected . render ( ) ) else : return http . HttpResponse ( tab_group . render ( ) ) return self . render_to_response ( context )
Sends back an AJAX - appropriate response for the tab group if needed .
27,025
def load_tabs ( self ) : tab_group = self . get_tabs ( self . request , ** self . kwargs ) tabs = tab_group . get_tabs ( ) for tab in [ t for t in tabs if issubclass ( t . __class__ , TableTab ) ] : self . table_classes . extend ( tab . table_classes ) for table in tab . _tables . values ( ) : self . _table_dict [ tabl...
Loads the tab group .
27,026
def handle_table ( self , table_dict ) : table = table_dict [ 'table' ] tab = table_dict [ 'tab' ] tab . load_table_data ( ) table_name = table . _meta . name tab . _tables [ table_name ] . _meta . has_prev_data = self . has_prev_data ( table ) tab . _tables [ table_name ] . _meta . has_more_data = self . has_more_data...
Loads the table data based on a given table_dict and handles them .
27,027
def openstack ( request ) : context = { } context . setdefault ( 'authorized_tenants' , [ ] ) if request . user . is_authenticated : context [ 'authorized_tenants' ] = [ tenant for tenant in request . user . authorized_tenants if tenant . enabled ] available_regions = getattr ( settings , 'AVAILABLE_REGIONS' , [ ] ) re...
Context processor necessary for OpenStack Dashboard functionality .
27,028
def is_token_valid ( token , margin = None ) : expiration = token . expires if expiration is None : return False if margin is None : margin = getattr ( settings , 'TOKEN_TIMEOUT_MARGIN' , 0 ) expiration = expiration - datetime . timedelta ( seconds = margin ) if settings . USE_TZ and timezone . is_naive ( expiration ) ...
Timezone - aware checking of the auth token s expiration timestamp .
27,029
def is_safe_url ( url , host = None ) : if not url : return False netloc = urlparse . urlparse ( url ) [ 1 ] return not netloc or netloc == host
Return True if the url is a safe redirection .
27,030
def build_absolute_uri ( request , relative_url ) : webroot = getattr ( settings , 'WEBROOT' , '' ) if webroot . endswith ( "/" ) and relative_url . startswith ( "/" ) : webroot = webroot [ : - 1 ] return request . build_absolute_uri ( webroot + relative_url )
Ensure absolute_uri are relative to WEBROOT .
27,031
def get_websso_url ( request , auth_url , websso_auth ) : origin = build_absolute_uri ( request , '/auth/websso/' ) idp_mapping = getattr ( settings , 'WEBSSO_IDP_MAPPING' , { } ) idp_id , protocol_id = idp_mapping . get ( websso_auth , ( None , websso_auth ) ) if idp_id : url = ( '%s/auth/OS-FEDERATION/identity_provid...
Return the keystone endpoint for initiating WebSSO .
27,032
def has_in_url_path ( url , subs ) : scheme , netloc , path , query , fragment = urlparse . urlsplit ( url ) return any ( [ sub in path for sub in subs ] )
Test if any of subs strings is present in the url path .
27,033
def url_path_replace ( url , old , new , count = None ) : args = [ ] scheme , netloc , path , query , fragment = urlparse . urlsplit ( url ) if count is not None : args . append ( count ) return urlparse . urlunsplit ( ( scheme , netloc , path . replace ( old , new , * args ) , query , fragment ) )
Return a copy of url with replaced path .
27,034
def _augment_url_with_version ( auth_url ) : if has_in_url_path ( auth_url , [ "/v2.0" , "/v3" ] ) : return auth_url if get_keystone_version ( ) >= 3 : return url_path_append ( auth_url , "/v3" ) else : return url_path_append ( auth_url , "/v2.0" )
Optionally augment auth_url path with version suffix .
27,035
def fix_auth_url_version_prefix ( auth_url ) : auth_url = _augment_url_with_version ( auth_url ) url_fixed = False if get_keystone_version ( ) >= 3 and has_in_url_path ( auth_url , [ "/v2.0" ] ) : url_fixed = True auth_url = url_path_replace ( auth_url , "/v2.0" , "/v3" , 1 ) return auth_url , url_fixed
Fix up the auth url if an invalid or no version prefix was given .
27,036
def clean_up_auth_url ( auth_url ) : scheme , netloc , path , query , fragment = urlparse . urlsplit ( auth_url ) return urlparse . urlunsplit ( ( scheme , netloc , re . sub ( r'/auth.*' , '' , path ) , '' , '' ) )
Clean up the auth url to extract the exact Keystone URL
27,037
def default_services_region ( service_catalog , request = None , ks_endpoint = None ) : if service_catalog : available_regions = [ get_endpoint_region ( endpoint ) for service in service_catalog for endpoint in service . get ( 'endpoints' , [ ] ) if ( service . get ( 'type' ) is not None and service . get ( 'type' ) !=...
Return the default service region .
27,038
def set_response_cookie ( response , cookie_name , cookie_value ) : now = timezone . now ( ) expire_date = now + datetime . timedelta ( days = 365 ) response . set_cookie ( cookie_name , cookie_value , expires = expire_date )
Common function for setting the cookie in the response .
27,039
def get_client_ip ( request ) : _SECURE_PROXY_ADDR_HEADER = getattr ( settings , 'SECURE_PROXY_ADDR_HEADER' , False ) if _SECURE_PROXY_ADDR_HEADER : return request . META . get ( _SECURE_PROXY_ADDR_HEADER , request . META . get ( 'REMOTE_ADDR' ) ) return request . META . get ( 'REMOTE_ADDR' )
Return client ip address using SECURE_PROXY_ADDR_HEADER variable .
27,040
def store_initial_k2k_session ( auth_url , request , scoped_auth_ref , unscoped_auth_ref ) : keystone_provider_id = request . session . get ( 'keystone_provider_id' , None ) if keystone_provider_id : return None providers = getattr ( scoped_auth_ref , 'service_providers' , None ) if providers : providers = getattr ( pr...
Stores session variables if there are k2k service providers
27,041
def get_int_or_uuid ( value ) : try : uuid . UUID ( value ) return value except ( ValueError , AttributeError ) : return int ( value )
Check if a value is valid as UUID or an integer .
27,042
def get_display_label ( choices , status ) : for ( value , label ) in choices : if value == ( status or '' ) . lower ( ) : display_label = label break else : display_label = status return display_label
Get a display label for resource status .
27,043
def get_user ( self , user_id ) : if ( hasattr ( self , 'request' ) and user_id == self . request . session [ "user_id" ] ) : token = self . request . session [ 'token' ] endpoint = self . request . session [ 'region_endpoint' ] services_region = self . request . session [ 'services_region' ] user = auth_user . create_...
Returns the current user from the session data .
27,044
def get_all_permissions ( self , user , obj = None ) : if user . is_anonymous or obj is not None : return set ( ) role_perms = { utils . get_role_permission ( role [ 'name' ] ) for role in user . roles } services = [ ] for service in user . service_catalog : try : service_type = service [ 'type' ] except KeyError : con...
Returns a set of permission strings that the user has .
27,045
def has_perm ( self , user , perm , obj = None ) : if not user . is_active : return False return perm in self . get_all_permissions ( user , obj )
Returns True if the given user has the specified permission .
27,046
def handle ( request , message = None , redirect = None , ignore = False , escalate = False , log_level = None , force_log = None ) : exc_type , exc_value , exc_traceback = sys . exc_info ( ) log_method = getattr ( LOG , log_level or "exception" ) force_log = force_log or os . environ . get ( "HORIZON_TEST_RUN" , False...
Centralized error handling for Horizon .
27,047
def load_config ( files = None , root_path = None , local_path = None ) : config = cfg . ConfigOpts ( ) config . register_opts ( [ cfg . Opt ( 'root_path' , default = root_path ) , cfg . Opt ( 'local_path' , default = local_path ) , ] ) if files is not None : config ( args = [ ] , default_config_files = files ) return ...
Load the configuration from specified files .
27,048
def _update_user_roles_names_from_roles_id ( self , user , users_roles , roles_list ) : user_roles_names = [ role . name for role in roles_list if role . id in users_roles ] current_user_roles_names = set ( getattr ( user , "roles" , [ ] ) ) user . roles = list ( current_user_roles_names . union ( user_roles_names ) )
Add roles names to user . roles based on users_roles .
27,049
def _get_users_from_project ( self , project_id , roles , project_users ) : users = api . keystone . user_list ( self . request ) users = { user . id : user for user in users } project_users_roles = api . keystone . get_project_users_roles ( self . request , project = project_id ) for user_id in project_users_roles : i...
Update with users which have role on project NOT through a group .
27,050
def _get_users_from_groups ( self , project_id , roles , project_users ) : groups = api . keystone . group_list ( self . request ) group_names = { group . id : group . name for group in groups } project_groups_roles = api . keystone . get_project_groups_roles ( self . request , project = project_id ) for group_id in pr...
Update with users which have role on project through a group .
27,051
def get_userstable_data ( self ) : project_users = { } project = self . tab_group . kwargs [ 'project' ] try : roles = api . keystone . role_list ( self . request ) self . _get_users_from_project ( project_id = project . id , roles = roles , project_users = project_users ) self . _get_users_from_groups ( project_id = p...
Get users with roles on the project .
27,052
def _objectify ( items , container_name ) : objects = [ ] for item in items : if item . get ( "subdir" , None ) is not None : object_cls = PseudoFolder else : object_cls = StorageObject objects . append ( object_cls ( item , container_name ) ) return objects
Splits a listing of objects into their appropriate wrapper classes .
27,053
def validate ( self , result , spec ) : if spec is None : return if isinstance ( spec , dict ) : if not isinstance ( result , dict ) : raise ValueError ( 'Dictionary expected, but %r found.' % result ) if spec : spec_value = next ( iter ( spec . values ( ) ) ) for value in result . values ( ) : self . validate ( value ...
Validate that the result has the correct structure .
27,054
def update ( self , result , spec ) : if isinstance ( spec , dict ) : if spec : spec_value = next ( iter ( spec . values ( ) ) ) for key , value in result . items ( ) : result [ key ] = self . update ( value , spec_value ) if isinstance ( spec , list ) : if spec : for i , value in enumerate ( result ) : result [ i ] = ...
Replace elements with results of calling callables .
27,055
def get_available_images ( request , project_id = None , images_cache = None ) : if images_cache is None : images_cache = { } public_images = images_cache . get ( 'public_images' , [ ] ) community_images = images_cache . get ( 'community_images' , [ ] ) images_by_project = images_cache . get ( 'images_by_project' , { }...
Returns a list of available images
27,056
def image_field_data ( request , include_empty_option = False ) : try : images = get_available_images ( request , request . user . project_id ) except Exception : exceptions . handle ( request , _ ( 'Unable to retrieve images' ) ) images . sort ( key = lambda c : c . name ) images_list = [ ( '' , _ ( 'Select Image' ) )...
Returns a list of tuples of all images .
27,057
def horizon_main_nav ( context ) : if 'request' not in context : return { } current_dashboard = context [ 'request' ] . horizon . get ( 'dashboard' , None ) dashboards = [ ] for dash in Horizon . get_dashboards ( ) : if dash . can_access ( context ) : if callable ( dash . nav ) and dash . nav ( context ) : dashboards ....
Generates top - level dashboard navigation entries .
27,058
def horizon_dashboard_nav ( context ) : if 'request' not in context : return { } dashboard = context [ 'request' ] . horizon [ 'dashboard' ] panel_groups = dashboard . get_panel_groups ( ) non_empty_groups = [ ] for group in panel_groups . values ( ) : allowed_panels = [ ] for panel in group : if ( callable ( panel . n...
Generates sub - navigation entries for the current dashboard .
27,059
def jstemplate ( parser , token ) : nodelist = parser . parse ( ( 'endjstemplate' , ) ) parser . delete_first_token ( ) return JSTemplateNode ( nodelist )
Templatetag to handle any of the Mustache - based templates .
27,060
def minifyspace ( parser , token ) : nodelist = parser . parse ( ( 'endminifyspace' , ) ) parser . delete_first_token ( ) return MinifiedNode ( nodelist )
Removes whitespace including tab and newline characters .
27,061
def process_message_notification ( request , messages_path ) : if not messages_path : return global _MESSAGES_CACHE global _MESSAGES_MTIME if ( _MESSAGES_CACHE is None or _MESSAGES_MTIME != os . path . getmtime ( messages_path ) ) : _MESSAGES_CACHE = _get_processed_messages ( messages_path ) _MESSAGES_MTIME = os . path...
Process all the msg file found in the message directory
27,062
def load ( self ) : try : self . _read ( ) self . _parse ( ) except Exception as exc : self . failed = True params = { 'path' : self . _path , 'exception' : exc } if self . fail_silently : LOG . warning ( "Error processing message json file '%(path)s': " "%(exception)s" , params ) else : raise exceptions . MessageFailu...
Read and parse the message file .
27,063
def handle_server_filter ( self , request , table = None ) : if not table : table = self . get_table ( ) filter_info = self . get_server_filter_info ( request , table ) if filter_info is None : return False request . session [ filter_info [ 'value_param' ] ] = filter_info [ 'value' ] if filter_info [ 'field_param' ] : ...
Update the table server filter information in the session .
27,064
def update_server_filter_action ( self , request , table = None ) : if not table : table = self . get_table ( ) filter_info = self . get_server_filter_info ( request , table ) if filter_info is not None : action = filter_info [ 'action' ] setattr ( action , 'filter_string' , filter_info [ 'value' ] ) if filter_info [ '...
Update the table server side filter action .
27,065
def get_filters ( self , filters = None , filters_map = None ) : filters = filters or { } filters_map = filters_map or { } filter_action = self . table . _meta . _filter_action if filter_action : filter_field = self . table . get_filter_field ( ) if filter_action . is_api_filter ( filter_field ) : filter_string = self ...
Converts a string given by the user into a valid api filter value .
27,066
def _setup_subnet_parameters ( self , params , data , is_create = True ) : is_update = not is_create params [ 'enable_dhcp' ] = data [ 'enable_dhcp' ] if int ( data [ 'ip_version' ] ) == 6 : ipv6_modes = utils . get_ipv6_modes_attrs_from_menu ( data [ 'ipv6_modes' ] ) if ipv6_modes [ 0 ] and is_create : params [ 'ipv6_...
Setup subnet parameters
27,067
def _delete_network ( self , request , network ) : try : api . neutron . network_delete ( request , network . id ) LOG . debug ( 'Delete the created network %s ' 'due to subnet creation failure.' , network . id ) msg = _ ( 'Delete the created network "%s" ' 'due to subnet creation failure.' ) % network . name redirect ...
Delete the created network when subnet creation failed .
27,068
def bs_progress_bar ( * args , ** kwargs ) : bars = [ ] contexts = kwargs . get ( 'contexts' , [ '' , 'success' , 'info' , 'warning' , 'danger' ] ) for ndx , arg in enumerate ( args ) : bars . append ( dict ( percent = arg , context = kwargs . get ( 'context' , contexts [ ndx % len ( contexts ) ] ) ) ) return { 'bars' ...
A Standard Bootstrap Progress Bar .
27,069
def timesince_or_never ( dt , default = None ) : if default is None : default = _ ( "Never" ) if isinstance ( dt , datetime . date ) : return timesince ( dt ) else : return default
Call the Django timesince filter or a given default string .
27,070
def get_plugin ( self , service_provider = None , auth_url = None , plugins = None , ** kwargs ) : plugins = plugins or [ ] if utils . get_keystone_version ( ) < 3 or not service_provider : return None keystone_idp_id = getattr ( settings , 'KEYSTONE_PROVIDER_IDP_ID' , 'localkeystone' ) if service_provider == keystone_...
Authenticate using keystone to keystone federation .
27,071
def get_access_info ( self , unscoped_auth ) : try : unscoped_auth_ref = base . BasePlugin . get_access_info ( self , unscoped_auth ) except exceptions . KeystoneAuthException as excp : msg = _ ( 'Service provider authentication failed. %s' ) raise exceptions . KeystoneAuthException ( msg % str ( excp ) ) return unscop...
Get the access info object
27,072
def is_token_expired ( self , margin = None ) : if self . token is None : return None return not utils . is_token_valid ( self . token , margin )
Determine if the token is expired .
27,073
def is_superuser ( self ) : admin_roles = utils . get_admin_roles ( ) user_roles = { role [ 'name' ] . lower ( ) for role in self . roles } return not admin_roles . isdisjoint ( user_roles )
Evaluates whether this user has admin privileges .
27,074
def authorized_tenants ( self ) : if self . is_authenticated and self . _authorized_tenants is None : endpoint = self . endpoint try : self . _authorized_tenants = utils . get_project_list ( user_id = self . id , auth_url = endpoint , token = self . unscoped_token , is_federated = self . is_federated ) except ( keyston...
Returns a memoized list of tenants this user may access .
27,075
def available_services_regions ( self ) : regions = [ ] if self . service_catalog : for service in self . service_catalog : service_type = service . get ( 'type' ) if service_type is None or service_type == 'identity' : continue for endpoint in service . get ( 'endpoints' , [ ] ) : region = utils . get_endpoint_region ...
Returns list of unique region name values in service catalog .
27,076
def has_a_matching_perm ( self , perm_list , obj = None ) : if not perm_list : return True for perm in perm_list : if self . has_perm ( perm , obj ) : return True return False
Returns True if the user has one of the specified permissions .
27,077
def has_perms ( self , perm_list , obj = None ) : if not perm_list : return True for perm in perm_list : if isinstance ( perm , six . string_types ) : if not self . has_perm ( perm , obj ) : return False else : if not self . has_a_matching_perm ( perm , obj ) : return False return True
Returns True if the user has all of the specified permissions .
27,078
def time_until_expiration ( self ) : if self . password_expires_at is not None : expiration_date = datetime . datetime . strptime ( self . password_expires_at , "%Y-%m-%dT%H:%M:%S.%f" ) return expiration_date - datetime . datetime . now ( )
Returns the number of remaining days until user s password expires .
27,079
def clear_profiling_cookies ( request , response ) : if 'profile_page' in request . COOKIES : path = request . path response . set_cookie ( 'profile_page' , max_age = 0 , path = path )
Expire any cookie that initiated profiling request .
27,080
def render_context_with_title ( self , context ) : if "page_title" not in context : con = template . Context ( context ) temp = template . Template ( encoding . force_text ( self . page_title ) ) context [ "page_title" ] = temp . render ( con ) return context
Render a page title and insert it into the context .
27,081
def check ( actions , request , target = None ) : if target is None : target = { } user = auth_utils . get_user ( request ) if target . get ( 'project_id' ) is None : target [ 'project_id' ] = user . project_id if target . get ( 'tenant_id' ) is None : target [ 'tenant_id' ] = target [ 'project_id' ] if target . get ( ...
Check user permission .
27,082
def logout_with_message ( request , msg , redirect = True , status = 'success' ) : logout ( request ) if redirect : response = http . HttpResponseRedirect ( '%s?next=%s' % ( settings . LOGOUT_URL , request . path ) ) else : response = http . HttpResponseRedirect ( settings . LOGOUT_URL ) add_logout_reason ( request , r...
Send HttpResponseRedirect to LOGOUT_URL .
27,083
def save_config_value ( request , response , key , value ) : request . session [ key ] = value response . set_cookie ( key , value , expires = one_year_from_now ( ) ) return response
Sets value of key key to value in both session and cookies .
27,084
def next_key ( tuple_of_tuples , key ) : for i , t in enumerate ( tuple_of_tuples ) : if t [ 0 ] == key : try : return tuple_of_tuples [ i + 1 ] [ 0 ] except IndexError : return None
Returns the key which comes after the given key .
27,085
def previous_key ( tuple_of_tuples , key ) : for i , t in enumerate ( tuple_of_tuples ) : if t [ 0 ] == key : try : return tuple_of_tuples [ i - 1 ] [ 0 ] except IndexError : return None
Returns the key which comes before the give key .
27,086
def format_value ( value ) : value = decimal . Decimal ( str ( value ) ) if int ( value ) == value : return int ( value ) return float ( round ( value , 1 ) )
Returns the given value rounded to one decimal place if deciaml .
27,087
def process_exception ( self , request , exception ) : if isinstance ( exception , ( exceptions . NotAuthorized , exceptions . NotAuthenticated ) ) : auth_url = settings . LOGIN_URL next_url = iri_to_uri ( request . get_full_path ( ) ) if next_url != auth_url : field_name = REDIRECT_FIELD_NAME else : field_name = None ...
Catches internal Horizon exception classes .
27,088
def _process_response ( self , request , response ) : if request . is_ajax ( ) and hasattr ( request , 'horizon' ) : queued_msgs = request . horizon [ 'async_messages' ] if type ( response ) == http . HttpResponseRedirect : for tag , message , extra_tags in queued_msgs : getattr ( django_messages , tag ) ( request , me...
Convert HttpResponseRedirect to HttpResponse if request is via ajax .
27,089
def get_domain_id_for_operation ( request ) : domain_context = request . session . get ( 'domain_context' ) if domain_context : return domain_context return api . keystone . get_effective_domain_id ( request )
Get the ID of the domain in which the current operation should happen .
27,090
def get_module_path ( module_name ) : path = sys . path for name in module_name . split ( '.' ) : file_pointer , path , desc = imp . find_module ( name , path ) path = [ path , ] if file_pointer is not None : file_pointer . close ( ) return path [ 0 ]
Gets the module path without importing anything .
27,091
def gendiff ( self , force = False ) : with DirContext ( self . local_settings_dir ) as dircontext : if not os . path . exists ( self . local_settings_diff ) or force : with open ( self . local_settings_example , 'r' ) as fp : example_lines = fp . readlines ( ) with open ( self . local_settings_file , 'r' ) as fp : loc...
Generate a diff between self . local_settings and the example file .
27,092
def patch ( self , force = False ) : with DirContext ( self . local_settings_dir ) as dircontext : if os . path . exists ( self . local_settings_diff ) : if not os . path . exists ( self . local_settings_file ) or force : local_settings_reject = self . local_settings_reject_pattern % ( time . strftime ( self . file_tim...
Patch local_settings . py . example with local_settings . diff .
27,093
def check ( actions , request , target = None ) : policy_check = utils_settings . import_setting ( "POLICY_CHECK_FUNCTION" ) if policy_check : return policy_check ( actions , request , target ) return True
Wrapper of the configurable policy method .
27,094
def get_auth_params_from_request ( request ) : return ( request . user . username , request . user . token . id , request . user . tenant_id , request . user . token . project . get ( 'domain_id' ) , base . url_for ( request , 'compute' ) , base . url_for ( request , 'identity' ) )
Extracts properties needed by novaclient call from the request object .
27,095
def get_context ( request , context = None ) : if context is None : context = { } network_config = getattr ( settings , 'OPENSTACK_NEUTRON_NETWORK' , { } ) context [ 'launch_instance_allowed' ] = policy . check ( ( ( "compute" , "os_compute_api:servers:create" ) , ) , request ) context [ 'instance_quota_exceeded' ] = _...
Returns common context data for network topology views .
27,096
def get_object_id ( self , datum ) : scope_id = "" if "project" in datum . scope : scope_id = datum . scope [ "project" ] [ "id" ] elif "domain" in datum . scope : scope_id = datum . scope [ "domain" ] [ "id" ] assignee_id = "" if hasattr ( datum , "user" ) : assignee_id = datum . user [ "id" ] elif hasattr ( datum , "...
Identifier of the role assignment .
27,097
def get_url_for_service ( service , region , endpoint_type ) : if 'type' not in service : return None identity_version = get_version_from_service ( service ) service_endpoints = service . get ( 'endpoints' , [ ] ) available_endpoints = [ endpoint for endpoint in service_endpoints if region == _get_endpoint_region ( end...
if we are dealing with the identity service and there is no endpoint in the current region it is okay to use the first endpoint for any identity service endpoints and we can assume that it is global
27,098
def is_larger ( unit_1 , unit_2 ) : unit_1 = functions . value_for_key ( INFORMATION_UNITS , unit_1 ) unit_2 = functions . value_for_key ( INFORMATION_UNITS , unit_2 ) return ureg . parse_expression ( unit_1 ) > ureg . parse_expression ( unit_2 )
Returns a boolean indicating whether unit_1 is larger than unit_2 .
27,099
def convert ( value , source_unit , target_unit , fmt = False ) : orig_target_unit = target_unit source_unit = functions . value_for_key ( INFORMATION_UNITS , source_unit ) target_unit = functions . value_for_key ( INFORMATION_UNITS , target_unit ) q = ureg . Quantity ( value , source_unit ) q = q . to ( ureg . parse_e...
Converts value from source_unit to target_unit .