id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
234,900 | openstack/horizon | openstack_auth/user.py | User.is_superuser | def is_superuser(self):
"""Evaluates whether this user has admin privileges.
:returns: ``True`` or ``False``.
"""
admin_roles = utils.get_admin_roles()
user_roles = {role['name'].lower() for role in self.roles}
return not admin_roles.isdisjoint(user_roles) | python | 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) | [
"def",
"is_superuser",
"(",
"self",
")",
":",
"admin_roles",
"=",
"utils",
".",
"get_admin_roles",
"(",
")",
"user_roles",
"=",
"{",
"role",
"[",
"'name'",
"]",
".",
"lower",
"(",
")",
"for",
"role",
"in",
"self",
".",
"roles",
"}",
"return",
"not",
... | Evaluates whether this user has admin privileges.
:returns: ``True`` or ``False``. | [
"Evaluates",
"whether",
"this",
"user",
"has",
"admin",
"privileges",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_auth/user.py#L282-L289 |
234,901 | openstack/horizon | openstack_auth/user.py | User.authorized_tenants | def authorized_tenants(self):
"""Returns a memoized list of tenants this user may access."""
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 (keystone_exceptions.ClientException,
keystone_exceptions.AuthorizationFailure):
LOG.exception('Unable to retrieve project list.')
return self._authorized_tenants or [] | python | 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 (keystone_exceptions.ClientException,
keystone_exceptions.AuthorizationFailure):
LOG.exception('Unable to retrieve project list.')
return self._authorized_tenants or [] | [
"def",
"authorized_tenants",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_authenticated",
"and",
"self",
".",
"_authorized_tenants",
"is",
"None",
":",
"endpoint",
"=",
"self",
".",
"endpoint",
"try",
":",
"self",
".",
"_authorized_tenants",
"=",
"utils",
"... | Returns a memoized list of tenants this user may access. | [
"Returns",
"a",
"memoized",
"list",
"of",
"tenants",
"this",
"user",
"may",
"access",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_auth/user.py#L292-L305 |
234,902 | openstack/horizon | openstack_auth/user.py | User.available_services_regions | def available_services_regions(self):
"""Returns list of unique region name values in service catalog."""
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(endpoint)
if region not in regions:
regions.append(region)
return regions | python | 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(endpoint)
if region not in regions:
regions.append(region)
return regions | [
"def",
"available_services_regions",
"(",
"self",
")",
":",
"regions",
"=",
"[",
"]",
"if",
"self",
".",
"service_catalog",
":",
"for",
"service",
"in",
"self",
".",
"service_catalog",
":",
"service_type",
"=",
"service",
".",
"get",
"(",
"'type'",
")",
"i... | Returns list of unique region name values in service catalog. | [
"Returns",
"list",
"of",
"unique",
"region",
"name",
"values",
"in",
"service",
"catalog",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_auth/user.py#L320-L332 |
234,903 | openstack/horizon | openstack_auth/user.py | User.has_a_matching_perm | def has_a_matching_perm(self, perm_list, obj=None):
"""Returns True if the user has one of the specified permissions.
If object is passed, it checks if the user has any of the required
perms for this object.
"""
# If there are no permissions to check, just return true
if not perm_list:
return True
# Check that user has at least one of the required permissions.
for perm in perm_list:
if self.has_perm(perm, obj):
return True
return False | python | def has_a_matching_perm(self, perm_list, obj=None):
# If there are no permissions to check, just return true
if not perm_list:
return True
# Check that user has at least one of the required permissions.
for perm in perm_list:
if self.has_perm(perm, obj):
return True
return False | [
"def",
"has_a_matching_perm",
"(",
"self",
",",
"perm_list",
",",
"obj",
"=",
"None",
")",
":",
"# If there are no permissions to check, just return true",
"if",
"not",
"perm_list",
":",
"return",
"True",
"# Check that user has at least one of the required permissions.",
"for... | Returns True if the user has one of the specified permissions.
If object is passed, it checks if the user has any of the required
perms for this object. | [
"Returns",
"True",
"if",
"the",
"user",
"has",
"one",
"of",
"the",
"specified",
"permissions",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_auth/user.py#L344-L357 |
234,904 | openstack/horizon | openstack_auth/user.py | User.has_perms | def has_perms(self, perm_list, obj=None):
"""Returns True if the user has all of the specified permissions.
Tuples in the list will possess the required permissions if
the user has a permissions matching one of the elements of
that tuple
"""
# If there are no permissions to check, just return true
if not perm_list:
return True
for perm in perm_list:
if isinstance(perm, six.string_types):
# check that the permission matches
if not self.has_perm(perm, obj):
return False
else:
# check that a permission in the tuple matches
if not self.has_a_matching_perm(perm, obj):
return False
return True | python | def has_perms(self, perm_list, obj=None):
# If there are no permissions to check, just return true
if not perm_list:
return True
for perm in perm_list:
if isinstance(perm, six.string_types):
# check that the permission matches
if not self.has_perm(perm, obj):
return False
else:
# check that a permission in the tuple matches
if not self.has_a_matching_perm(perm, obj):
return False
return True | [
"def",
"has_perms",
"(",
"self",
",",
"perm_list",
",",
"obj",
"=",
"None",
")",
":",
"# If there are no permissions to check, just return true",
"if",
"not",
"perm_list",
":",
"return",
"True",
"for",
"perm",
"in",
"perm_list",
":",
"if",
"isinstance",
"(",
"pe... | Returns True if the user has all of the specified permissions.
Tuples in the list will possess the required permissions if
the user has a permissions matching one of the elements of
that tuple | [
"Returns",
"True",
"if",
"the",
"user",
"has",
"all",
"of",
"the",
"specified",
"permissions",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_auth/user.py#L371-L390 |
234,905 | openstack/horizon | openstack_auth/user.py | User.time_until_expiration | def time_until_expiration(self):
"""Returns the number of remaining days until user's password expires.
Calculates the number days until the user must change their password,
once the password expires the user will not able to log in until an
admin changes its password.
"""
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() | python | 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() | [
"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\"... | Returns the number of remaining days until user's password expires.
Calculates the number days until the user must change their password,
once the password expires the user will not able to log in until an
admin changes its password. | [
"Returns",
"the",
"number",
"of",
"remaining",
"days",
"until",
"user",
"s",
"password",
"expires",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_auth/user.py#L392-L402 |
234,906 | openstack/horizon | openstack_dashboard/contrib/developer/profiler/middleware.py | ProfilerMiddleware.clear_profiling_cookies | def clear_profiling_cookies(request, response):
"""Expire any cookie that initiated profiling request."""
if 'profile_page' in request.COOKIES:
path = request.path
response.set_cookie('profile_page', max_age=0, path=path) | python | 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) | [
"def",
"clear_profiling_cookies",
"(",
"request",
",",
"response",
")",
":",
"if",
"'profile_page'",
"in",
"request",
".",
"COOKIES",
":",
"path",
"=",
"request",
".",
"path",
"response",
".",
"set_cookie",
"(",
"'profile_page'",
",",
"max_age",
"=",
"0",
",... | Expire any cookie that initiated profiling request. | [
"Expire",
"any",
"cookie",
"that",
"initiated",
"profiling",
"request",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/contrib/developer/profiler/middleware.py#L137-L141 |
234,907 | openstack/horizon | horizon/views.py | PageTitleMixin.render_context_with_title | def render_context_with_title(self, context):
"""Render a page title and insert it into the context.
This function takes in a context dict and uses it to render the
page_title variable. It then appends this title to the context using
the 'page_title' key. If there is already a page_title key defined in
context received then this function will do nothing.
"""
if "page_title" not in context:
con = template.Context(context)
# NOTE(sambetts): Use force_text to ensure lazy translations
# are handled correctly.
temp = template.Template(encoding.force_text(self.page_title))
context["page_title"] = temp.render(con)
return context | python | def render_context_with_title(self, context):
if "page_title" not in context:
con = template.Context(context)
# NOTE(sambetts): Use force_text to ensure lazy translations
# are handled correctly.
temp = template.Template(encoding.force_text(self.page_title))
context["page_title"] = temp.render(con)
return context | [
"def",
"render_context_with_title",
"(",
"self",
",",
"context",
")",
":",
"if",
"\"page_title\"",
"not",
"in",
"context",
":",
"con",
"=",
"template",
".",
"Context",
"(",
"context",
")",
"# NOTE(sambetts): Use force_text to ensure lazy translations",
"# are handled co... | Render a page title and insert it into the context.
This function takes in a context dict and uses it to render the
page_title variable. It then appends this title to the context using
the 'page_title' key. If there is already a page_title key defined in
context received then this function will do nothing. | [
"Render",
"a",
"page",
"title",
"and",
"insert",
"it",
"into",
"the",
"context",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/views.py#L45-L60 |
234,908 | openstack/horizon | openstack_auth/policy.py | check | def check(actions, request, target=None):
"""Check user permission.
Check if the user has permission to the action according
to policy setting.
:param actions: list of scope and action to do policy checks on,
the composition of which is (scope, action). Multiple actions
are treated as a logical AND.
* scope: service type managing the policy for action
* action: string representing the action to be checked
this should be colon separated for clarity.
i.e.
| compute:create_instance
| compute:attach_volume
| volume:attach_volume
for a policy action that requires a single action, actions
should look like
| "(("compute", "compute:create_instance"),)"
for a multiple action check, actions should look like
| "(("identity", "identity:list_users"),
| ("identity", "identity:list_roles"))"
:param request: django http request object. If not specified, credentials
must be passed.
:param target: dictionary representing the object of the action
for object creation this should be a dictionary
representing the location of the object e.g.
{'project_id': object.project_id}
:returns: boolean if the user has permission or not for the actions.
"""
if target is None:
target = {}
user = auth_utils.get_user(request)
# Several service policy engines default to a project id check for
# ownership. Since the user is already scoped to a project, if a
# different project id has not been specified use the currently scoped
# project's id.
#
# The reason is the operator can edit the local copies of the service
# policy file. If a rule is removed, then the default rule is used. We
# don't want to block all actions because the operator did not fully
# understand the implication of editing the policy file. Additionally,
# the service APIs will correct us if we are too permissive.
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']
# same for user_id
if target.get('user_id') is None:
target['user_id'] = user.id
domain_id_keys = [
'domain_id',
'project.domain_id',
'user.domain_id',
'group.domain_id'
]
# populates domain id keys with user's current domain id
for key in domain_id_keys:
if target.get(key) is None:
target[key] = user.user_domain_id
credentials = _user_to_credentials(user)
domain_credentials = _domain_to_credentials(request, user)
# if there is a domain token use the domain_id instead of the user's domain
if domain_credentials:
credentials['domain_id'] = domain_credentials.get('domain_id')
enforcer = _get_enforcer()
for action in actions:
scope, action = action[0], action[1]
if scope in enforcer:
# this is for handling the v3 policy file and will only be
# needed when a domain scoped token is present
if scope == 'identity' and domain_credentials:
# use domain credentials
if not _check_credentials(enforcer[scope],
action,
target,
domain_credentials):
return False
# use project credentials
if not _check_credentials(enforcer[scope],
action, target, credentials):
return False
# if no policy for scope, allow action, underlying API will
# ultimately block the action if not permitted, treat as though
# allowed
return True | python | def check(actions, request, target=None):
if target is None:
target = {}
user = auth_utils.get_user(request)
# Several service policy engines default to a project id check for
# ownership. Since the user is already scoped to a project, if a
# different project id has not been specified use the currently scoped
# project's id.
#
# The reason is the operator can edit the local copies of the service
# policy file. If a rule is removed, then the default rule is used. We
# don't want to block all actions because the operator did not fully
# understand the implication of editing the policy file. Additionally,
# the service APIs will correct us if we are too permissive.
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']
# same for user_id
if target.get('user_id') is None:
target['user_id'] = user.id
domain_id_keys = [
'domain_id',
'project.domain_id',
'user.domain_id',
'group.domain_id'
]
# populates domain id keys with user's current domain id
for key in domain_id_keys:
if target.get(key) is None:
target[key] = user.user_domain_id
credentials = _user_to_credentials(user)
domain_credentials = _domain_to_credentials(request, user)
# if there is a domain token use the domain_id instead of the user's domain
if domain_credentials:
credentials['domain_id'] = domain_credentials.get('domain_id')
enforcer = _get_enforcer()
for action in actions:
scope, action = action[0], action[1]
if scope in enforcer:
# this is for handling the v3 policy file and will only be
# needed when a domain scoped token is present
if scope == 'identity' and domain_credentials:
# use domain credentials
if not _check_credentials(enforcer[scope],
action,
target,
domain_credentials):
return False
# use project credentials
if not _check_credentials(enforcer[scope],
action, target, credentials):
return False
# if no policy for scope, allow action, underlying API will
# ultimately block the action if not permitted, treat as though
# allowed
return True | [
"def",
"check",
"(",
"actions",
",",
"request",
",",
"target",
"=",
"None",
")",
":",
"if",
"target",
"is",
"None",
":",
"target",
"=",
"{",
"}",
"user",
"=",
"auth_utils",
".",
"get_user",
"(",
"request",
")",
"# Several service policy engines default to a ... | Check user permission.
Check if the user has permission to the action according
to policy setting.
:param actions: list of scope and action to do policy checks on,
the composition of which is (scope, action). Multiple actions
are treated as a logical AND.
* scope: service type managing the policy for action
* action: string representing the action to be checked
this should be colon separated for clarity.
i.e.
| compute:create_instance
| compute:attach_volume
| volume:attach_volume
for a policy action that requires a single action, actions
should look like
| "(("compute", "compute:create_instance"),)"
for a multiple action check, actions should look like
| "(("identity", "identity:list_users"),
| ("identity", "identity:list_roles"))"
:param request: django http request object. If not specified, credentials
must be passed.
:param target: dictionary representing the object of the action
for object creation this should be a dictionary
representing the location of the object e.g.
{'project_id': object.project_id}
:returns: boolean if the user has permission or not for the actions. | [
"Check",
"user",
"permission",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_auth/policy.py#L86-L186 |
234,909 | openstack/horizon | horizon/utils/functions.py | logout_with_message | def logout_with_message(request, msg, redirect=True, status='success'):
"""Send HttpResponseRedirect to LOGOUT_URL.
`msg` is a message displayed on the login page after the logout, to explain
the logout reason.
"""
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, response, msg, status)
return response | python | 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, response, msg, status)
return response | [
"def",
"logout_with_message",
"(",
"request",
",",
"msg",
",",
"redirect",
"=",
"True",
",",
"status",
"=",
"'success'",
")",
":",
"logout",
"(",
"request",
")",
"if",
"redirect",
":",
"response",
"=",
"http",
".",
"HttpResponseRedirect",
"(",
"'%s?next=%s'"... | Send HttpResponseRedirect to LOGOUT_URL.
`msg` is a message displayed on the login page after the logout, to explain
the logout reason. | [
"Send",
"HttpResponseRedirect",
"to",
"LOGOUT_URL",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/utils/functions.py#L54-L67 |
234,910 | openstack/horizon | horizon/utils/functions.py | save_config_value | def save_config_value(request, response, key, value):
"""Sets value of key `key` to `value` in both session and cookies."""
request.session[key] = value
response.set_cookie(key, value, expires=one_year_from_now())
return response | python | def save_config_value(request, response, key, value):
request.session[key] = value
response.set_cookie(key, value, expires=one_year_from_now())
return response | [
"def",
"save_config_value",
"(",
"request",
",",
"response",
",",
"key",
",",
"value",
")",
":",
"request",
".",
"session",
"[",
"key",
"]",
"=",
"value",
"response",
".",
"set_cookie",
"(",
"key",
",",
"value",
",",
"expires",
"=",
"one_year_from_now",
... | Sets value of key `key` to `value` in both session and cookies. | [
"Sets",
"value",
"of",
"key",
"key",
"to",
"value",
"in",
"both",
"session",
"and",
"cookies",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/utils/functions.py#L96-L100 |
234,911 | openstack/horizon | horizon/utils/functions.py | next_key | def next_key(tuple_of_tuples, key):
"""Returns the key which comes after the given key.
It processes a tuple of 2-element tuples and returns the key which comes
after the given 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 | python | 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 | [
"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",
"]"... | Returns the key which comes after the given key.
It processes a tuple of 2-element tuples and returns the key which comes
after the given key. | [
"Returns",
"the",
"key",
"which",
"comes",
"after",
"the",
"given",
"key",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/utils/functions.py#L151-L162 |
234,912 | openstack/horizon | horizon/utils/functions.py | previous_key | def previous_key(tuple_of_tuples, key):
"""Returns the key which comes before the give key.
It Processes a tuple of 2-element tuples and returns the key which comes
before the given 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 | python | 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 | [
"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",
... | Returns the key which comes before the give key.
It Processes a tuple of 2-element tuples and returns the key which comes
before the given key. | [
"Returns",
"the",
"key",
"which",
"comes",
"before",
"the",
"give",
"key",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/utils/functions.py#L165-L176 |
234,913 | openstack/horizon | horizon/utils/functions.py | format_value | def format_value(value):
"""Returns the given value rounded to one decimal place if deciaml.
Returns the integer if an integer is given.
"""
value = decimal.Decimal(str(value))
if int(value) == value:
return int(value)
# On Python 3, an explicit cast to float is required
return float(round(value, 1)) | python | def format_value(value):
value = decimal.Decimal(str(value))
if int(value) == value:
return int(value)
# On Python 3, an explicit cast to float is required
return float(round(value, 1)) | [
"def",
"format_value",
"(",
"value",
")",
":",
"value",
"=",
"decimal",
".",
"Decimal",
"(",
"str",
"(",
"value",
")",
")",
"if",
"int",
"(",
"value",
")",
"==",
"value",
":",
"return",
"int",
"(",
"value",
")",
"# On Python 3, an explicit cast to float is... | Returns the given value rounded to one decimal place if deciaml.
Returns the integer if an integer is given. | [
"Returns",
"the",
"given",
"value",
"rounded",
"to",
"one",
"decimal",
"place",
"if",
"deciaml",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/utils/functions.py#L179-L189 |
234,914 | openstack/horizon | horizon/middleware/base.py | HorizonMiddleware.process_exception | def process_exception(self, request, exception):
"""Catches internal Horizon exception classes.
Exception classes such as NotAuthorized, NotFound and Http302
are caught and handles them gracefully.
"""
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
login_url = request.build_absolute_uri(auth_url)
response = redirect_to_login(next_url, login_url=login_url,
redirect_field_name=field_name)
if isinstance(exception, exceptions.NotAuthorized):
response.delete_cookie('messages')
return shortcuts.render(request, 'not_authorized.html',
status=403)
if request.is_ajax():
response_401 = http.HttpResponse(status=401)
response_401['X-Horizon-Location'] = response['location']
return response_401
return response
# If an internal "NotFound" error gets this far, return a real 404.
if isinstance(exception, exceptions.NotFound):
raise http.Http404(exception)
if isinstance(exception, exceptions.Http302):
# TODO(gabriel): Find a way to display an appropriate message to
# the user *on* the login form...
return shortcuts.redirect(exception.location) | python | 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
login_url = request.build_absolute_uri(auth_url)
response = redirect_to_login(next_url, login_url=login_url,
redirect_field_name=field_name)
if isinstance(exception, exceptions.NotAuthorized):
response.delete_cookie('messages')
return shortcuts.render(request, 'not_authorized.html',
status=403)
if request.is_ajax():
response_401 = http.HttpResponse(status=401)
response_401['X-Horizon-Location'] = response['location']
return response_401
return response
# If an internal "NotFound" error gets this far, return a real 404.
if isinstance(exception, exceptions.NotFound):
raise http.Http404(exception)
if isinstance(exception, exceptions.Http302):
# TODO(gabriel): Find a way to display an appropriate message to
# the user *on* the login form...
return shortcuts.redirect(exception.location) | [
"def",
"process_exception",
"(",
"self",
",",
"request",
",",
"exception",
")",
":",
"if",
"isinstance",
"(",
"exception",
",",
"(",
"exceptions",
".",
"NotAuthorized",
",",
"exceptions",
".",
"NotAuthenticated",
")",
")",
":",
"auth_url",
"=",
"settings",
"... | Catches internal Horizon exception classes.
Exception classes such as NotAuthorized, NotFound and Http302
are caught and handles them gracefully. | [
"Catches",
"internal",
"Horizon",
"exception",
"classes",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/middleware/base.py#L123-L159 |
234,915 | openstack/horizon | horizon/middleware/base.py | HorizonMiddleware._process_response | def _process_response(self, request, response):
"""Convert HttpResponseRedirect to HttpResponse if request is via ajax.
This is to allow ajax request to redirect url.
"""
if request.is_ajax() and hasattr(request, 'horizon'):
queued_msgs = request.horizon['async_messages']
if type(response) == http.HttpResponseRedirect:
# Drop our messages back into the session as per usual so they
# don't disappear during the redirect. Not that we explicitly
# use django's messages methods here.
for tag, message, extra_tags in queued_msgs:
getattr(django_messages, tag)(request, message, extra_tags)
if response['location'].startswith(settings.LOGOUT_URL):
redirect_response = http.HttpResponse(status=401)
# This header is used for handling the logout in JS
redirect_response['logout'] = True
if self.logout_reason is not None:
utils.add_logout_reason(
request, redirect_response, self.logout_reason,
'error')
else:
redirect_response = http.HttpResponse()
# Use a set while checking if we want a cookie's attributes
# copied
cookie_keys = {'max_age', 'expires', 'path', 'domain',
'secure', 'httponly', 'logout_reason'}
# Copy cookies from HttpResponseRedirect towards HttpResponse
for cookie_name, cookie in response.cookies.items():
cookie_kwargs = dict((
(key, value) for key, value in cookie.items()
if key in cookie_keys and value
))
redirect_response.set_cookie(
cookie_name, cookie.value, **cookie_kwargs)
redirect_response['X-Horizon-Location'] = response['location']
upload_url_key = 'X-File-Upload-URL'
if upload_url_key in response:
self._copy_headers(response, redirect_response,
(upload_url_key, 'X-Auth-Token'))
return redirect_response
if queued_msgs:
# TODO(gabriel): When we have an async connection to the
# client (e.g. websockets) this should be pushed to the
# socket queue rather than being sent via a header.
# The header method has notable drawbacks (length limits,
# etc.) and is not meant as a long-term solution.
response['X-Horizon-Messages'] = json.dumps(queued_msgs)
return response | python | 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:
# Drop our messages back into the session as per usual so they
# don't disappear during the redirect. Not that we explicitly
# use django's messages methods here.
for tag, message, extra_tags in queued_msgs:
getattr(django_messages, tag)(request, message, extra_tags)
if response['location'].startswith(settings.LOGOUT_URL):
redirect_response = http.HttpResponse(status=401)
# This header is used for handling the logout in JS
redirect_response['logout'] = True
if self.logout_reason is not None:
utils.add_logout_reason(
request, redirect_response, self.logout_reason,
'error')
else:
redirect_response = http.HttpResponse()
# Use a set while checking if we want a cookie's attributes
# copied
cookie_keys = {'max_age', 'expires', 'path', 'domain',
'secure', 'httponly', 'logout_reason'}
# Copy cookies from HttpResponseRedirect towards HttpResponse
for cookie_name, cookie in response.cookies.items():
cookie_kwargs = dict((
(key, value) for key, value in cookie.items()
if key in cookie_keys and value
))
redirect_response.set_cookie(
cookie_name, cookie.value, **cookie_kwargs)
redirect_response['X-Horizon-Location'] = response['location']
upload_url_key = 'X-File-Upload-URL'
if upload_url_key in response:
self._copy_headers(response, redirect_response,
(upload_url_key, 'X-Auth-Token'))
return redirect_response
if queued_msgs:
# TODO(gabriel): When we have an async connection to the
# client (e.g. websockets) this should be pushed to the
# socket queue rather than being sent via a header.
# The header method has notable drawbacks (length limits,
# etc.) and is not meant as a long-term solution.
response['X-Horizon-Messages'] = json.dumps(queued_msgs)
return response | [
"def",
"_process_response",
"(",
"self",
",",
"request",
",",
"response",
")",
":",
"if",
"request",
".",
"is_ajax",
"(",
")",
"and",
"hasattr",
"(",
"request",
",",
"'horizon'",
")",
":",
"queued_msgs",
"=",
"request",
".",
"horizon",
"[",
"'async_message... | Convert HttpResponseRedirect to HttpResponse if request is via ajax.
This is to allow ajax request to redirect url. | [
"Convert",
"HttpResponseRedirect",
"to",
"HttpResponse",
"if",
"request",
"is",
"via",
"ajax",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/middleware/base.py#L166-L214 |
234,916 | openstack/horizon | openstack_dashboard/utils/identity.py | get_domain_id_for_operation | def get_domain_id_for_operation(request):
"""Get the ID of the domain in which the current operation should happen.
If the user has a domain context set, use that, otherwise use the user's
effective domain.
"""
domain_context = request.session.get('domain_context')
if domain_context:
return domain_context
return api.keystone.get_effective_domain_id(request) | python | 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) | [
"def",
"get_domain_id_for_operation",
"(",
"request",
")",
":",
"domain_context",
"=",
"request",
".",
"session",
".",
"get",
"(",
"'domain_context'",
")",
"if",
"domain_context",
":",
"return",
"domain_context",
"return",
"api",
".",
"keystone",
".",
"get_effecti... | Get the ID of the domain in which the current operation should happen.
If the user has a domain context set, use that, otherwise use the user's
effective domain. | [
"Get",
"the",
"ID",
"of",
"the",
"domain",
"in",
"which",
"the",
"current",
"operation",
"should",
"happen",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/utils/identity.py#L18-L28 |
234,917 | openstack/horizon | openstack_dashboard/management/commands/migrate_settings.py | get_module_path | def get_module_path(module_name):
"""Gets the module path without importing anything.
Avoids conflicts with package dependencies.
(taken from http://github.com/sitkatech/pypatch)
"""
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] | python | 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] | [
"def",
"get_module_path",
"(",
"module_name",
")",
":",
"path",
"=",
"sys",
".",
"path",
"for",
"name",
"in",
"module_name",
".",
"split",
"(",
"'.'",
")",
":",
"file_pointer",
",",
"path",
",",
"desc",
"=",
"imp",
".",
"find_module",
"(",
"name",
",",... | Gets the module path without importing anything.
Avoids conflicts with package dependencies.
(taken from http://github.com/sitkatech/pypatch) | [
"Gets",
"the",
"module",
"path",
"without",
"importing",
"anything",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/management/commands/migrate_settings.py#L31-L44 |
234,918 | openstack/horizon | openstack_dashboard/management/commands/migrate_settings.py | Command.gendiff | def gendiff(self, force=False):
"""Generate a diff between self.local_settings and the example file.
"""
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:
local_settings_lines = fp.readlines()
local_settings_example_mtime = time.strftime(
self.time_fmt,
time.localtime(
os.stat(self.local_settings_example).st_mtime)
)
local_settings_mtime = time.strftime(
self.time_fmt,
time.localtime(os.stat(self.local_settings_file).st_mtime)
)
print('generating "%s"...' % os.path.join(
dircontext.curdir,
self.local_settings_diff)
)
with open(self.local_settings_diff, 'w') as fp:
for line in difflib.unified_diff(
example_lines, local_settings_lines,
fromfile=self.local_settings_example,
tofile=self.local_settings_file,
fromfiledate=local_settings_example_mtime,
tofiledate=local_settings_mtime
):
fp.write(line)
print('\tDONE.')
sys.exit(0)
else:
sys.exit(
'"%s" already exists.' %
os.path.join(dircontext.curdir,
self.local_settings_diff)
) | python | 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:
local_settings_lines = fp.readlines()
local_settings_example_mtime = time.strftime(
self.time_fmt,
time.localtime(
os.stat(self.local_settings_example).st_mtime)
)
local_settings_mtime = time.strftime(
self.time_fmt,
time.localtime(os.stat(self.local_settings_file).st_mtime)
)
print('generating "%s"...' % os.path.join(
dircontext.curdir,
self.local_settings_diff)
)
with open(self.local_settings_diff, 'w') as fp:
for line in difflib.unified_diff(
example_lines, local_settings_lines,
fromfile=self.local_settings_example,
tofile=self.local_settings_file,
fromfiledate=local_settings_example_mtime,
tofiledate=local_settings_mtime
):
fp.write(line)
print('\tDONE.')
sys.exit(0)
else:
sys.exit(
'"%s" already exists.' %
os.path.join(dircontext.curdir,
self.local_settings_diff)
) | [
"def",
"gendiff",
"(",
"self",
",",
"force",
"=",
"False",
")",
":",
"with",
"DirContext",
"(",
"self",
".",
"local_settings_dir",
")",
"as",
"dircontext",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"local_settings_diff",
")",
... | Generate a diff between self.local_settings and the example file. | [
"Generate",
"a",
"diff",
"between",
"self",
".",
"local_settings",
"and",
"the",
"example",
"file",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/management/commands/migrate_settings.py#L120-L162 |
234,919 | openstack/horizon | openstack_dashboard/management/commands/migrate_settings.py | Command.patch | def patch(self, force=False):
"""Patch local_settings.py.example with local_settings.diff.
The patch application generates the local_settings.py file (the
local_settings.py.example remains unchanged).
http://github.com/sitkatech/pypatch fails if the
local_settings.py.example file is not 100% identical to the one used to
generate the first diff so we use the patch command instead.
"""
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_time_fmt, time.localtime())
)
patch_cmd = shlex.split(
'patch %s %s -o %s -r %s' % (
self.local_settings_example,
self.local_settings_diff,
self.local_settings_file,
local_settings_reject
)
)
try:
subprocess.check_call(patch_cmd)
except subprocess.CalledProcessError:
if os.path.exists(local_settings_reject):
sys.exit(
'Some conflict(s) occurred. Please check "%s" '
'to find unapplied parts of the diff.\n'
'Once conflicts are solved, it is safer to '
'regenerate a newer diff with the "--gendiff" '
'option.' %
os.path.join(
dircontext.curdir,
local_settings_reject)
)
else:
sys.exit('An unhandled error occurred.')
print('Generation of "%s" successful.' % os.path.join(
dircontext.curdir,
self.local_settings_file)
)
sys.exit(0)
else:
sys.exit(
'"%s" already exists.' %
os.path.join(dircontext.curdir,
self.local_settings_file)
)
else:
sys.exit('No diff file found, please generate one with the '
'"--gendiff" option.') | python | 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_time_fmt, time.localtime())
)
patch_cmd = shlex.split(
'patch %s %s -o %s -r %s' % (
self.local_settings_example,
self.local_settings_diff,
self.local_settings_file,
local_settings_reject
)
)
try:
subprocess.check_call(patch_cmd)
except subprocess.CalledProcessError:
if os.path.exists(local_settings_reject):
sys.exit(
'Some conflict(s) occurred. Please check "%s" '
'to find unapplied parts of the diff.\n'
'Once conflicts are solved, it is safer to '
'regenerate a newer diff with the "--gendiff" '
'option.' %
os.path.join(
dircontext.curdir,
local_settings_reject)
)
else:
sys.exit('An unhandled error occurred.')
print('Generation of "%s" successful.' % os.path.join(
dircontext.curdir,
self.local_settings_file)
)
sys.exit(0)
else:
sys.exit(
'"%s" already exists.' %
os.path.join(dircontext.curdir,
self.local_settings_file)
)
else:
sys.exit('No diff file found, please generate one with the '
'"--gendiff" option.') | [
"def",
"patch",
"(",
"self",
",",
"force",
"=",
"False",
")",
":",
"with",
"DirContext",
"(",
"self",
".",
"local_settings_dir",
")",
"as",
"dircontext",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"local_settings_diff",
")",
":",
"i... | Patch local_settings.py.example with local_settings.diff.
The patch application generates the local_settings.py file (the
local_settings.py.example remains unchanged).
http://github.com/sitkatech/pypatch fails if the
local_settings.py.example file is not 100% identical to the one used to
generate the first diff so we use the patch command instead. | [
"Patch",
"local_settings",
".",
"py",
".",
"example",
"with",
"local_settings",
".",
"diff",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/management/commands/migrate_settings.py#L164-L220 |
234,920 | openstack/horizon | openstack_dashboard/policy.py | check | def check(actions, request, target=None):
"""Wrapper of the configurable policy method."""
policy_check = utils_settings.import_setting("POLICY_CHECK_FUNCTION")
if policy_check:
return policy_check(actions, request, target)
return True | python | 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 | [
"def",
"check",
"(",
"actions",
",",
"request",
",",
"target",
"=",
"None",
")",
":",
"policy_check",
"=",
"utils_settings",
".",
"import_setting",
"(",
"\"POLICY_CHECK_FUNCTION\"",
")",
"if",
"policy_check",
":",
"return",
"policy_check",
"(",
"actions",
",",
... | Wrapper of the configurable policy method. | [
"Wrapper",
"of",
"the",
"configurable",
"policy",
"method",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/policy.py#L18-L26 |
234,921 | openstack/horizon | openstack_dashboard/api/_nova.py | get_auth_params_from_request | def get_auth_params_from_request(request):
"""Extracts properties needed by novaclient call from the request object.
These will be used to memoize the calls to novaclient.
"""
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')
) | python | 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')
) | [
"def",
"get_auth_params_from_request",
"(",
"request",
")",
":",
"return",
"(",
"request",
".",
"user",
".",
"username",
",",
"request",
".",
"user",
".",
"token",
".",
"id",
",",
"request",
".",
"user",
".",
"tenant_id",
",",
"request",
".",
"user",
"."... | Extracts properties needed by novaclient call from the request object.
These will be used to memoize the calls to novaclient. | [
"Extracts",
"properties",
"needed",
"by",
"novaclient",
"call",
"from",
"the",
"request",
"object",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/_nova.py#L99-L111 |
234,922 | openstack/horizon | openstack_dashboard/dashboards/project/network_topology/utils.py | get_context | def get_context(request, context=None):
"""Returns common context data for network topology views."""
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'] = _quota_exceeded(request, 'instances')
context['create_network_allowed'] = policy.check(
(("network", "create_network"),), request)
context['network_quota_exceeded'] = _quota_exceeded(request, 'network')
context['create_router_allowed'] = (
network_config.get('enable_router', True) and
policy.check((("network", "create_router"),), request))
context['router_quota_exceeded'] = _quota_exceeded(request, 'router')
context['console_type'] = getattr(settings, 'CONSOLE_TYPE', 'AUTO')
context['show_ng_launch'] = (
base.is_service_enabled(request, 'compute') and
getattr(settings, 'LAUNCH_INSTANCE_NG_ENABLED', True))
context['show_legacy_launch'] = (
base.is_service_enabled(request, 'compute') and
getattr(settings, 'LAUNCH_INSTANCE_LEGACY_ENABLED', False))
return context | python | 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'] = _quota_exceeded(request, 'instances')
context['create_network_allowed'] = policy.check(
(("network", "create_network"),), request)
context['network_quota_exceeded'] = _quota_exceeded(request, 'network')
context['create_router_allowed'] = (
network_config.get('enable_router', True) and
policy.check((("network", "create_router"),), request))
context['router_quota_exceeded'] = _quota_exceeded(request, 'router')
context['console_type'] = getattr(settings, 'CONSOLE_TYPE', 'AUTO')
context['show_ng_launch'] = (
base.is_service_enabled(request, 'compute') and
getattr(settings, 'LAUNCH_INSTANCE_NG_ENABLED', True))
context['show_legacy_launch'] = (
base.is_service_enabled(request, 'compute') and
getattr(settings, 'LAUNCH_INSTANCE_LEGACY_ENABLED', False))
return context | [
"def",
"get_context",
"(",
"request",
",",
"context",
"=",
"None",
")",
":",
"if",
"context",
"is",
"None",
":",
"context",
"=",
"{",
"}",
"network_config",
"=",
"getattr",
"(",
"settings",
",",
"'OPENSTACK_NEUTRON_NETWORK'",
",",
"{",
"}",
")",
"context",... | Returns common context data for network topology views. | [
"Returns",
"common",
"context",
"data",
"for",
"network",
"topology",
"views",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/dashboards/project/network_topology/utils.py#L26-L50 |
234,923 | openstack/horizon | openstack_dashboard/dashboards/identity/users/role_assignments/tables.py | RoleAssignmentsTable.get_object_id | def get_object_id(self, datum):
"""Identifier of the role assignment."""
# Role assignment doesn't have identifier so one will be created
# from the identifier of scope, user and role. This will guaranty the
# unicity.
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, "group"):
assignee_id = datum.group["id"]
return "%s%s%s" % (assignee_id, datum.role["id"], scope_id) | python | def get_object_id(self, datum):
# Role assignment doesn't have identifier so one will be created
# from the identifier of scope, user and role. This will guaranty the
# unicity.
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, "group"):
assignee_id = datum.group["id"]
return "%s%s%s" % (assignee_id, datum.role["id"], scope_id) | [
"def",
"get_object_id",
"(",
"self",
",",
"datum",
")",
":",
"# Role assignment doesn't have identifier so one will be created",
"# from the identifier of scope, user and role. This will guaranty the",
"# unicity.",
"scope_id",
"=",
"\"\"",
"if",
"\"project\"",
"in",
"datum",
"."... | Identifier of the role assignment. | [
"Identifier",
"of",
"the",
"role",
"assignment",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/dashboards/identity/users/role_assignments/tables.py#L85-L103 |
234,924 | openstack/horizon | openstack_dashboard/api/base.py | get_url_for_service | 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(endpoint)]
"""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
"""
if service['type'] == 'identity' and not available_endpoints:
available_endpoints = [endpoint for endpoint in service_endpoints]
for endpoint in available_endpoints:
try:
if identity_version < 3:
return endpoint.get(endpoint_type)
else:
interface = \
ENDPOINT_TYPE_TO_INTERFACE.get(endpoint_type, '')
if endpoint.get('interface') == interface:
return endpoint.get('url')
except (IndexError, KeyError):
# it could be that the current endpoint just doesn't match the
# type, continue trying the next one
pass
return None | python | 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(endpoint)]
if service['type'] == 'identity' and not available_endpoints:
available_endpoints = [endpoint for endpoint in service_endpoints]
for endpoint in available_endpoints:
try:
if identity_version < 3:
return endpoint.get(endpoint_type)
else:
interface = \
ENDPOINT_TYPE_TO_INTERFACE.get(endpoint_type, '')
if endpoint.get('interface') == interface:
return endpoint.get('url')
except (IndexError, KeyError):
# it could be that the current endpoint just doesn't match the
# type, continue trying the next one
pass
return None | [
"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... | 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 | [
"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",
"an... | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/base.py#L295-L323 |
234,925 | openstack/horizon | horizon/utils/units.py | is_larger | def is_larger(unit_1, unit_2):
"""Returns a boolean indicating whether unit_1 is larger than unit_2.
E.g:
>>> is_larger('KB', 'B')
True
>>> is_larger('min', 'day')
False
"""
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) | python | 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) | [
"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"... | Returns a boolean indicating whether unit_1 is larger than unit_2.
E.g:
>>> is_larger('KB', 'B')
True
>>> is_larger('min', 'day')
False | [
"Returns",
"a",
"boolean",
"indicating",
"whether",
"unit_1",
"is",
"larger",
"than",
"unit_2",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/utils/units.py#L40-L53 |
234,926 | openstack/horizon | horizon/utils/units.py | convert | def convert(value, source_unit, target_unit, fmt=False):
"""Converts value from source_unit to target_unit.
Returns a tuple containing the converted value and target_unit.
Having fmt set to True causes the value to be formatted to 1 decimal digit
if it's a decimal or be formatted as integer if it's an integer.
E.g:
>>> convert(2, 'hr', 'min')
(120.0, 'min')
>>> convert(2, 'hr', 'min', fmt=True)
(120, 'min')
>>> convert(30, 'min', 'hr', fmt=True)
(0.5, 'hr')
"""
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_expression(target_unit))
value = functions.format_value(q.magnitude) if fmt else q.magnitude
return value, orig_target_unit | python | 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_expression(target_unit))
value = functions.format_value(q.magnitude) if fmt else q.magnitude
return value, orig_target_unit | [
"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_... | Converts value from source_unit to target_unit.
Returns a tuple containing the converted value and target_unit.
Having fmt set to True causes the value to be formatted to 1 decimal digit
if it's a decimal or be formatted as integer if it's an integer.
E.g:
>>> convert(2, 'hr', 'min')
(120.0, 'min')
>>> convert(2, 'hr', 'min', fmt=True)
(120, 'min')
>>> convert(30, 'min', 'hr', fmt=True)
(0.5, 'hr') | [
"Converts",
"value",
"from",
"source_unit",
"to",
"target_unit",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/utils/units.py#L56-L79 |
234,927 | openstack/horizon | horizon/utils/units.py | normalize | def normalize(value, unit):
"""Converts the value so that it belongs to some expected range.
Returns the new value and new unit.
E.g:
>>> normalize(1024, 'KB')
(1, 'MB')
>>> normalize(90, 'min')
(1.5, 'hr')
>>> normalize(1.0, 'object')
(1, 'object')
"""
if value < 0:
raise ValueError('Negative value: %s %s.' % (value, unit))
if unit in functions.get_keys(INFORMATION_UNITS):
return _normalize_information(value, unit)
elif unit in TIME_UNITS:
return _normalize_time(value, unit)
else:
# Unknown unit, just return it
return functions.format_value(value), unit | python | def normalize(value, unit):
if value < 0:
raise ValueError('Negative value: %s %s.' % (value, unit))
if unit in functions.get_keys(INFORMATION_UNITS):
return _normalize_information(value, unit)
elif unit in TIME_UNITS:
return _normalize_time(value, unit)
else:
# Unknown unit, just return it
return functions.format_value(value), unit | [
"def",
"normalize",
"(",
"value",
",",
"unit",
")",
":",
"if",
"value",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"'Negative value: %s %s.'",
"%",
"(",
"value",
",",
"unit",
")",
")",
"if",
"unit",
"in",
"functions",
".",
"get_keys",
"(",
"INFORMATION_U... | Converts the value so that it belongs to some expected range.
Returns the new value and new unit.
E.g:
>>> normalize(1024, 'KB')
(1, 'MB')
>>> normalize(90, 'min')
(1.5, 'hr')
>>> normalize(1.0, 'object')
(1, 'object') | [
"Converts",
"the",
"value",
"so",
"that",
"it",
"belongs",
"to",
"some",
"expected",
"range",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/utils/units.py#L82-L105 |
234,928 | openstack/horizon | openstack_dashboard/api/rest/utils.py | ajax | def ajax(authenticated=True, data_required=False,
json_encoder=json.JSONEncoder):
"""Decorator to allow the wrappered view to exist in an AJAX environment.
Provide a decorator to wrap a view method so that it may exist in an
entirely AJAX environment:
- data decoded from JSON as input and data coded as JSON as output
- result status is coded in the HTTP status code; any non-2xx response
data will be coded as a JSON string, otherwise the response type (always
JSON) is specific to the method called.
if authenticated is true then we'll make sure the current user is
authenticated.
If data_required is true then we'll assert that there is a JSON body
present.
The wrapped view method should return either:
- JSON serialisable data
- an object of the django http.HttpResponse subclass (one of JSONResponse
or CreatedResponse is suggested)
- nothing
Methods returning nothing (or None explicitly) will result in a 204 "NO
CONTENT" being returned to the caller.
"""
def decorator(function, authenticated=authenticated,
data_required=data_required):
@functools.wraps(function,
assigned=decorators.available_attrs(function))
def _wrapped(self, request, *args, **kw):
if authenticated and not request.user.is_authenticated:
return JSONResponse('not logged in', 401)
if not request.is_ajax():
return JSONResponse('request must be AJAX', 400)
# decode the JSON body if present
request.DATA = None
if request.body:
try:
request.DATA = jsonutils.loads(request.body)
except (TypeError, ValueError) as e:
return JSONResponse('malformed JSON request: %s' % e, 400)
if data_required:
if not request.DATA:
return JSONResponse('request requires JSON body', 400)
# invoke the wrapped function, handling exceptions sanely
try:
data = function(self, request, *args, **kw)
if isinstance(data, http.HttpResponse):
return data
elif data is None:
return JSONResponse('', status=204)
return JSONResponse(data, json_encoder=json_encoder)
except http_errors as e:
# exception was raised with a specific HTTP status
for attr in ['http_status', 'code', 'status_code']:
if hasattr(e, attr):
http_status = getattr(e, attr)
break
else:
LOG.exception('HTTP exception with no status/code')
return JSONResponse(str(e), 500)
return JSONResponse(str(e), http_status)
except Exception as e:
LOG.exception('error invoking apiclient')
return JSONResponse(str(e), 500)
return _wrapped
return decorator | python | def ajax(authenticated=True, data_required=False,
json_encoder=json.JSONEncoder):
def decorator(function, authenticated=authenticated,
data_required=data_required):
@functools.wraps(function,
assigned=decorators.available_attrs(function))
def _wrapped(self, request, *args, **kw):
if authenticated and not request.user.is_authenticated:
return JSONResponse('not logged in', 401)
if not request.is_ajax():
return JSONResponse('request must be AJAX', 400)
# decode the JSON body if present
request.DATA = None
if request.body:
try:
request.DATA = jsonutils.loads(request.body)
except (TypeError, ValueError) as e:
return JSONResponse('malformed JSON request: %s' % e, 400)
if data_required:
if not request.DATA:
return JSONResponse('request requires JSON body', 400)
# invoke the wrapped function, handling exceptions sanely
try:
data = function(self, request, *args, **kw)
if isinstance(data, http.HttpResponse):
return data
elif data is None:
return JSONResponse('', status=204)
return JSONResponse(data, json_encoder=json_encoder)
except http_errors as e:
# exception was raised with a specific HTTP status
for attr in ['http_status', 'code', 'status_code']:
if hasattr(e, attr):
http_status = getattr(e, attr)
break
else:
LOG.exception('HTTP exception with no status/code')
return JSONResponse(str(e), 500)
return JSONResponse(str(e), http_status)
except Exception as e:
LOG.exception('error invoking apiclient')
return JSONResponse(str(e), 500)
return _wrapped
return decorator | [
"def",
"ajax",
"(",
"authenticated",
"=",
"True",
",",
"data_required",
"=",
"False",
",",
"json_encoder",
"=",
"json",
".",
"JSONEncoder",
")",
":",
"def",
"decorator",
"(",
"function",
",",
"authenticated",
"=",
"authenticated",
",",
"data_required",
"=",
... | Decorator to allow the wrappered view to exist in an AJAX environment.
Provide a decorator to wrap a view method so that it may exist in an
entirely AJAX environment:
- data decoded from JSON as input and data coded as JSON as output
- result status is coded in the HTTP status code; any non-2xx response
data will be coded as a JSON string, otherwise the response type (always
JSON) is specific to the method called.
if authenticated is true then we'll make sure the current user is
authenticated.
If data_required is true then we'll assert that there is a JSON body
present.
The wrapped view method should return either:
- JSON serialisable data
- an object of the django http.HttpResponse subclass (one of JSONResponse
or CreatedResponse is suggested)
- nothing
Methods returning nothing (or None explicitly) will result in a 204 "NO
CONTENT" being returned to the caller. | [
"Decorator",
"to",
"allow",
"the",
"wrappered",
"view",
"to",
"exist",
"in",
"an",
"AJAX",
"environment",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/rest/utils.py#L76-L149 |
234,929 | openstack/horizon | openstack_dashboard/api/rest/utils.py | parse_filters_kwargs | def parse_filters_kwargs(request, client_keywords=None):
"""Extract REST filter parameters from the request GET args.
Client processes some keywords separately from filters and takes
them as separate inputs. This will ignore those keys to avoid
potential conflicts.
"""
filters = {}
kwargs = {}
client_keywords = client_keywords or {}
for param in request.GET:
param_value = PARAM_MAPPING.get(request.GET[param], request.GET[param])
if param in client_keywords:
kwargs[param] = param_value
else:
filters[param] = param_value
return filters, kwargs | python | def parse_filters_kwargs(request, client_keywords=None):
filters = {}
kwargs = {}
client_keywords = client_keywords or {}
for param in request.GET:
param_value = PARAM_MAPPING.get(request.GET[param], request.GET[param])
if param in client_keywords:
kwargs[param] = param_value
else:
filters[param] = param_value
return filters, kwargs | [
"def",
"parse_filters_kwargs",
"(",
"request",
",",
"client_keywords",
"=",
"None",
")",
":",
"filters",
"=",
"{",
"}",
"kwargs",
"=",
"{",
"}",
"client_keywords",
"=",
"client_keywords",
"or",
"{",
"}",
"for",
"param",
"in",
"request",
".",
"GET",
":",
... | Extract REST filter parameters from the request GET args.
Client processes some keywords separately from filters and takes
them as separate inputs. This will ignore those keys to avoid
potential conflicts. | [
"Extract",
"REST",
"filter",
"parameters",
"from",
"the",
"request",
"GET",
"args",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/rest/utils.py#L159-L175 |
234,930 | openstack/horizon | openstack_dashboard/api/rest/utils.py | post2data | def post2data(func):
"""Decorator to restore original form values along with their types.
The sole purpose of this decorator is to restore original form values
along with their types stored on client-side under key $$originalJSON.
This in turn prevents the loss of field types when they are passed with
header 'Content-Type: multipart/form-data', which is needed to pass a
binary blob as a part of POST request.
"""
def wrapper(self, request):
request.DATA = request.POST
if '$$originalJSON' in request.POST:
request.DATA = jsonutils.loads(request.POST['$$originalJSON'])
return func(self, request)
return wrapper | python | def post2data(func):
def wrapper(self, request):
request.DATA = request.POST
if '$$originalJSON' in request.POST:
request.DATA = jsonutils.loads(request.POST['$$originalJSON'])
return func(self, request)
return wrapper | [
"def",
"post2data",
"(",
"func",
")",
":",
"def",
"wrapper",
"(",
"self",
",",
"request",
")",
":",
"request",
".",
"DATA",
"=",
"request",
".",
"POST",
"if",
"'$$originalJSON'",
"in",
"request",
".",
"POST",
":",
"request",
".",
"DATA",
"=",
"jsonutil... | Decorator to restore original form values along with their types.
The sole purpose of this decorator is to restore original form values
along with their types stored on client-side under key $$originalJSON.
This in turn prevents the loss of field types when they are passed with
header 'Content-Type: multipart/form-data', which is needed to pass a
binary blob as a part of POST request. | [
"Decorator",
"to",
"restore",
"original",
"form",
"values",
"along",
"with",
"their",
"types",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/rest/utils.py#L178-L194 |
234,931 | openstack/horizon | horizon/workflows/views.py | WorkflowView.get_workflow | def get_workflow(self):
"""Returns the instantiated workflow class."""
extra_context = self.get_initial()
entry_point = self.request.GET.get("step", None)
workflow = self.workflow_class(self.request,
context_seed=extra_context,
entry_point=entry_point)
return workflow | python | def get_workflow(self):
extra_context = self.get_initial()
entry_point = self.request.GET.get("step", None)
workflow = self.workflow_class(self.request,
context_seed=extra_context,
entry_point=entry_point)
return workflow | [
"def",
"get_workflow",
"(",
"self",
")",
":",
"extra_context",
"=",
"self",
".",
"get_initial",
"(",
")",
"entry_point",
"=",
"self",
".",
"request",
".",
"GET",
".",
"get",
"(",
"\"step\"",
",",
"None",
")",
"workflow",
"=",
"self",
".",
"workflow_class... | Returns the instantiated workflow class. | [
"Returns",
"the",
"instantiated",
"workflow",
"class",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/workflows/views.py#L76-L83 |
234,932 | openstack/horizon | horizon/workflows/views.py | WorkflowView.get_context_data | def get_context_data(self, **kwargs):
"""Returns the template context, including the workflow class.
This method should be overridden in subclasses to provide additional
context data to the template.
"""
context = super(WorkflowView, self).get_context_data(**kwargs)
workflow = self.get_workflow()
workflow.verify_integrity()
context[self.context_object_name] = workflow
next = self.request.GET.get(workflow.redirect_param_name)
context['REDIRECT_URL'] = next
context['layout'] = self.get_layout()
# For consistency with Workflow class
context['modal'] = 'modal' in context['layout']
if ADD_TO_FIELD_HEADER in self.request.META:
context['add_to_field'] = self.request.META[ADD_TO_FIELD_HEADER]
return context | python | def get_context_data(self, **kwargs):
context = super(WorkflowView, self).get_context_data(**kwargs)
workflow = self.get_workflow()
workflow.verify_integrity()
context[self.context_object_name] = workflow
next = self.request.GET.get(workflow.redirect_param_name)
context['REDIRECT_URL'] = next
context['layout'] = self.get_layout()
# For consistency with Workflow class
context['modal'] = 'modal' in context['layout']
if ADD_TO_FIELD_HEADER in self.request.META:
context['add_to_field'] = self.request.META[ADD_TO_FIELD_HEADER]
return context | [
"def",
"get_context_data",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"context",
"=",
"super",
"(",
"WorkflowView",
",",
"self",
")",
".",
"get_context_data",
"(",
"*",
"*",
"kwargs",
")",
"workflow",
"=",
"self",
".",
"get_workflow",
"(",
")",
"w... | Returns the template context, including the workflow class.
This method should be overridden in subclasses to provide additional
context data to the template. | [
"Returns",
"the",
"template",
"context",
"including",
"the",
"workflow",
"class",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/workflows/views.py#L85-L103 |
234,933 | openstack/horizon | horizon/workflows/views.py | WorkflowView.get_layout | def get_layout(self):
"""Returns classes for the workflow element in template.
The returned classes are determied based on
the workflow characteristics.
"""
if self.request.is_ajax():
layout = ['modal', ]
else:
layout = ['static_page', ]
if self.workflow_class.wizard:
layout += ['wizard', ]
return layout | python | def get_layout(self):
if self.request.is_ajax():
layout = ['modal', ]
else:
layout = ['static_page', ]
if self.workflow_class.wizard:
layout += ['wizard', ]
return layout | [
"def",
"get_layout",
"(",
"self",
")",
":",
"if",
"self",
".",
"request",
".",
"is_ajax",
"(",
")",
":",
"layout",
"=",
"[",
"'modal'",
",",
"]",
"else",
":",
"layout",
"=",
"[",
"'static_page'",
",",
"]",
"if",
"self",
".",
"workflow_class",
".",
... | Returns classes for the workflow element in template.
The returned classes are determied based on
the workflow characteristics. | [
"Returns",
"classes",
"for",
"the",
"workflow",
"element",
"in",
"template",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/workflows/views.py#L105-L119 |
234,934 | openstack/horizon | horizon/workflows/views.py | WorkflowView.get_template_names | def get_template_names(self):
"""Returns the template name to use for this request."""
if self.request.is_ajax():
template = self.ajax_template_name
else:
template = self.template_name
return template | python | def get_template_names(self):
if self.request.is_ajax():
template = self.ajax_template_name
else:
template = self.template_name
return template | [
"def",
"get_template_names",
"(",
"self",
")",
":",
"if",
"self",
".",
"request",
".",
"is_ajax",
"(",
")",
":",
"template",
"=",
"self",
".",
"ajax_template_name",
"else",
":",
"template",
"=",
"self",
".",
"template_name",
"return",
"template"
] | Returns the template name to use for this request. | [
"Returns",
"the",
"template",
"name",
"to",
"use",
"for",
"this",
"request",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/workflows/views.py#L121-L127 |
234,935 | openstack/horizon | horizon/workflows/views.py | WorkflowView.get | def get(self, request, *args, **kwargs):
"""Handler for HTTP GET requests."""
try:
context = self.get_context_data(**kwargs)
except exceptions.NotAvailable:
exceptions.handle(request)
self.set_workflow_step_errors(context)
return self.render_to_response(context) | python | def get(self, request, *args, **kwargs):
try:
context = self.get_context_data(**kwargs)
except exceptions.NotAvailable:
exceptions.handle(request)
self.set_workflow_step_errors(context)
return self.render_to_response(context) | [
"def",
"get",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"context",
"=",
"self",
".",
"get_context_data",
"(",
"*",
"*",
"kwargs",
")",
"except",
"exceptions",
".",
"NotAvailable",
":",
"exceptions",
... | Handler for HTTP GET requests. | [
"Handler",
"for",
"HTTP",
"GET",
"requests",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/workflows/views.py#L144-L151 |
234,936 | openstack/horizon | horizon/workflows/views.py | WorkflowView.validate_steps | def validate_steps(self, request, workflow, start, end):
"""Validates the workflow steps from ``start`` to ``end``, inclusive.
Returns a dict describing the validation state of the workflow.
"""
errors = {}
for step in workflow.steps[start:end + 1]:
if not step.action.is_valid():
errors[step.slug] = dict(
(field, [six.text_type(error) for error in errors])
for (field, errors) in step.action.errors.items())
return {
'has_errors': bool(errors),
'workflow_slug': workflow.slug,
'errors': errors,
} | python | def validate_steps(self, request, workflow, start, end):
errors = {}
for step in workflow.steps[start:end + 1]:
if not step.action.is_valid():
errors[step.slug] = dict(
(field, [six.text_type(error) for error in errors])
for (field, errors) in step.action.errors.items())
return {
'has_errors': bool(errors),
'workflow_slug': workflow.slug,
'errors': errors,
} | [
"def",
"validate_steps",
"(",
"self",
",",
"request",
",",
"workflow",
",",
"start",
",",
"end",
")",
":",
"errors",
"=",
"{",
"}",
"for",
"step",
"in",
"workflow",
".",
"steps",
"[",
"start",
":",
"end",
"+",
"1",
"]",
":",
"if",
"not",
"step",
... | Validates the workflow steps from ``start`` to ``end``, inclusive.
Returns a dict describing the validation state of the workflow. | [
"Validates",
"the",
"workflow",
"steps",
"from",
"start",
"to",
"end",
"inclusive",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/workflows/views.py#L153-L168 |
234,937 | openstack/horizon | horizon/workflows/views.py | WorkflowView.post | def post(self, request, *args, **kwargs):
"""Handler for HTTP POST requests."""
context = self.get_context_data(**kwargs)
workflow = context[self.context_object_name]
try:
# Check for the VALIDATE_STEP* headers, if they are present
# and valid integers, return validation results as JSON,
# otherwise proceed normally.
validate_step_start = int(self.request.META.get(
'HTTP_X_HORIZON_VALIDATE_STEP_START', ''))
validate_step_end = int(self.request.META.get(
'HTTP_X_HORIZON_VALIDATE_STEP_END', ''))
except ValueError:
# No VALIDATE_STEP* headers, or invalid values. Just proceed
# with normal workflow handling for POSTs.
pass
else:
# There are valid VALIDATE_STEP* headers, so only do validation
# for the specified steps and return results.
data = self.validate_steps(request, workflow,
validate_step_start,
validate_step_end)
return http.HttpResponse(json.dumps(data),
content_type="application/json")
if not workflow.is_valid():
return self.render_to_response(context)
try:
success = workflow.finalize()
except forms.ValidationError:
return self.render_to_response(context)
except Exception:
success = False
exceptions.handle(request)
if success:
msg = workflow.format_status_message(workflow.success_message)
messages.success(request, msg)
else:
msg = workflow.format_status_message(workflow.failure_message)
messages.error(request, msg)
if "HTTP_X_HORIZON_ADD_TO_FIELD" in self.request.META:
field_id = self.request.META["HTTP_X_HORIZON_ADD_TO_FIELD"]
response = http.HttpResponse()
if workflow.object:
data = [self.get_object_id(workflow.object),
self.get_object_display(workflow.object)]
response.content = json.dumps(data)
response["X-Horizon-Add-To-Field"] = field_id
return response
next_url = self.request.POST.get(workflow.redirect_param_name)
return shortcuts.redirect(next_url or workflow.get_success_url()) | python | def post(self, request, *args, **kwargs):
context = self.get_context_data(**kwargs)
workflow = context[self.context_object_name]
try:
# Check for the VALIDATE_STEP* headers, if they are present
# and valid integers, return validation results as JSON,
# otherwise proceed normally.
validate_step_start = int(self.request.META.get(
'HTTP_X_HORIZON_VALIDATE_STEP_START', ''))
validate_step_end = int(self.request.META.get(
'HTTP_X_HORIZON_VALIDATE_STEP_END', ''))
except ValueError:
# No VALIDATE_STEP* headers, or invalid values. Just proceed
# with normal workflow handling for POSTs.
pass
else:
# There are valid VALIDATE_STEP* headers, so only do validation
# for the specified steps and return results.
data = self.validate_steps(request, workflow,
validate_step_start,
validate_step_end)
return http.HttpResponse(json.dumps(data),
content_type="application/json")
if not workflow.is_valid():
return self.render_to_response(context)
try:
success = workflow.finalize()
except forms.ValidationError:
return self.render_to_response(context)
except Exception:
success = False
exceptions.handle(request)
if success:
msg = workflow.format_status_message(workflow.success_message)
messages.success(request, msg)
else:
msg = workflow.format_status_message(workflow.failure_message)
messages.error(request, msg)
if "HTTP_X_HORIZON_ADD_TO_FIELD" in self.request.META:
field_id = self.request.META["HTTP_X_HORIZON_ADD_TO_FIELD"]
response = http.HttpResponse()
if workflow.object:
data = [self.get_object_id(workflow.object),
self.get_object_display(workflow.object)]
response.content = json.dumps(data)
response["X-Horizon-Add-To-Field"] = field_id
return response
next_url = self.request.POST.get(workflow.redirect_param_name)
return shortcuts.redirect(next_url or workflow.get_success_url()) | [
"def",
"post",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"context",
"=",
"self",
".",
"get_context_data",
"(",
"*",
"*",
"kwargs",
")",
"workflow",
"=",
"context",
"[",
"self",
".",
"context_object_name",
"]",
... | Handler for HTTP POST requests. | [
"Handler",
"for",
"HTTP",
"POST",
"requests",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/workflows/views.py#L170-L219 |
234,938 | openstack/horizon | horizon/templatetags/angular.py | update_angular_template_hash | def update_angular_template_hash(sender, **kwargs):
"""Listen for compress events.
If the angular templates have been re-compressed, also clear them
from the Django cache backend. This is important to allow
deployers to change a template file, re-compress, and not
accidentally serve the old Django cached version of that content
to clients.
"""
context = kwargs['context'] # context the compressor is working with
compressed = context['compressed'] # the compressed content
compressed_name = compressed['name'] # name of the compressed content
if compressed_name == 'angular_template_cache_preloads':
# The compressor has modified the angular template cache preloads
# which are cached in the 'default' Django cache. Fetch that cache.
cache = caches['default']
# generate the same key as used in _scripts.html when caching the
# preloads
theme = context['THEME'] # current theme being compressed
key = make_template_fragment_key(
"angular",
['template_cache_preloads', theme]
)
# if template preloads have been cached, clear them
if cache.get(key):
cache.delete(key) | python | def update_angular_template_hash(sender, **kwargs):
context = kwargs['context'] # context the compressor is working with
compressed = context['compressed'] # the compressed content
compressed_name = compressed['name'] # name of the compressed content
if compressed_name == 'angular_template_cache_preloads':
# The compressor has modified the angular template cache preloads
# which are cached in the 'default' Django cache. Fetch that cache.
cache = caches['default']
# generate the same key as used in _scripts.html when caching the
# preloads
theme = context['THEME'] # current theme being compressed
key = make_template_fragment_key(
"angular",
['template_cache_preloads', theme]
)
# if template preloads have been cached, clear them
if cache.get(key):
cache.delete(key) | [
"def",
"update_angular_template_hash",
"(",
"sender",
",",
"*",
"*",
"kwargs",
")",
":",
"context",
"=",
"kwargs",
"[",
"'context'",
"]",
"# context the compressor is working with",
"compressed",
"=",
"context",
"[",
"'compressed'",
"]",
"# the compressed content",
"c... | Listen for compress events.
If the angular templates have been re-compressed, also clear them
from the Django cache backend. This is important to allow
deployers to change a template file, re-compress, and not
accidentally serve the old Django cached version of that content
to clients. | [
"Listen",
"for",
"compress",
"events",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/templatetags/angular.py#L28-L55 |
234,939 | openstack/horizon | horizon/templatetags/angular.py | angular_templates | def angular_templates(context):
"""Generate a dictionary of template contents for all static HTML templates.
If the template has been overridden by a theme, load the
override contents instead of the original HTML file.
One use for this is to pre-populate the angular template cache.
Args:
context: the context of the current Django template
Returns: an object containing
angular_templates: dictionary of angular template contents
- key is the template's static path,
- value is a string of HTML template contents
"""
template_paths = context['HORIZON_CONFIG']['external_templates']
all_theme_static_files = context['HORIZON_CONFIG']['theme_static_files']
this_theme_static_files = all_theme_static_files[context['THEME']]
template_overrides = this_theme_static_files['template_overrides']
angular_templates = {}
for relative_path in template_paths:
template_static_path = context['STATIC_URL'] + relative_path
# If the current theme overrides this template, use the theme
# content instead of the original file content
if relative_path in template_overrides:
relative_path = template_overrides[relative_path]
result = []
for finder in finders.get_finders():
result.extend(finder.find(relative_path, True))
path = result[-1]
try:
if six.PY3:
with open(path, encoding='utf-8') as template_file:
angular_templates[template_static_path] = template_file.\
read()
else:
with open(path) as template_file:
angular_templates[template_static_path] = template_file.\
read()
except (OSError, IOError):
# Failed to read template, leave the template dictionary blank
# If the caller is using this dictionary to pre-populate a cache
# there will simply be no pre-loaded version for this template.
pass
templates = [(key, value) for key, value in angular_templates.items()]
templates.sort(key=lambda item: item[0])
return {
'angular_templates': templates
} | python | def angular_templates(context):
template_paths = context['HORIZON_CONFIG']['external_templates']
all_theme_static_files = context['HORIZON_CONFIG']['theme_static_files']
this_theme_static_files = all_theme_static_files[context['THEME']]
template_overrides = this_theme_static_files['template_overrides']
angular_templates = {}
for relative_path in template_paths:
template_static_path = context['STATIC_URL'] + relative_path
# If the current theme overrides this template, use the theme
# content instead of the original file content
if relative_path in template_overrides:
relative_path = template_overrides[relative_path]
result = []
for finder in finders.get_finders():
result.extend(finder.find(relative_path, True))
path = result[-1]
try:
if six.PY3:
with open(path, encoding='utf-8') as template_file:
angular_templates[template_static_path] = template_file.\
read()
else:
with open(path) as template_file:
angular_templates[template_static_path] = template_file.\
read()
except (OSError, IOError):
# Failed to read template, leave the template dictionary blank
# If the caller is using this dictionary to pre-populate a cache
# there will simply be no pre-loaded version for this template.
pass
templates = [(key, value) for key, value in angular_templates.items()]
templates.sort(key=lambda item: item[0])
return {
'angular_templates': templates
} | [
"def",
"angular_templates",
"(",
"context",
")",
":",
"template_paths",
"=",
"context",
"[",
"'HORIZON_CONFIG'",
"]",
"[",
"'external_templates'",
"]",
"all_theme_static_files",
"=",
"context",
"[",
"'HORIZON_CONFIG'",
"]",
"[",
"'theme_static_files'",
"]",
"this_them... | Generate a dictionary of template contents for all static HTML templates.
If the template has been overridden by a theme, load the
override contents instead of the original HTML file.
One use for this is to pre-populate the angular template cache.
Args:
context: the context of the current Django template
Returns: an object containing
angular_templates: dictionary of angular template contents
- key is the template's static path,
- value is a string of HTML template contents | [
"Generate",
"a",
"dictionary",
"of",
"template",
"contents",
"for",
"all",
"static",
"HTML",
"templates",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/templatetags/angular.py#L81-L135 |
234,940 | openstack/horizon | openstack_dashboard/api/microversions.py | get_microversion_for_features | def get_microversion_for_features(service, features, wrapper_class,
min_ver, max_ver):
"""Retrieves that highest known functional microversion for features"""
feature_versions = get_requested_versions(service, features)
if not feature_versions:
return None
for version in feature_versions:
microversion = wrapper_class(version)
if microversion.matches(min_ver, max_ver):
return microversion
return None | python | def get_microversion_for_features(service, features, wrapper_class,
min_ver, max_ver):
feature_versions = get_requested_versions(service, features)
if not feature_versions:
return None
for version in feature_versions:
microversion = wrapper_class(version)
if microversion.matches(min_ver, max_ver):
return microversion
return None | [
"def",
"get_microversion_for_features",
"(",
"service",
",",
"features",
",",
"wrapper_class",
",",
"min_ver",
",",
"max_ver",
")",
":",
"feature_versions",
"=",
"get_requested_versions",
"(",
"service",
",",
"features",
")",
"if",
"not",
"feature_versions",
":",
... | Retrieves that highest known functional microversion for features | [
"Retrieves",
"that",
"highest",
"known",
"functional",
"microversion",
"for",
"features"
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/microversions.py#L85-L96 |
234,941 | openstack/horizon | horizon/base.py | Registry._register | def _register(self, cls):
"""Registers the given class.
If the specified class is already registered then it is ignored.
"""
if not inspect.isclass(cls):
raise ValueError('Only classes may be registered.')
elif not issubclass(cls, self._registerable_class):
raise ValueError('Only %s classes or subclasses may be registered.'
% self._registerable_class.__name__)
if cls not in self._registry:
cls._registered_with = self
self._registry[cls] = cls()
return self._registry[cls] | python | def _register(self, cls):
if not inspect.isclass(cls):
raise ValueError('Only classes may be registered.')
elif not issubclass(cls, self._registerable_class):
raise ValueError('Only %s classes or subclasses may be registered.'
% self._registerable_class.__name__)
if cls not in self._registry:
cls._registered_with = self
self._registry[cls] = cls()
return self._registry[cls] | [
"def",
"_register",
"(",
"self",
",",
"cls",
")",
":",
"if",
"not",
"inspect",
".",
"isclass",
"(",
"cls",
")",
":",
"raise",
"ValueError",
"(",
"'Only classes may be registered.'",
")",
"elif",
"not",
"issubclass",
"(",
"cls",
",",
"self",
".",
"_register... | Registers the given class.
If the specified class is already registered then it is ignored. | [
"Registers",
"the",
"given",
"class",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/base.py#L185-L200 |
234,942 | openstack/horizon | horizon/base.py | Registry._unregister | def _unregister(self, cls):
"""Unregisters the given class.
If the specified class isn't registered, ``NotRegistered`` will
be raised.
"""
if not issubclass(cls, self._registerable_class):
raise ValueError('Only %s classes or subclasses may be '
'unregistered.' % self._registerable_class)
if cls not in self._registry:
raise NotRegistered('%s is not registered' % cls)
del self._registry[cls]
return True | python | def _unregister(self, cls):
if not issubclass(cls, self._registerable_class):
raise ValueError('Only %s classes or subclasses may be '
'unregistered.' % self._registerable_class)
if cls not in self._registry:
raise NotRegistered('%s is not registered' % cls)
del self._registry[cls]
return True | [
"def",
"_unregister",
"(",
"self",
",",
"cls",
")",
":",
"if",
"not",
"issubclass",
"(",
"cls",
",",
"self",
".",
"_registerable_class",
")",
":",
"raise",
"ValueError",
"(",
"'Only %s classes or subclasses may be '",
"'unregistered.'",
"%",
"self",
".",
"_regis... | Unregisters the given class.
If the specified class isn't registered, ``NotRegistered`` will
be raised. | [
"Unregisters",
"the",
"given",
"class",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/base.py#L202-L217 |
234,943 | openstack/horizon | horizon/base.py | Panel.get_absolute_url | def get_absolute_url(self):
"""Returns the default URL for this panel.
The default URL is defined as the URL pattern with ``name="index"`` in
the URLconf for this panel.
"""
try:
return reverse('horizon:%s:%s:%s' % (self._registered_with.slug,
self.slug,
self.index_url_name))
except Exception as exc:
# Logging here since this will often be called in a template
# where the exception would be hidden.
LOG.info("Error reversing absolute URL for %(self)s: %(exc)s",
{'self': self, 'exc': exc})
raise | python | def get_absolute_url(self):
try:
return reverse('horizon:%s:%s:%s' % (self._registered_with.slug,
self.slug,
self.index_url_name))
except Exception as exc:
# Logging here since this will often be called in a template
# where the exception would be hidden.
LOG.info("Error reversing absolute URL for %(self)s: %(exc)s",
{'self': self, 'exc': exc})
raise | [
"def",
"get_absolute_url",
"(",
"self",
")",
":",
"try",
":",
"return",
"reverse",
"(",
"'horizon:%s:%s:%s'",
"%",
"(",
"self",
".",
"_registered_with",
".",
"slug",
",",
"self",
".",
"slug",
",",
"self",
".",
"index_url_name",
")",
")",
"except",
"Excepti... | Returns the default URL for this panel.
The default URL is defined as the URL pattern with ``name="index"`` in
the URLconf for this panel. | [
"Returns",
"the",
"default",
"URL",
"for",
"this",
"panel",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/base.py#L312-L327 |
234,944 | openstack/horizon | horizon/base.py | Dashboard.get_panels | def get_panels(self):
"""Returns the Panel instances registered with this dashboard in order.
Panel grouping information is not included.
"""
all_panels = []
panel_groups = self.get_panel_groups()
for panel_group in panel_groups.values():
all_panels.extend(panel_group)
return all_panels | python | def get_panels(self):
all_panels = []
panel_groups = self.get_panel_groups()
for panel_group in panel_groups.values():
all_panels.extend(panel_group)
return all_panels | [
"def",
"get_panels",
"(",
"self",
")",
":",
"all_panels",
"=",
"[",
"]",
"panel_groups",
"=",
"self",
".",
"get_panel_groups",
"(",
")",
"for",
"panel_group",
"in",
"panel_groups",
".",
"values",
"(",
")",
":",
"all_panels",
".",
"extend",
"(",
"panel_grou... | Returns the Panel instances registered with this dashboard in order.
Panel grouping information is not included. | [
"Returns",
"the",
"Panel",
"instances",
"registered",
"with",
"this",
"dashboard",
"in",
"order",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/base.py#L492-L501 |
234,945 | openstack/horizon | horizon/base.py | Dashboard.get_absolute_url | def get_absolute_url(self):
"""Returns the default URL for this dashboard.
The default URL is defined as the URL pattern with ``name="index"``
in the URLconf for the :class:`~horizon.Panel` specified by
:attr:`~horizon.Dashboard.default_panel`.
"""
try:
return self._registered(self.default_panel).get_absolute_url()
except Exception:
# Logging here since this will often be called in a template
# where the exception would be hidden.
LOG.exception("Error reversing absolute URL for %s.", self)
raise | python | def get_absolute_url(self):
try:
return self._registered(self.default_panel).get_absolute_url()
except Exception:
# Logging here since this will often be called in a template
# where the exception would be hidden.
LOG.exception("Error reversing absolute URL for %s.", self)
raise | [
"def",
"get_absolute_url",
"(",
"self",
")",
":",
"try",
":",
"return",
"self",
".",
"_registered",
"(",
"self",
".",
"default_panel",
")",
".",
"get_absolute_url",
"(",
")",
"except",
"Exception",
":",
"# Logging here since this will often be called in a template",
... | Returns the default URL for this dashboard.
The default URL is defined as the URL pattern with ``name="index"``
in the URLconf for the :class:`~horizon.Panel` specified by
:attr:`~horizon.Dashboard.default_panel`. | [
"Returns",
"the",
"default",
"URL",
"for",
"this",
"dashboard",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/base.py#L531-L544 |
234,946 | openstack/horizon | horizon/base.py | Dashboard._autodiscover | def _autodiscover(self):
"""Discovers panels to register from the current dashboard module."""
if getattr(self, "_autodiscover_complete", False):
return
panels_to_discover = []
panel_groups = []
# If we have a flat iterable of panel names, wrap it again so
# we have a consistent structure for the next step.
if all([isinstance(i, six.string_types) for i in self.panels]):
self.panels = [self.panels]
# Now iterate our panel sets.
default_created = False
for panel_set in self.panels:
# Instantiate PanelGroup classes.
if not isinstance(panel_set, collections.Iterable) and \
issubclass(panel_set, PanelGroup):
panel_group = panel_set(self)
# Check for nested tuples, and convert them to PanelGroups
elif not isinstance(panel_set, PanelGroup):
panel_group = PanelGroup(self, panels=panel_set)
# Put our results into their appropriate places
panels_to_discover.extend(panel_group.panels)
panel_groups.append((panel_group.slug, panel_group))
if panel_group.slug == DEFAULT_PANEL_GROUP:
default_created = True
# Plugin panels can be added to a default panel group. Make sure such a
# default group exists.
if not default_created:
default_group = PanelGroup(self)
panel_groups.insert(0, (default_group.slug, default_group))
self._panel_groups = collections.OrderedDict(panel_groups)
# Do the actual discovery
package = '.'.join(self.__module__.split('.')[:-1])
mod = import_module(package)
for panel in panels_to_discover:
try:
before_import_registry = copy.copy(self._registry)
import_module('.%s.panel' % panel, package)
except Exception:
self._registry = before_import_registry
if module_has_submodule(mod, panel):
raise
self._autodiscover_complete = True | python | def _autodiscover(self):
if getattr(self, "_autodiscover_complete", False):
return
panels_to_discover = []
panel_groups = []
# If we have a flat iterable of panel names, wrap it again so
# we have a consistent structure for the next step.
if all([isinstance(i, six.string_types) for i in self.panels]):
self.panels = [self.panels]
# Now iterate our panel sets.
default_created = False
for panel_set in self.panels:
# Instantiate PanelGroup classes.
if not isinstance(panel_set, collections.Iterable) and \
issubclass(panel_set, PanelGroup):
panel_group = panel_set(self)
# Check for nested tuples, and convert them to PanelGroups
elif not isinstance(panel_set, PanelGroup):
panel_group = PanelGroup(self, panels=panel_set)
# Put our results into their appropriate places
panels_to_discover.extend(panel_group.panels)
panel_groups.append((panel_group.slug, panel_group))
if panel_group.slug == DEFAULT_PANEL_GROUP:
default_created = True
# Plugin panels can be added to a default panel group. Make sure such a
# default group exists.
if not default_created:
default_group = PanelGroup(self)
panel_groups.insert(0, (default_group.slug, default_group))
self._panel_groups = collections.OrderedDict(panel_groups)
# Do the actual discovery
package = '.'.join(self.__module__.split('.')[:-1])
mod = import_module(package)
for panel in panels_to_discover:
try:
before_import_registry = copy.copy(self._registry)
import_module('.%s.panel' % panel, package)
except Exception:
self._registry = before_import_registry
if module_has_submodule(mod, panel):
raise
self._autodiscover_complete = True | [
"def",
"_autodiscover",
"(",
"self",
")",
":",
"if",
"getattr",
"(",
"self",
",",
"\"_autodiscover_complete\"",
",",
"False",
")",
":",
"return",
"panels_to_discover",
"=",
"[",
"]",
"panel_groups",
"=",
"[",
"]",
"# If we have a flat iterable of panel names, wrap i... | Discovers panels to register from the current dashboard module. | [
"Discovers",
"panels",
"to",
"register",
"from",
"the",
"current",
"dashboard",
"module",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/base.py#L578-L625 |
234,947 | openstack/horizon | horizon/base.py | Dashboard.allowed | def allowed(self, context):
"""Checks for role based access for this dashboard.
Checks for access to any panels in the dashboard and of the
dashboard itself.
This method should be overridden to return the result of
any policy checks required for the user to access this dashboard
when more complex checks are required.
"""
# if the dashboard has policy rules, honor those above individual
# panels
if not self._can_access(context['request']):
return False
# check if access is allowed to a single panel,
# the default for each panel is True
for panel in self.get_panels():
if panel.can_access(context):
return True
return False | python | def allowed(self, context):
# if the dashboard has policy rules, honor those above individual
# panels
if not self._can_access(context['request']):
return False
# check if access is allowed to a single panel,
# the default for each panel is True
for panel in self.get_panels():
if panel.can_access(context):
return True
return False | [
"def",
"allowed",
"(",
"self",
",",
"context",
")",
":",
"# if the dashboard has policy rules, honor those above individual",
"# panels",
"if",
"not",
"self",
".",
"_can_access",
"(",
"context",
"[",
"'request'",
"]",
")",
":",
"return",
"False",
"# check if access is... | Checks for role based access for this dashboard.
Checks for access to any panels in the dashboard and of the
dashboard itself.
This method should be overridden to return the result of
any policy checks required for the user to access this dashboard
when more complex checks are required. | [
"Checks",
"for",
"role",
"based",
"access",
"for",
"this",
"dashboard",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/base.py#L651-L673 |
234,948 | openstack/horizon | horizon/base.py | Site.get_user_home | def get_user_home(self, user):
"""Returns the default URL for a particular user.
This method can be used to customize where a user is sent when
they log in, etc. By default it returns the value of
:meth:`get_absolute_url`.
An alternative function can be supplied to customize this behavior
by specifying a either a URL or a function which returns a URL via
the ``"user_home"`` key in ``HORIZON_CONFIG``. Each of these
would be valid::
{"user_home": "/home",} # A URL
{"user_home": "my_module.get_user_home",} # Path to a function
{"user_home": lambda user: "/" + user.name,} # A function
{"user_home": None,} # Will always return the default dashboard
This can be useful if the default dashboard may not be accessible
to all users. When user_home is missing from HORIZON_CONFIG,
it will default to the settings.LOGIN_REDIRECT_URL value.
"""
user_home = self._conf['user_home']
if user_home:
if callable(user_home):
return user_home(user)
elif isinstance(user_home, six.string_types):
# Assume we've got a URL if there's a slash in it
if '/' in user_home:
return user_home
else:
mod, func = user_home.rsplit(".", 1)
return getattr(import_module(mod), func)(user)
# If it's not callable and not a string, it's wrong.
raise ValueError('The user_home setting must be either a string '
'or a callable object (e.g. a function).')
else:
return self.get_absolute_url() | python | def get_user_home(self, user):
user_home = self._conf['user_home']
if user_home:
if callable(user_home):
return user_home(user)
elif isinstance(user_home, six.string_types):
# Assume we've got a URL if there's a slash in it
if '/' in user_home:
return user_home
else:
mod, func = user_home.rsplit(".", 1)
return getattr(import_module(mod), func)(user)
# If it's not callable and not a string, it's wrong.
raise ValueError('The user_home setting must be either a string '
'or a callable object (e.g. a function).')
else:
return self.get_absolute_url() | [
"def",
"get_user_home",
"(",
"self",
",",
"user",
")",
":",
"user_home",
"=",
"self",
".",
"_conf",
"[",
"'user_home'",
"]",
"if",
"user_home",
":",
"if",
"callable",
"(",
"user_home",
")",
":",
"return",
"user_home",
"(",
"user",
")",
"elif",
"isinstanc... | Returns the default URL for a particular user.
This method can be used to customize where a user is sent when
they log in, etc. By default it returns the value of
:meth:`get_absolute_url`.
An alternative function can be supplied to customize this behavior
by specifying a either a URL or a function which returns a URL via
the ``"user_home"`` key in ``HORIZON_CONFIG``. Each of these
would be valid::
{"user_home": "/home",} # A URL
{"user_home": "my_module.get_user_home",} # Path to a function
{"user_home": lambda user: "/" + user.name,} # A function
{"user_home": None,} # Will always return the default dashboard
This can be useful if the default dashboard may not be accessible
to all users. When user_home is missing from HORIZON_CONFIG,
it will default to the settings.LOGIN_REDIRECT_URL value. | [
"Returns",
"the",
"default",
"URL",
"for",
"a",
"particular",
"user",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/base.py#L793-L829 |
234,949 | openstack/horizon | horizon/base.py | Site._lazy_urls | def _lazy_urls(self):
"""Lazy loading for URL patterns.
This method avoids problems associated with attempting to evaluate
the URLconf before the settings module has been loaded.
"""
def url_patterns():
return self._urls()[0]
return LazyURLPattern(url_patterns), self.namespace, self.slug | python | def _lazy_urls(self):
def url_patterns():
return self._urls()[0]
return LazyURLPattern(url_patterns), self.namespace, self.slug | [
"def",
"_lazy_urls",
"(",
"self",
")",
":",
"def",
"url_patterns",
"(",
")",
":",
"return",
"self",
".",
"_urls",
"(",
")",
"[",
"0",
"]",
"return",
"LazyURLPattern",
"(",
"url_patterns",
")",
",",
"self",
".",
"namespace",
",",
"self",
".",
"slug"
] | Lazy loading for URL patterns.
This method avoids problems associated with attempting to evaluate
the URLconf before the settings module has been loaded. | [
"Lazy",
"loading",
"for",
"URL",
"patterns",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/base.py#L842-L851 |
234,950 | openstack/horizon | horizon/base.py | Site._urls | def _urls(self):
"""Constructs the URLconf for Horizon from registered Dashboards."""
urlpatterns = self._get_default_urlpatterns()
self._autodiscover()
# Discover each dashboard's panels.
for dash in self._registry.values():
dash._autodiscover()
# Load the plugin-based panel configuration
self._load_panel_customization()
# Allow for override modules
if self._conf.get("customization_module", None):
customization_module = self._conf["customization_module"]
bits = customization_module.split('.')
mod_name = bits.pop()
package = '.'.join(bits)
mod = import_module(package)
try:
before_import_registry = copy.copy(self._registry)
import_module('%s.%s' % (package, mod_name))
except Exception:
self._registry = before_import_registry
if module_has_submodule(mod, mod_name):
raise
# Compile the dynamic urlconf.
for dash in self._registry.values():
urlpatterns.append(url(r'^%s/' % dash.slug,
_wrapped_include(dash._decorated_urls)))
# Return the three arguments to django.conf.urls.include
return urlpatterns, self.namespace, self.slug | python | def _urls(self):
urlpatterns = self._get_default_urlpatterns()
self._autodiscover()
# Discover each dashboard's panels.
for dash in self._registry.values():
dash._autodiscover()
# Load the plugin-based panel configuration
self._load_panel_customization()
# Allow for override modules
if self._conf.get("customization_module", None):
customization_module = self._conf["customization_module"]
bits = customization_module.split('.')
mod_name = bits.pop()
package = '.'.join(bits)
mod = import_module(package)
try:
before_import_registry = copy.copy(self._registry)
import_module('%s.%s' % (package, mod_name))
except Exception:
self._registry = before_import_registry
if module_has_submodule(mod, mod_name):
raise
# Compile the dynamic urlconf.
for dash in self._registry.values():
urlpatterns.append(url(r'^%s/' % dash.slug,
_wrapped_include(dash._decorated_urls)))
# Return the three arguments to django.conf.urls.include
return urlpatterns, self.namespace, self.slug | [
"def",
"_urls",
"(",
"self",
")",
":",
"urlpatterns",
"=",
"self",
".",
"_get_default_urlpatterns",
"(",
")",
"self",
".",
"_autodiscover",
"(",
")",
"# Discover each dashboard's panels.",
"for",
"dash",
"in",
"self",
".",
"_registry",
".",
"values",
"(",
")",... | Constructs the URLconf for Horizon from registered Dashboards. | [
"Constructs",
"the",
"URLconf",
"for",
"Horizon",
"from",
"registered",
"Dashboards",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/base.py#L853-L886 |
234,951 | openstack/horizon | horizon/base.py | Site._autodiscover | def _autodiscover(self):
"""Discovers modules to register from ``settings.INSTALLED_APPS``.
This makes sure that the appropriate modules get imported to register
themselves with Horizon.
"""
if not getattr(self, '_registerable_class', None):
raise ImproperlyConfigured('You must set a '
'"_registerable_class" property '
'in order to use autodiscovery.')
# Discover both dashboards and panels, in that order
for mod_name in ('dashboard', 'panel'):
for app in settings.INSTALLED_APPS:
mod = import_module(app)
try:
before_import_registry = copy.copy(self._registry)
import_module('%s.%s' % (app, mod_name))
except Exception:
self._registry = before_import_registry
if module_has_submodule(mod, mod_name):
raise | python | def _autodiscover(self):
if not getattr(self, '_registerable_class', None):
raise ImproperlyConfigured('You must set a '
'"_registerable_class" property '
'in order to use autodiscovery.')
# Discover both dashboards and panels, in that order
for mod_name in ('dashboard', 'panel'):
for app in settings.INSTALLED_APPS:
mod = import_module(app)
try:
before_import_registry = copy.copy(self._registry)
import_module('%s.%s' % (app, mod_name))
except Exception:
self._registry = before_import_registry
if module_has_submodule(mod, mod_name):
raise | [
"def",
"_autodiscover",
"(",
"self",
")",
":",
"if",
"not",
"getattr",
"(",
"self",
",",
"'_registerable_class'",
",",
"None",
")",
":",
"raise",
"ImproperlyConfigured",
"(",
"'You must set a '",
"'\"_registerable_class\" property '",
"'in order to use autodiscovery.'",
... | Discovers modules to register from ``settings.INSTALLED_APPS``.
This makes sure that the appropriate modules get imported to register
themselves with Horizon. | [
"Discovers",
"modules",
"to",
"register",
"from",
"settings",
".",
"INSTALLED_APPS",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/base.py#L888-L908 |
234,952 | openstack/horizon | horizon/base.py | Site._load_panel_customization | def _load_panel_customization(self):
"""Applies the plugin-based panel configurations.
This method parses the panel customization from the ``HORIZON_CONFIG``
and make changes to the dashboard accordingly.
It supports adding, removing and setting default panels on the
dashboard. It also support registering a panel group.
"""
panel_customization = self._conf.get("panel_customization", [])
# Process all the panel groups first so that they exist before panels
# are added to them and Dashboard._autodiscover() doesn't wipe out any
# panels previously added when its panel groups are instantiated.
panel_configs = []
for config in panel_customization:
if config.get('PANEL'):
panel_configs.append(config)
elif config.get('PANEL_GROUP'):
self._process_panel_group_configuration(config)
else:
LOG.warning("Skipping %s because it doesn't have PANEL or "
"PANEL_GROUP defined.", config.__name__)
# Now process the panels.
for config in panel_configs:
self._process_panel_configuration(config) | python | def _load_panel_customization(self):
panel_customization = self._conf.get("panel_customization", [])
# Process all the panel groups first so that they exist before panels
# are added to them and Dashboard._autodiscover() doesn't wipe out any
# panels previously added when its panel groups are instantiated.
panel_configs = []
for config in panel_customization:
if config.get('PANEL'):
panel_configs.append(config)
elif config.get('PANEL_GROUP'):
self._process_panel_group_configuration(config)
else:
LOG.warning("Skipping %s because it doesn't have PANEL or "
"PANEL_GROUP defined.", config.__name__)
# Now process the panels.
for config in panel_configs:
self._process_panel_configuration(config) | [
"def",
"_load_panel_customization",
"(",
"self",
")",
":",
"panel_customization",
"=",
"self",
".",
"_conf",
".",
"get",
"(",
"\"panel_customization\"",
",",
"[",
"]",
")",
"# Process all the panel groups first so that they exist before panels",
"# are added to them and Dashb... | Applies the plugin-based panel configurations.
This method parses the panel customization from the ``HORIZON_CONFIG``
and make changes to the dashboard accordingly.
It supports adding, removing and setting default panels on the
dashboard. It also support registering a panel group. | [
"Applies",
"the",
"plugin",
"-",
"based",
"panel",
"configurations",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/base.py#L910-L935 |
234,953 | openstack/horizon | horizon/base.py | Site._process_panel_configuration | def _process_panel_configuration(self, config):
"""Add, remove and set default panels on the dashboard."""
try:
dashboard = config.get('PANEL_DASHBOARD')
if not dashboard:
LOG.warning("Skipping %s because it doesn't have "
"PANEL_DASHBOARD defined.", config.__name__)
return
panel_slug = config.get('PANEL')
dashboard_cls = self.get_dashboard(dashboard)
panel_group = config.get('PANEL_GROUP')
default_panel = config.get('DEFAULT_PANEL')
# Set the default panel
if default_panel:
dashboard_cls.default_panel = default_panel
# Remove the panel
if config.get('REMOVE_PANEL', False):
for panel in dashboard_cls.get_panels():
if panel_slug == panel.slug:
dashboard_cls.unregister(panel.__class__)
elif config.get('ADD_PANEL', None):
# Add the panel to the dashboard
panel_path = config['ADD_PANEL']
mod_path, panel_cls = panel_path.rsplit(".", 1)
try:
mod = import_module(mod_path)
except ImportError as e:
LOG.warning("Could not import panel module %(module)s: "
"%(exc)s", {'module': mod_path, 'exc': e})
return
panel = getattr(mod, panel_cls)
# test is can_register method is present and call method if
# it is to determine if the panel should be loaded
if hasattr(panel, 'can_register') and \
callable(getattr(panel, 'can_register')):
if not panel.can_register():
LOG.debug("Load condition failed for panel: %(panel)s",
{'panel': panel_slug})
return
dashboard_cls.register(panel)
if panel_group:
dashboard_cls.get_panel_group(panel_group).\
panels.append(panel.slug)
else:
panels = list(dashboard_cls.panels)
panels.append(panel)
dashboard_cls.panels = tuple(panels)
except Exception as e:
LOG.warning('Could not process panel %(panel)s: %(exc)s',
{'panel': panel_slug, 'exc': e}) | python | def _process_panel_configuration(self, config):
try:
dashboard = config.get('PANEL_DASHBOARD')
if not dashboard:
LOG.warning("Skipping %s because it doesn't have "
"PANEL_DASHBOARD defined.", config.__name__)
return
panel_slug = config.get('PANEL')
dashboard_cls = self.get_dashboard(dashboard)
panel_group = config.get('PANEL_GROUP')
default_panel = config.get('DEFAULT_PANEL')
# Set the default panel
if default_panel:
dashboard_cls.default_panel = default_panel
# Remove the panel
if config.get('REMOVE_PANEL', False):
for panel in dashboard_cls.get_panels():
if panel_slug == panel.slug:
dashboard_cls.unregister(panel.__class__)
elif config.get('ADD_PANEL', None):
# Add the panel to the dashboard
panel_path = config['ADD_PANEL']
mod_path, panel_cls = panel_path.rsplit(".", 1)
try:
mod = import_module(mod_path)
except ImportError as e:
LOG.warning("Could not import panel module %(module)s: "
"%(exc)s", {'module': mod_path, 'exc': e})
return
panel = getattr(mod, panel_cls)
# test is can_register method is present and call method if
# it is to determine if the panel should be loaded
if hasattr(panel, 'can_register') and \
callable(getattr(panel, 'can_register')):
if not panel.can_register():
LOG.debug("Load condition failed for panel: %(panel)s",
{'panel': panel_slug})
return
dashboard_cls.register(panel)
if panel_group:
dashboard_cls.get_panel_group(panel_group).\
panels.append(panel.slug)
else:
panels = list(dashboard_cls.panels)
panels.append(panel)
dashboard_cls.panels = tuple(panels)
except Exception as e:
LOG.warning('Could not process panel %(panel)s: %(exc)s',
{'panel': panel_slug, 'exc': e}) | [
"def",
"_process_panel_configuration",
"(",
"self",
",",
"config",
")",
":",
"try",
":",
"dashboard",
"=",
"config",
".",
"get",
"(",
"'PANEL_DASHBOARD'",
")",
"if",
"not",
"dashboard",
":",
"LOG",
".",
"warning",
"(",
"\"Skipping %s because it doesn't have \"",
... | Add, remove and set default panels on the dashboard. | [
"Add",
"remove",
"and",
"set",
"default",
"panels",
"on",
"the",
"dashboard",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/base.py#L937-L988 |
234,954 | openstack/horizon | horizon/base.py | Site._process_panel_group_configuration | def _process_panel_group_configuration(self, config):
"""Adds a panel group to the dashboard."""
panel_group_slug = config.get('PANEL_GROUP')
try:
dashboard = config.get('PANEL_GROUP_DASHBOARD')
if not dashboard:
LOG.warning("Skipping %s because it doesn't have "
"PANEL_GROUP_DASHBOARD defined.", config.__name__)
return
dashboard_cls = self.get_dashboard(dashboard)
panel_group_name = config.get('PANEL_GROUP_NAME')
if not panel_group_name:
LOG.warning("Skipping %s because it doesn't have "
"PANEL_GROUP_NAME defined.", config.__name__)
return
# Create the panel group class
panel_group = type(panel_group_slug,
(PanelGroup, ),
{'slug': panel_group_slug,
'name': panel_group_name,
'panels': []},)
# Add the panel group to dashboard
panels = list(dashboard_cls.panels)
panels.append(panel_group)
dashboard_cls.panels = tuple(panels)
# Trigger the autodiscovery to completely load the new panel group
dashboard_cls._autodiscover_complete = False
dashboard_cls._autodiscover()
except Exception as e:
LOG.warning('Could not process panel group %(panel_group)s: '
'%(exc)s',
{'panel_group': panel_group_slug, 'exc': e}) | python | def _process_panel_group_configuration(self, config):
panel_group_slug = config.get('PANEL_GROUP')
try:
dashboard = config.get('PANEL_GROUP_DASHBOARD')
if not dashboard:
LOG.warning("Skipping %s because it doesn't have "
"PANEL_GROUP_DASHBOARD defined.", config.__name__)
return
dashboard_cls = self.get_dashboard(dashboard)
panel_group_name = config.get('PANEL_GROUP_NAME')
if not panel_group_name:
LOG.warning("Skipping %s because it doesn't have "
"PANEL_GROUP_NAME defined.", config.__name__)
return
# Create the panel group class
panel_group = type(panel_group_slug,
(PanelGroup, ),
{'slug': panel_group_slug,
'name': panel_group_name,
'panels': []},)
# Add the panel group to dashboard
panels = list(dashboard_cls.panels)
panels.append(panel_group)
dashboard_cls.panels = tuple(panels)
# Trigger the autodiscovery to completely load the new panel group
dashboard_cls._autodiscover_complete = False
dashboard_cls._autodiscover()
except Exception as e:
LOG.warning('Could not process panel group %(panel_group)s: '
'%(exc)s',
{'panel_group': panel_group_slug, 'exc': e}) | [
"def",
"_process_panel_group_configuration",
"(",
"self",
",",
"config",
")",
":",
"panel_group_slug",
"=",
"config",
".",
"get",
"(",
"'PANEL_GROUP'",
")",
"try",
":",
"dashboard",
"=",
"config",
".",
"get",
"(",
"'PANEL_GROUP_DASHBOARD'",
")",
"if",
"not",
"... | Adds a panel group to the dashboard. | [
"Adds",
"a",
"panel",
"group",
"to",
"the",
"dashboard",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/base.py#L990-L1022 |
234,955 | openstack/horizon | horizon/tables/base.py | Row.load_cells | def load_cells(self, datum=None):
"""Load the row's data and initialize all the cells in the row.
It also set the appropriate row properties which require
the row's data to be determined.
The row's data is provided either at initialization or as an
argument to this function.
This function is called automatically by
:meth:`~horizon.tables.Row.__init__` if the ``datum`` argument is
provided. However, by not providing the data during initialization
this function allows for the possibility of a two-step loading
pattern when you need a row instance but don't yet have the data
available.
"""
# Compile all the cells on instantiation.
table = self.table
if datum:
self.datum = datum
else:
datum = self.datum
cells = []
for column in table.columns.values():
cell = table._meta.cell_class(datum, column, self)
cells.append((column.name or column.auto, cell))
self.cells = collections.OrderedDict(cells)
if self.ajax:
interval = conf.HORIZON_CONFIG['ajax_poll_interval']
self.attrs['data-update-interval'] = interval
self.attrs['data-update-url'] = self.get_ajax_update_url()
self.classes.append("ajax-update")
self.attrs['data-object-id'] = table.get_object_id(datum)
# Add the row's status class and id to the attributes to be rendered.
self.classes.append(self.status_class)
id_vals = {"table": self.table.name,
"sep": STRING_SEPARATOR,
"id": table.get_object_id(datum)}
self.id = "%(table)s%(sep)srow%(sep)s%(id)s" % id_vals
self.attrs['id'] = self.id
# Add the row's display name if available
display_name = table.get_object_display(datum)
display_name_key = table.get_object_display_key(datum)
if display_name:
self.attrs['data-display'] = escape(display_name)
self.attrs['data-display-key'] = escape(display_name_key) | python | def load_cells(self, datum=None):
# Compile all the cells on instantiation.
table = self.table
if datum:
self.datum = datum
else:
datum = self.datum
cells = []
for column in table.columns.values():
cell = table._meta.cell_class(datum, column, self)
cells.append((column.name or column.auto, cell))
self.cells = collections.OrderedDict(cells)
if self.ajax:
interval = conf.HORIZON_CONFIG['ajax_poll_interval']
self.attrs['data-update-interval'] = interval
self.attrs['data-update-url'] = self.get_ajax_update_url()
self.classes.append("ajax-update")
self.attrs['data-object-id'] = table.get_object_id(datum)
# Add the row's status class and id to the attributes to be rendered.
self.classes.append(self.status_class)
id_vals = {"table": self.table.name,
"sep": STRING_SEPARATOR,
"id": table.get_object_id(datum)}
self.id = "%(table)s%(sep)srow%(sep)s%(id)s" % id_vals
self.attrs['id'] = self.id
# Add the row's display name if available
display_name = table.get_object_display(datum)
display_name_key = table.get_object_display_key(datum)
if display_name:
self.attrs['data-display'] = escape(display_name)
self.attrs['data-display-key'] = escape(display_name_key) | [
"def",
"load_cells",
"(",
"self",
",",
"datum",
"=",
"None",
")",
":",
"# Compile all the cells on instantiation.",
"table",
"=",
"self",
".",
"table",
"if",
"datum",
":",
"self",
".",
"datum",
"=",
"datum",
"else",
":",
"datum",
"=",
"self",
".",
"datum",... | Load the row's data and initialize all the cells in the row.
It also set the appropriate row properties which require
the row's data to be determined.
The row's data is provided either at initialization or as an
argument to this function.
This function is called automatically by
:meth:`~horizon.tables.Row.__init__` if the ``datum`` argument is
provided. However, by not providing the data during initialization
this function allows for the possibility of a two-step loading
pattern when you need a row instance but don't yet have the data
available. | [
"Load",
"the",
"row",
"s",
"data",
"and",
"initialize",
"all",
"the",
"cells",
"in",
"the",
"row",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/tables/base.py#L595-L645 |
234,956 | openstack/horizon | horizon/tables/base.py | Cell.get_data | def get_data(self, datum, column, row):
"""Fetches the data to be displayed in this cell."""
table = row.table
if column.auto == "multi_select":
data = ""
if row.can_be_selected(datum):
widget = ThemableCheckboxInput(check_test=lambda value: False)
# Convert value to string to avoid accidental type conversion
data = widget.render('object_ids',
six.text_type(table.get_object_id(datum)),
{'class': 'table-row-multi-select'})
table._data_cache[column][table.get_object_id(datum)] = data
elif column.auto == "form_field":
widget = column.form_field
if issubclass(widget.__class__, forms.Field):
widget = widget.widget
widget_name = "%s__%s" % \
(column.name,
six.text_type(table.get_object_id(datum)))
# Create local copy of attributes, so it don't change column
# class form_field_attributes
form_field_attributes = {}
form_field_attributes.update(column.form_field_attributes)
# Adding id of the input so it pairs with label correctly
form_field_attributes['id'] = widget_name
if (template.defaultfilters.urlize in column.filters or
template.defaultfilters.yesno in column.filters):
data = widget.render(widget_name,
column.get_raw_data(datum),
form_field_attributes)
else:
data = widget.render(widget_name,
column.get_data(datum),
form_field_attributes)
table._data_cache[column][table.get_object_id(datum)] = data
elif column.auto == "actions":
data = table.render_row_actions(datum)
table._data_cache[column][table.get_object_id(datum)] = data
else:
data = column.get_data(datum)
if column.cell_attributes_getter:
cell_attributes = column.cell_attributes_getter(data) or {}
self.attrs.update(cell_attributes)
return data | python | def get_data(self, datum, column, row):
table = row.table
if column.auto == "multi_select":
data = ""
if row.can_be_selected(datum):
widget = ThemableCheckboxInput(check_test=lambda value: False)
# Convert value to string to avoid accidental type conversion
data = widget.render('object_ids',
six.text_type(table.get_object_id(datum)),
{'class': 'table-row-multi-select'})
table._data_cache[column][table.get_object_id(datum)] = data
elif column.auto == "form_field":
widget = column.form_field
if issubclass(widget.__class__, forms.Field):
widget = widget.widget
widget_name = "%s__%s" % \
(column.name,
six.text_type(table.get_object_id(datum)))
# Create local copy of attributes, so it don't change column
# class form_field_attributes
form_field_attributes = {}
form_field_attributes.update(column.form_field_attributes)
# Adding id of the input so it pairs with label correctly
form_field_attributes['id'] = widget_name
if (template.defaultfilters.urlize in column.filters or
template.defaultfilters.yesno in column.filters):
data = widget.render(widget_name,
column.get_raw_data(datum),
form_field_attributes)
else:
data = widget.render(widget_name,
column.get_data(datum),
form_field_attributes)
table._data_cache[column][table.get_object_id(datum)] = data
elif column.auto == "actions":
data = table.render_row_actions(datum)
table._data_cache[column][table.get_object_id(datum)] = data
else:
data = column.get_data(datum)
if column.cell_attributes_getter:
cell_attributes = column.cell_attributes_getter(data) or {}
self.attrs.update(cell_attributes)
return data | [
"def",
"get_data",
"(",
"self",
",",
"datum",
",",
"column",
",",
"row",
")",
":",
"table",
"=",
"row",
".",
"table",
"if",
"column",
".",
"auto",
"==",
"\"multi_select\"",
":",
"data",
"=",
"\"\"",
"if",
"row",
".",
"can_be_selected",
"(",
"datum",
... | Fetches the data to be displayed in this cell. | [
"Fetches",
"the",
"data",
"to",
"be",
"displayed",
"in",
"this",
"cell",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/tables/base.py#L743-L789 |
234,957 | openstack/horizon | horizon/tables/base.py | Cell.value | def value(self):
"""Returns a formatted version of the data for final output.
This takes into consideration the
:attr:`~horizon.tables.Column.link`` and
:attr:`~horizon.tables.Column.empty_value`
attributes.
"""
try:
data = self.column.get_data(self.datum)
if data is None:
if callable(self.column.empty_value):
data = self.column.empty_value(self.datum)
else:
data = self.column.empty_value
except Exception:
data = None
exc_info = sys.exc_info()
raise six.reraise(template.TemplateSyntaxError, exc_info[1],
exc_info[2])
if self.url and not self.column.auto == "form_field":
link_attrs = ' '.join(['%s="%s"' % (k, v) for (k, v) in
self.column.link_attrs.items()])
# Escape the data inside while allowing our HTML to render
data = mark_safe('<a href="%s" %s>%s</a>' % (
(escape(self.url),
link_attrs,
escape(six.text_type(data)))))
return data | python | def value(self):
try:
data = self.column.get_data(self.datum)
if data is None:
if callable(self.column.empty_value):
data = self.column.empty_value(self.datum)
else:
data = self.column.empty_value
except Exception:
data = None
exc_info = sys.exc_info()
raise six.reraise(template.TemplateSyntaxError, exc_info[1],
exc_info[2])
if self.url and not self.column.auto == "form_field":
link_attrs = ' '.join(['%s="%s"' % (k, v) for (k, v) in
self.column.link_attrs.items()])
# Escape the data inside while allowing our HTML to render
data = mark_safe('<a href="%s" %s>%s</a>' % (
(escape(self.url),
link_attrs,
escape(six.text_type(data)))))
return data | [
"def",
"value",
"(",
"self",
")",
":",
"try",
":",
"data",
"=",
"self",
".",
"column",
".",
"get_data",
"(",
"self",
".",
"datum",
")",
"if",
"data",
"is",
"None",
":",
"if",
"callable",
"(",
"self",
".",
"column",
".",
"empty_value",
")",
":",
"... | Returns a formatted version of the data for final output.
This takes into consideration the
:attr:`~horizon.tables.Column.link`` and
:attr:`~horizon.tables.Column.empty_value`
attributes. | [
"Returns",
"a",
"formatted",
"version",
"of",
"the",
"data",
"for",
"final",
"output",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/tables/base.py#L802-L831 |
234,958 | openstack/horizon | horizon/tables/base.py | Cell.status | def status(self):
"""Gets the status for the column based on the cell's data."""
# Deal with status column mechanics based in this cell's data
if hasattr(self, '_status'):
# pylint: disable=access-member-before-definition
return self._status
if self.column.status or \
self.column.name in self.column.table._meta.status_columns:
# returns the first matching status found
data_status_lower = six.text_type(
self.column.get_raw_data(self.datum)).lower()
for status_name, status_value in self.column.status_choices:
if six.text_type(status_name).lower() == data_status_lower:
self._status = status_value
return self._status
self._status = None
return self._status | python | def status(self):
# Deal with status column mechanics based in this cell's data
if hasattr(self, '_status'):
# pylint: disable=access-member-before-definition
return self._status
if self.column.status or \
self.column.name in self.column.table._meta.status_columns:
# returns the first matching status found
data_status_lower = six.text_type(
self.column.get_raw_data(self.datum)).lower()
for status_name, status_value in self.column.status_choices:
if six.text_type(status_name).lower() == data_status_lower:
self._status = status_value
return self._status
self._status = None
return self._status | [
"def",
"status",
"(",
"self",
")",
":",
"# Deal with status column mechanics based in this cell's data",
"if",
"hasattr",
"(",
"self",
",",
"'_status'",
")",
":",
"# pylint: disable=access-member-before-definition",
"return",
"self",
".",
"_status",
"if",
"self",
".",
"... | Gets the status for the column based on the cell's data. | [
"Gets",
"the",
"status",
"for",
"the",
"column",
"based",
"on",
"the",
"cell",
"s",
"data",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/tables/base.py#L843-L860 |
234,959 | openstack/horizon | horizon/tables/base.py | Cell.get_default_classes | def get_default_classes(self):
"""Returns a flattened string of the cell's CSS classes."""
if not self.url:
self.column.classes = [cls for cls in self.column.classes
if cls != "anchor"]
column_class_string = self.column.get_final_attrs().get('class', "")
classes = set(column_class_string.split(" "))
if self.column.status:
classes.add(self.get_status_class(self.status))
if self.inline_edit_available:
classes.add("inline_edit_available")
return list(classes) | python | def get_default_classes(self):
if not self.url:
self.column.classes = [cls for cls in self.column.classes
if cls != "anchor"]
column_class_string = self.column.get_final_attrs().get('class', "")
classes = set(column_class_string.split(" "))
if self.column.status:
classes.add(self.get_status_class(self.status))
if self.inline_edit_available:
classes.add("inline_edit_available")
return list(classes) | [
"def",
"get_default_classes",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"url",
":",
"self",
".",
"column",
".",
"classes",
"=",
"[",
"cls",
"for",
"cls",
"in",
"self",
".",
"column",
".",
"classes",
"if",
"cls",
"!=",
"\"anchor\"",
"]",
"colum... | Returns a flattened string of the cell's CSS classes. | [
"Returns",
"a",
"flattened",
"string",
"of",
"the",
"cell",
"s",
"CSS",
"classes",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/tables/base.py#L871-L884 |
234,960 | openstack/horizon | horizon/tables/base.py | Cell.update_allowed | def update_allowed(self):
"""Determines whether update of given cell is allowed.
Calls allowed action of defined UpdateAction of the Column.
"""
return self.update_action.allowed(self.column.table.request,
self.datum,
self) | python | def update_allowed(self):
return self.update_action.allowed(self.column.table.request,
self.datum,
self) | [
"def",
"update_allowed",
"(",
"self",
")",
":",
"return",
"self",
".",
"update_action",
".",
"allowed",
"(",
"self",
".",
"column",
".",
"table",
".",
"request",
",",
"self",
".",
"datum",
",",
"self",
")"
] | Determines whether update of given cell is allowed.
Calls allowed action of defined UpdateAction of the Column. | [
"Determines",
"whether",
"update",
"of",
"given",
"cell",
"is",
"allowed",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/tables/base.py#L899-L906 |
234,961 | openstack/horizon | openstack_dashboard/dashboards/project/instances/console.py | get_console | def get_console(request, console_type, instance):
"""Get a tuple of console url and console type."""
if console_type == 'AUTO':
check_consoles = CONSOLES
else:
try:
check_consoles = {console_type: CONSOLES[console_type]}
except KeyError:
msg = _('Console type "%s" not supported.') % console_type
raise exceptions.NotAvailable(msg)
# Ugly workaround due novaclient API change from 2.17 to 2.18.
try:
httpnotimplemented = nova_exception.HttpNotImplemented
except AttributeError:
httpnotimplemented = nova_exception.HTTPNotImplemented
for con_type, api_call in check_consoles.items():
try:
console = api_call(request, instance.id)
# If not supported, don't log it to avoid lot of errors in case
# of AUTO.
except httpnotimplemented:
continue
except Exception:
LOG.debug('Console not available', exc_info=True)
continue
if con_type == 'SERIAL':
console_url = console.url
else:
console_url = "%s&%s(%s)" % (
console.url,
urlencode({'title': getattr(instance, "name", "")}),
instance.id)
return (con_type, console_url)
raise exceptions.NotAvailable(_('No available console found.')) | python | def get_console(request, console_type, instance):
if console_type == 'AUTO':
check_consoles = CONSOLES
else:
try:
check_consoles = {console_type: CONSOLES[console_type]}
except KeyError:
msg = _('Console type "%s" not supported.') % console_type
raise exceptions.NotAvailable(msg)
# Ugly workaround due novaclient API change from 2.17 to 2.18.
try:
httpnotimplemented = nova_exception.HttpNotImplemented
except AttributeError:
httpnotimplemented = nova_exception.HTTPNotImplemented
for con_type, api_call in check_consoles.items():
try:
console = api_call(request, instance.id)
# If not supported, don't log it to avoid lot of errors in case
# of AUTO.
except httpnotimplemented:
continue
except Exception:
LOG.debug('Console not available', exc_info=True)
continue
if con_type == 'SERIAL':
console_url = console.url
else:
console_url = "%s&%s(%s)" % (
console.url,
urlencode({'title': getattr(instance, "name", "")}),
instance.id)
return (con_type, console_url)
raise exceptions.NotAvailable(_('No available console found.')) | [
"def",
"get_console",
"(",
"request",
",",
"console_type",
",",
"instance",
")",
":",
"if",
"console_type",
"==",
"'AUTO'",
":",
"check_consoles",
"=",
"CONSOLES",
"else",
":",
"try",
":",
"check_consoles",
"=",
"{",
"console_type",
":",
"CONSOLES",
"[",
"co... | Get a tuple of console url and console type. | [
"Get",
"a",
"tuple",
"of",
"console",
"url",
"and",
"console",
"type",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/dashboards/project/instances/console.py#L34-L72 |
234,962 | openstack/horizon | openstack_dashboard/dashboards/admin/flavors/tables.py | FlavorFilterAction.filter | def filter(self, table, flavors, filter_string):
"""Really naive case-insensitive search."""
q = filter_string.lower()
def comp(flavor):
return q in flavor.name.lower()
return filter(comp, flavors) | python | def filter(self, table, flavors, filter_string):
q = filter_string.lower()
def comp(flavor):
return q in flavor.name.lower()
return filter(comp, flavors) | [
"def",
"filter",
"(",
"self",
",",
"table",
",",
"flavors",
",",
"filter_string",
")",
":",
"q",
"=",
"filter_string",
".",
"lower",
"(",
")",
"def",
"comp",
"(",
"flavor",
")",
":",
"return",
"q",
"in",
"flavor",
".",
"name",
".",
"lower",
"(",
")... | Really naive case-insensitive search. | [
"Really",
"naive",
"case",
"-",
"insensitive",
"search",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/dashboards/admin/flavors/tables.py#L104-L111 |
234,963 | openstack/horizon | horizon/middleware/operation_log.py | OperationLogMiddleware._process_response | def _process_response(self, request, response):
"""Log user operation."""
log_format = self._get_log_format(request)
if not log_format:
return response
params = self._get_parameters_from_request(request)
# log a message displayed to user
messages = django_messages.get_messages(request)
result_message = None
if messages:
result_message = ', '.join('%s: %s' % (message.tags, message)
for message in messages)
elif 'action' in request.POST:
result_message = request.POST['action']
params['message'] = result_message
params['http_status'] = response.status_code
self.OPERATION_LOG.info(log_format, params)
return response | python | def _process_response(self, request, response):
log_format = self._get_log_format(request)
if not log_format:
return response
params = self._get_parameters_from_request(request)
# log a message displayed to user
messages = django_messages.get_messages(request)
result_message = None
if messages:
result_message = ', '.join('%s: %s' % (message.tags, message)
for message in messages)
elif 'action' in request.POST:
result_message = request.POST['action']
params['message'] = result_message
params['http_status'] = response.status_code
self.OPERATION_LOG.info(log_format, params)
return response | [
"def",
"_process_response",
"(",
"self",
",",
"request",
",",
"response",
")",
":",
"log_format",
"=",
"self",
".",
"_get_log_format",
"(",
"request",
")",
"if",
"not",
"log_format",
":",
"return",
"response",
"params",
"=",
"self",
".",
"_get_parameters_from_... | Log user operation. | [
"Log",
"user",
"operation",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/middleware/operation_log.py#L87-L107 |
234,964 | openstack/horizon | horizon/middleware/operation_log.py | OperationLogMiddleware.process_exception | def process_exception(self, request, exception):
"""Log error info when exception occurred."""
log_format = self._get_log_format(request)
if log_format is None:
return
params = self._get_parameters_from_request(request, True)
params['message'] = exception
params['http_status'] = '-'
self.OPERATION_LOG.info(log_format, params) | python | def process_exception(self, request, exception):
log_format = self._get_log_format(request)
if log_format is None:
return
params = self._get_parameters_from_request(request, True)
params['message'] = exception
params['http_status'] = '-'
self.OPERATION_LOG.info(log_format, params) | [
"def",
"process_exception",
"(",
"self",
",",
"request",
",",
"exception",
")",
":",
"log_format",
"=",
"self",
".",
"_get_log_format",
"(",
"request",
")",
"if",
"log_format",
"is",
"None",
":",
"return",
"params",
"=",
"self",
".",
"_get_parameters_from_requ... | Log error info when exception occurred. | [
"Log",
"error",
"info",
"when",
"exception",
"occurred",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/middleware/operation_log.py#L109-L119 |
234,965 | openstack/horizon | horizon/middleware/operation_log.py | OperationLogMiddleware._get_log_format | def _get_log_format(self, request):
"""Return operation log format."""
user = getattr(request, 'user', None)
if not user:
return
if not request.user.is_authenticated:
return
method = request.method.upper()
if not (method in self.target_methods):
return
request_url = urlparse.unquote(request.path)
for rule in self._ignored_urls:
if rule.search(request_url):
return
return self.format | python | def _get_log_format(self, request):
user = getattr(request, 'user', None)
if not user:
return
if not request.user.is_authenticated:
return
method = request.method.upper()
if not (method in self.target_methods):
return
request_url = urlparse.unquote(request.path)
for rule in self._ignored_urls:
if rule.search(request_url):
return
return self.format | [
"def",
"_get_log_format",
"(",
"self",
",",
"request",
")",
":",
"user",
"=",
"getattr",
"(",
"request",
",",
"'user'",
",",
"None",
")",
"if",
"not",
"user",
":",
"return",
"if",
"not",
"request",
".",
"user",
".",
"is_authenticated",
":",
"return",
"... | Return operation log format. | [
"Return",
"operation",
"log",
"format",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/middleware/operation_log.py#L121-L135 |
234,966 | openstack/horizon | horizon/middleware/operation_log.py | OperationLogMiddleware._get_parameters_from_request | def _get_parameters_from_request(self, request, exception=False):
"""Get parameters to log in OPERATION_LOG."""
user = request.user
referer_url = None
try:
referer_dic = urlparse.urlsplit(
urlparse.unquote(request.META.get('HTTP_REFERER')))
referer_url = referer_dic[2]
if referer_dic[3]:
referer_url += "?" + referer_dic[3]
if isinstance(referer_url, str):
referer_url = referer_url.decode('utf-8')
except Exception:
pass
request_url = urlparse.unquote(request.path)
if request.META['QUERY_STRING']:
request_url += '?' + request.META['QUERY_STRING']
return {
'client_ip': request.META.get('REMOTE_ADDR', None),
'domain_name': getattr(user, 'domain_name', None),
'domain_id': getattr(user, 'domain_id', None),
'project_name': getattr(user, 'project_name', None),
'project_id': getattr(user, 'project_id', None),
'user_name': getattr(user, 'username', None),
'user_id': request.session.get('user_id', None),
'request_scheme': request.scheme,
'referer_url': referer_url,
'request_url': request_url,
'method': request.method if not exception else None,
'param': self._get_request_param(request),
} | python | def _get_parameters_from_request(self, request, exception=False):
user = request.user
referer_url = None
try:
referer_dic = urlparse.urlsplit(
urlparse.unquote(request.META.get('HTTP_REFERER')))
referer_url = referer_dic[2]
if referer_dic[3]:
referer_url += "?" + referer_dic[3]
if isinstance(referer_url, str):
referer_url = referer_url.decode('utf-8')
except Exception:
pass
request_url = urlparse.unquote(request.path)
if request.META['QUERY_STRING']:
request_url += '?' + request.META['QUERY_STRING']
return {
'client_ip': request.META.get('REMOTE_ADDR', None),
'domain_name': getattr(user, 'domain_name', None),
'domain_id': getattr(user, 'domain_id', None),
'project_name': getattr(user, 'project_name', None),
'project_id': getattr(user, 'project_id', None),
'user_name': getattr(user, 'username', None),
'user_id': request.session.get('user_id', None),
'request_scheme': request.scheme,
'referer_url': referer_url,
'request_url': request_url,
'method': request.method if not exception else None,
'param': self._get_request_param(request),
} | [
"def",
"_get_parameters_from_request",
"(",
"self",
",",
"request",
",",
"exception",
"=",
"False",
")",
":",
"user",
"=",
"request",
".",
"user",
"referer_url",
"=",
"None",
"try",
":",
"referer_dic",
"=",
"urlparse",
".",
"urlsplit",
"(",
"urlparse",
".",
... | Get parameters to log in OPERATION_LOG. | [
"Get",
"parameters",
"to",
"log",
"in",
"OPERATION_LOG",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/middleware/operation_log.py#L137-L167 |
234,967 | openstack/horizon | horizon/middleware/operation_log.py | OperationLogMiddleware._get_request_param | def _get_request_param(self, request):
"""Change POST data to JSON string and mask data."""
params = {}
try:
params = request.POST.copy()
if not params:
params = json.loads(request.body)
except Exception:
pass
for key in params:
# replace a value to a masked characters
if key in self.mask_fields:
params[key] = '*' * 8
# when a file uploaded (E.g create image)
files = request.FILES.values()
if list(files):
filenames = ', '.join(
[up_file.name for up_file in files])
params['file_name'] = filenames
try:
return json.dumps(params, ensure_ascii=False)
except Exception:
return 'Unserializable Object' | python | def _get_request_param(self, request):
params = {}
try:
params = request.POST.copy()
if not params:
params = json.loads(request.body)
except Exception:
pass
for key in params:
# replace a value to a masked characters
if key in self.mask_fields:
params[key] = '*' * 8
# when a file uploaded (E.g create image)
files = request.FILES.values()
if list(files):
filenames = ', '.join(
[up_file.name for up_file in files])
params['file_name'] = filenames
try:
return json.dumps(params, ensure_ascii=False)
except Exception:
return 'Unserializable Object' | [
"def",
"_get_request_param",
"(",
"self",
",",
"request",
")",
":",
"params",
"=",
"{",
"}",
"try",
":",
"params",
"=",
"request",
".",
"POST",
".",
"copy",
"(",
")",
"if",
"not",
"params",
":",
"params",
"=",
"json",
".",
"loads",
"(",
"request",
... | Change POST data to JSON string and mask data. | [
"Change",
"POST",
"data",
"to",
"JSON",
"string",
"and",
"mask",
"data",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/middleware/operation_log.py#L169-L193 |
234,968 | openstack/horizon | openstack_dashboard/dashboards/identity/projects/workflows.py | UpdateProject._update_project | def _update_project(self, request, data):
"""Update project info"""
domain_id = identity.get_domain_id_for_operation(request)
try:
project_id = data['project_id']
# add extra information
if keystone.VERSIONS.active >= 3:
EXTRA_INFO = getattr(settings, 'PROJECT_TABLE_EXTRA_INFO', {})
kwargs = dict((key, data.get(key)) for key in EXTRA_INFO)
else:
kwargs = {}
return api.keystone.tenant_update(
request,
project_id,
name=data['name'],
description=data['description'],
enabled=data['enabled'],
domain=domain_id,
**kwargs)
except exceptions.Conflict:
msg = _('Project name "%s" is already used.') % data['name']
self.failure_message = msg
return
except Exception as e:
LOG.debug('Project update failed: %s', e)
exceptions.handle(request, ignore=True)
return | python | def _update_project(self, request, data):
domain_id = identity.get_domain_id_for_operation(request)
try:
project_id = data['project_id']
# add extra information
if keystone.VERSIONS.active >= 3:
EXTRA_INFO = getattr(settings, 'PROJECT_TABLE_EXTRA_INFO', {})
kwargs = dict((key, data.get(key)) for key in EXTRA_INFO)
else:
kwargs = {}
return api.keystone.tenant_update(
request,
project_id,
name=data['name'],
description=data['description'],
enabled=data['enabled'],
domain=domain_id,
**kwargs)
except exceptions.Conflict:
msg = _('Project name "%s" is already used.') % data['name']
self.failure_message = msg
return
except Exception as e:
LOG.debug('Project update failed: %s', e)
exceptions.handle(request, ignore=True)
return | [
"def",
"_update_project",
"(",
"self",
",",
"request",
",",
"data",
")",
":",
"domain_id",
"=",
"identity",
".",
"get_domain_id_for_operation",
"(",
"request",
")",
"try",
":",
"project_id",
"=",
"data",
"[",
"'project_id'",
"]",
"# add extra information",
"if",... | Update project info | [
"Update",
"project",
"info"
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/dashboards/identity/projects/workflows.py#L683-L711 |
234,969 | openstack/horizon | horizon/tables/formset.py | FormsetDataTableMixin.get_required_columns | def get_required_columns(self):
"""Lists names of columns that have required fields."""
required_columns = []
if self.formset_class:
empty_form = self.get_formset().empty_form
for column in self.columns.values():
field = empty_form.fields.get(column.name)
if field and field.required:
required_columns.append(column.name)
return required_columns | python | def get_required_columns(self):
required_columns = []
if self.formset_class:
empty_form = self.get_formset().empty_form
for column in self.columns.values():
field = empty_form.fields.get(column.name)
if field and field.required:
required_columns.append(column.name)
return required_columns | [
"def",
"get_required_columns",
"(",
"self",
")",
":",
"required_columns",
"=",
"[",
"]",
"if",
"self",
".",
"formset_class",
":",
"empty_form",
"=",
"self",
".",
"get_formset",
"(",
")",
".",
"empty_form",
"for",
"column",
"in",
"self",
".",
"columns",
"."... | Lists names of columns that have required fields. | [
"Lists",
"names",
"of",
"columns",
"that",
"have",
"required",
"fields",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/tables/formset.py#L87-L96 |
234,970 | openstack/horizon | horizon/tables/formset.py | FormsetDataTableMixin._get_formset_data | def _get_formset_data(self):
"""Formats the self.filtered_data in a way suitable for a formset."""
data = []
for datum in self.filtered_data:
form_data = {}
for column in self.columns.values():
value = column.get_data(datum)
form_data[column.name] = value
form_data['id'] = self.get_object_id(datum)
data.append(form_data)
return data | python | def _get_formset_data(self):
data = []
for datum in self.filtered_data:
form_data = {}
for column in self.columns.values():
value = column.get_data(datum)
form_data[column.name] = value
form_data['id'] = self.get_object_id(datum)
data.append(form_data)
return data | [
"def",
"_get_formset_data",
"(",
"self",
")",
":",
"data",
"=",
"[",
"]",
"for",
"datum",
"in",
"self",
".",
"filtered_data",
":",
"form_data",
"=",
"{",
"}",
"for",
"column",
"in",
"self",
".",
"columns",
".",
"values",
"(",
")",
":",
"value",
"=",
... | Formats the self.filtered_data in a way suitable for a formset. | [
"Formats",
"the",
"self",
".",
"filtered_data",
"in",
"a",
"way",
"suitable",
"for",
"a",
"formset",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/tables/formset.py#L98-L108 |
234,971 | openstack/horizon | horizon/tables/formset.py | FormsetDataTableMixin.get_rows | def get_rows(self):
"""Return the row data for this table broken out by columns.
The row objects get an additional ``form`` parameter, with the
formset form corresponding to that row.
"""
try:
rows = []
if self.formset_class is None:
formset = []
else:
formset = self.get_formset()
formset.is_valid()
for datum, form in six.moves.zip_longest(self.filtered_data,
formset):
row = self._meta.row_class(self, datum, form)
if self.get_object_id(datum) == self.current_item_id:
self.selected = True
row.classes.append('current_selected')
rows.append(row)
except Exception:
# Exceptions can be swallowed at the template level here,
# re-raising as a TemplateSyntaxError makes them visible.
LOG.exception("Error while rendering table rows.")
exc_info = sys.exc_info()
raise six.reraise(template.TemplateSyntaxError, exc_info[1],
exc_info[2])
return rows | python | def get_rows(self):
try:
rows = []
if self.formset_class is None:
formset = []
else:
formset = self.get_formset()
formset.is_valid()
for datum, form in six.moves.zip_longest(self.filtered_data,
formset):
row = self._meta.row_class(self, datum, form)
if self.get_object_id(datum) == self.current_item_id:
self.selected = True
row.classes.append('current_selected')
rows.append(row)
except Exception:
# Exceptions can be swallowed at the template level here,
# re-raising as a TemplateSyntaxError makes them visible.
LOG.exception("Error while rendering table rows.")
exc_info = sys.exc_info()
raise six.reraise(template.TemplateSyntaxError, exc_info[1],
exc_info[2])
return rows | [
"def",
"get_rows",
"(",
"self",
")",
":",
"try",
":",
"rows",
"=",
"[",
"]",
"if",
"self",
".",
"formset_class",
"is",
"None",
":",
"formset",
"=",
"[",
"]",
"else",
":",
"formset",
"=",
"self",
".",
"get_formset",
"(",
")",
"formset",
".",
"is_val... | Return the row data for this table broken out by columns.
The row objects get an additional ``form`` parameter, with the
formset form corresponding to that row. | [
"Return",
"the",
"row",
"data",
"for",
"this",
"table",
"broken",
"out",
"by",
"columns",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/tables/formset.py#L126-L153 |
234,972 | openstack/horizon | openstack_dashboard/api/keystone.py | keystoneclient | def keystoneclient(request, admin=False):
"""Returns a client connected to the Keystone backend.
Several forms of authentication are supported:
* Username + password -> Unscoped authentication
* Username + password + tenant id -> Scoped authentication
* Unscoped token -> Unscoped authentication
* Unscoped token + tenant id -> Scoped authentication
* Scoped token -> Scoped authentication
Available services and data from the backend will vary depending on
whether the authentication was scoped or unscoped.
Lazy authentication if an ``endpoint`` parameter is provided.
Calls requiring the admin endpoint should have ``admin=True`` passed in
as a keyword argument.
The client is cached so that subsequent API calls during the same
request/response cycle don't have to be re-authenticated.
"""
client_version = VERSIONS.get_active_version()
user = request.user
token_id = user.token.id
if is_multi_domain_enabled():
# Cloud Admin, Domain Admin or Mixed Domain Admin
if is_domain_admin(request):
domain_token = request.session.get('domain_token')
if domain_token:
token_id = getattr(domain_token, 'auth_token', None)
if admin:
if not policy.check((("identity", "admin_required"),), request):
raise exceptions.NotAuthorized
endpoint_type = 'adminURL'
else:
endpoint_type = getattr(settings,
'OPENSTACK_ENDPOINT_TYPE',
'publicURL')
# Take care of client connection caching/fetching a new client.
# Admin vs. non-admin clients are cached separately for token matching.
cache_attr = "_keystoneclient_admin" if admin \
else backend.KEYSTONE_CLIENT_ATTR
if (hasattr(request, cache_attr) and
(not user.token.id or
getattr(request, cache_attr).auth_token == user.token.id)):
conn = getattr(request, cache_attr)
else:
endpoint = _get_endpoint_url(request, endpoint_type)
verify = not getattr(settings, 'OPENSTACK_SSL_NO_VERIFY', False)
cacert = getattr(settings, 'OPENSTACK_SSL_CACERT', None)
verify = verify and cacert
LOG.debug("Creating a new keystoneclient connection to %s.", endpoint)
remote_addr = request.environ.get('REMOTE_ADDR', '')
token_auth = token_endpoint.Token(endpoint=endpoint,
token=token_id)
keystone_session = session.Session(auth=token_auth,
original_ip=remote_addr,
verify=verify)
conn = client_version['client'].Client(session=keystone_session,
debug=settings.DEBUG)
setattr(request, cache_attr, conn)
return conn | python | def keystoneclient(request, admin=False):
client_version = VERSIONS.get_active_version()
user = request.user
token_id = user.token.id
if is_multi_domain_enabled():
# Cloud Admin, Domain Admin or Mixed Domain Admin
if is_domain_admin(request):
domain_token = request.session.get('domain_token')
if domain_token:
token_id = getattr(domain_token, 'auth_token', None)
if admin:
if not policy.check((("identity", "admin_required"),), request):
raise exceptions.NotAuthorized
endpoint_type = 'adminURL'
else:
endpoint_type = getattr(settings,
'OPENSTACK_ENDPOINT_TYPE',
'publicURL')
# Take care of client connection caching/fetching a new client.
# Admin vs. non-admin clients are cached separately for token matching.
cache_attr = "_keystoneclient_admin" if admin \
else backend.KEYSTONE_CLIENT_ATTR
if (hasattr(request, cache_attr) and
(not user.token.id or
getattr(request, cache_attr).auth_token == user.token.id)):
conn = getattr(request, cache_attr)
else:
endpoint = _get_endpoint_url(request, endpoint_type)
verify = not getattr(settings, 'OPENSTACK_SSL_NO_VERIFY', False)
cacert = getattr(settings, 'OPENSTACK_SSL_CACERT', None)
verify = verify and cacert
LOG.debug("Creating a new keystoneclient connection to %s.", endpoint)
remote_addr = request.environ.get('REMOTE_ADDR', '')
token_auth = token_endpoint.Token(endpoint=endpoint,
token=token_id)
keystone_session = session.Session(auth=token_auth,
original_ip=remote_addr,
verify=verify)
conn = client_version['client'].Client(session=keystone_session,
debug=settings.DEBUG)
setattr(request, cache_attr, conn)
return conn | [
"def",
"keystoneclient",
"(",
"request",
",",
"admin",
"=",
"False",
")",
":",
"client_version",
"=",
"VERSIONS",
".",
"get_active_version",
"(",
")",
"user",
"=",
"request",
".",
"user",
"token_id",
"=",
"user",
".",
"token",
".",
"id",
"if",
"is_multi_do... | Returns a client connected to the Keystone backend.
Several forms of authentication are supported:
* Username + password -> Unscoped authentication
* Username + password + tenant id -> Scoped authentication
* Unscoped token -> Unscoped authentication
* Unscoped token + tenant id -> Scoped authentication
* Scoped token -> Scoped authentication
Available services and data from the backend will vary depending on
whether the authentication was scoped or unscoped.
Lazy authentication if an ``endpoint`` parameter is provided.
Calls requiring the admin endpoint should have ``admin=True`` passed in
as a keyword argument.
The client is cached so that subsequent API calls during the same
request/response cycle don't have to be re-authenticated. | [
"Returns",
"a",
"client",
"connected",
"to",
"the",
"Keystone",
"backend",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/keystone.py#L141-L206 |
234,973 | openstack/horizon | openstack_dashboard/api/keystone.py | get_default_domain | def get_default_domain(request, get_name=True):
"""Gets the default domain object to use when creating Identity object.
Returns the domain context if is set, otherwise return the domain
of the logon user.
:param get_name: Whether to get the domain name from Keystone if the
context isn't set. Setting this to False prevents an unnecessary call
to Keystone if only the domain ID is needed.
"""
domain_id = request.session.get("domain_context", None)
domain_name = request.session.get("domain_context_name", None)
# if running in Keystone V3 or later
if VERSIONS.active >= 3 and domain_id is None:
# if no domain context set, default to user's domain
domain_id = request.user.user_domain_id
domain_name = request.user.user_domain_name
if get_name and not request.user.is_federated:
try:
domain = domain_get(request, domain_id)
domain_name = domain.name
except exceptions.NotAuthorized:
# NOTE (knasim-wrs): Retrieving domain information
# is an admin URL operation. As a pre-check, such
# operations would be Forbidden if the logon user does
# not have an 'admin' role on the current project.
#
# Since this can be a common occurence and can cause
# incessant warning logging in the horizon logs,
# we recognize this condition and return the user's
# domain information instead.
LOG.debug("Cannot retrieve domain information for "
"user (%(user)s) that does not have an admin role "
"on project (%(project)s)",
{'user': request.user.username,
'project': request.user.project_name})
except Exception:
LOG.warning("Unable to retrieve Domain: %s", domain_id)
domain = base.APIDictWrapper({"id": domain_id,
"name": domain_name})
return domain | python | def get_default_domain(request, get_name=True):
domain_id = request.session.get("domain_context", None)
domain_name = request.session.get("domain_context_name", None)
# if running in Keystone V3 or later
if VERSIONS.active >= 3 and domain_id is None:
# if no domain context set, default to user's domain
domain_id = request.user.user_domain_id
domain_name = request.user.user_domain_name
if get_name and not request.user.is_federated:
try:
domain = domain_get(request, domain_id)
domain_name = domain.name
except exceptions.NotAuthorized:
# NOTE (knasim-wrs): Retrieving domain information
# is an admin URL operation. As a pre-check, such
# operations would be Forbidden if the logon user does
# not have an 'admin' role on the current project.
#
# Since this can be a common occurence and can cause
# incessant warning logging in the horizon logs,
# we recognize this condition and return the user's
# domain information instead.
LOG.debug("Cannot retrieve domain information for "
"user (%(user)s) that does not have an admin role "
"on project (%(project)s)",
{'user': request.user.username,
'project': request.user.project_name})
except Exception:
LOG.warning("Unable to retrieve Domain: %s", domain_id)
domain = base.APIDictWrapper({"id": domain_id,
"name": domain_name})
return domain | [
"def",
"get_default_domain",
"(",
"request",
",",
"get_name",
"=",
"True",
")",
":",
"domain_id",
"=",
"request",
".",
"session",
".",
"get",
"(",
"\"domain_context\"",
",",
"None",
")",
"domain_name",
"=",
"request",
".",
"session",
".",
"get",
"(",
"\"do... | Gets the default domain object to use when creating Identity object.
Returns the domain context if is set, otherwise return the domain
of the logon user.
:param get_name: Whether to get the domain name from Keystone if the
context isn't set. Setting this to False prevents an unnecessary call
to Keystone if only the domain ID is needed. | [
"Gets",
"the",
"default",
"domain",
"object",
"to",
"use",
"when",
"creating",
"Identity",
"object",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/keystone.py#L284-L324 |
234,974 | openstack/horizon | openstack_dashboard/api/keystone.py | get_effective_domain_id | def get_effective_domain_id(request):
"""Gets the id of the default domain.
If the requests default domain is the same as DEFAULT_DOMAIN,
return None.
"""
default_domain = get_default_domain(request)
domain_id = default_domain.get('id')
domain_name = default_domain.get('name')
return None if domain_name == DEFAULT_DOMAIN else domain_id | python | def get_effective_domain_id(request):
default_domain = get_default_domain(request)
domain_id = default_domain.get('id')
domain_name = default_domain.get('name')
return None if domain_name == DEFAULT_DOMAIN else domain_id | [
"def",
"get_effective_domain_id",
"(",
"request",
")",
":",
"default_domain",
"=",
"get_default_domain",
"(",
"request",
")",
"domain_id",
"=",
"default_domain",
".",
"get",
"(",
"'id'",
")",
"domain_name",
"=",
"default_domain",
".",
"get",
"(",
"'name'",
")",
... | Gets the id of the default domain.
If the requests default domain is the same as DEFAULT_DOMAIN,
return None. | [
"Gets",
"the",
"id",
"of",
"the",
"default",
"domain",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/keystone.py#L327-L336 |
234,975 | openstack/horizon | openstack_dashboard/api/keystone.py | get_project_groups_roles | def get_project_groups_roles(request, project):
"""Gets the groups roles in a given project.
:param request: the request entity containing the login user information
:param project: the project to filter the groups roles. It accepts both
project object resource or project ID
:returns group_roles: a dictionary mapping the groups and their roles in
given project
"""
groups_roles = collections.defaultdict(list)
project_role_assignments = role_assignments_list(request,
project=project)
for role_assignment in project_role_assignments:
if not hasattr(role_assignment, 'group'):
continue
group_id = role_assignment.group['id']
role_id = role_assignment.role['id']
# filter by project_id
if ('project' in role_assignment.scope and
role_assignment.scope['project']['id'] == project):
groups_roles[group_id].append(role_id)
return groups_roles | python | def get_project_groups_roles(request, project):
groups_roles = collections.defaultdict(list)
project_role_assignments = role_assignments_list(request,
project=project)
for role_assignment in project_role_assignments:
if not hasattr(role_assignment, 'group'):
continue
group_id = role_assignment.group['id']
role_id = role_assignment.role['id']
# filter by project_id
if ('project' in role_assignment.scope and
role_assignment.scope['project']['id'] == project):
groups_roles[group_id].append(role_id)
return groups_roles | [
"def",
"get_project_groups_roles",
"(",
"request",
",",
"project",
")",
":",
"groups_roles",
"=",
"collections",
".",
"defaultdict",
"(",
"list",
")",
"project_role_assignments",
"=",
"role_assignments_list",
"(",
"request",
",",
"project",
"=",
"project",
")",
"f... | Gets the groups roles in a given project.
:param request: the request entity containing the login user information
:param project: the project to filter the groups roles. It accepts both
project object resource or project ID
:returns group_roles: a dictionary mapping the groups and their roles in
given project | [
"Gets",
"the",
"groups",
"roles",
"in",
"a",
"given",
"project",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/keystone.py#L671-L696 |
234,976 | openstack/horizon | openstack_dashboard/api/keystone.py | role_list | def role_list(request, filters=None):
"""Returns a global list of available roles."""
manager = keystoneclient(request, admin=True).roles
roles = []
kwargs = {}
if filters is not None:
kwargs.update(filters)
if 'id' in kwargs:
try:
roles = [manager.get(kwargs['id'])]
except keystone_exceptions.NotFound:
roles = []
except Exception:
exceptions.handle(request)
else:
roles = manager.list(**kwargs)
return roles | python | def role_list(request, filters=None):
manager = keystoneclient(request, admin=True).roles
roles = []
kwargs = {}
if filters is not None:
kwargs.update(filters)
if 'id' in kwargs:
try:
roles = [manager.get(kwargs['id'])]
except keystone_exceptions.NotFound:
roles = []
except Exception:
exceptions.handle(request)
else:
roles = manager.list(**kwargs)
return roles | [
"def",
"role_list",
"(",
"request",
",",
"filters",
"=",
"None",
")",
":",
"manager",
"=",
"keystoneclient",
"(",
"request",
",",
"admin",
"=",
"True",
")",
".",
"roles",
"roles",
"=",
"[",
"]",
"kwargs",
"=",
"{",
"}",
"if",
"filters",
"is",
"not",
... | Returns a global list of available roles. | [
"Returns",
"a",
"global",
"list",
"of",
"available",
"roles",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/keystone.py#L742-L758 |
234,977 | openstack/horizon | openstack_dashboard/api/keystone.py | roles_for_user | def roles_for_user(request, user, project=None, domain=None):
"""Returns a list of user roles scoped to a project or domain."""
manager = keystoneclient(request, admin=True).roles
if VERSIONS.active < 3:
return manager.roles_for_user(user, project)
else:
return manager.list(user=user, domain=domain, project=project) | python | def roles_for_user(request, user, project=None, domain=None):
manager = keystoneclient(request, admin=True).roles
if VERSIONS.active < 3:
return manager.roles_for_user(user, project)
else:
return manager.list(user=user, domain=domain, project=project) | [
"def",
"roles_for_user",
"(",
"request",
",",
"user",
",",
"project",
"=",
"None",
",",
"domain",
"=",
"None",
")",
":",
"manager",
"=",
"keystoneclient",
"(",
"request",
",",
"admin",
"=",
"True",
")",
".",
"roles",
"if",
"VERSIONS",
".",
"active",
"<... | Returns a list of user roles scoped to a project or domain. | [
"Returns",
"a",
"list",
"of",
"user",
"roles",
"scoped",
"to",
"a",
"project",
"or",
"domain",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/keystone.py#L762-L768 |
234,978 | openstack/horizon | openstack_dashboard/api/keystone.py | add_domain_user_role | def add_domain_user_role(request, user, role, domain):
"""Adds a role for a user on a domain."""
manager = keystoneclient(request, admin=True).roles
return manager.grant(role, user=user, domain=domain) | python | def add_domain_user_role(request, user, role, domain):
manager = keystoneclient(request, admin=True).roles
return manager.grant(role, user=user, domain=domain) | [
"def",
"add_domain_user_role",
"(",
"request",
",",
"user",
",",
"role",
",",
"domain",
")",
":",
"manager",
"=",
"keystoneclient",
"(",
"request",
",",
"admin",
"=",
"True",
")",
".",
"roles",
"return",
"manager",
".",
"grant",
"(",
"role",
",",
"user",... | Adds a role for a user on a domain. | [
"Adds",
"a",
"role",
"for",
"a",
"user",
"on",
"a",
"domain",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/keystone.py#L791-L794 |
234,979 | openstack/horizon | openstack_dashboard/api/keystone.py | remove_domain_user_role | def remove_domain_user_role(request, user, role, domain=None):
"""Removes a given single role for a user from a domain."""
manager = keystoneclient(request, admin=True).roles
return manager.revoke(role, user=user, domain=domain) | python | def remove_domain_user_role(request, user, role, domain=None):
manager = keystoneclient(request, admin=True).roles
return manager.revoke(role, user=user, domain=domain) | [
"def",
"remove_domain_user_role",
"(",
"request",
",",
"user",
",",
"role",
",",
"domain",
"=",
"None",
")",
":",
"manager",
"=",
"keystoneclient",
"(",
"request",
",",
"admin",
"=",
"True",
")",
".",
"roles",
"return",
"manager",
".",
"revoke",
"(",
"ro... | Removes a given single role for a user from a domain. | [
"Removes",
"a",
"given",
"single",
"role",
"for",
"a",
"user",
"from",
"a",
"domain",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/keystone.py#L798-L801 |
234,980 | openstack/horizon | openstack_dashboard/api/keystone.py | add_tenant_user_role | def add_tenant_user_role(request, project=None, user=None, role=None,
group=None, domain=None):
"""Adds a role for a user on a tenant."""
manager = keystoneclient(request, admin=True).roles
if VERSIONS.active < 3:
manager.add_user_role(user, role, project)
else:
manager.grant(role, user=user, project=project,
group=group, domain=domain) | python | def add_tenant_user_role(request, project=None, user=None, role=None,
group=None, domain=None):
manager = keystoneclient(request, admin=True).roles
if VERSIONS.active < 3:
manager.add_user_role(user, role, project)
else:
manager.grant(role, user=user, project=project,
group=group, domain=domain) | [
"def",
"add_tenant_user_role",
"(",
"request",
",",
"project",
"=",
"None",
",",
"user",
"=",
"None",
",",
"role",
"=",
"None",
",",
"group",
"=",
"None",
",",
"domain",
"=",
"None",
")",
":",
"manager",
"=",
"keystoneclient",
"(",
"request",
",",
"adm... | Adds a role for a user on a tenant. | [
"Adds",
"a",
"role",
"for",
"a",
"user",
"on",
"a",
"tenant",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/keystone.py#L831-L839 |
234,981 | openstack/horizon | openstack_dashboard/api/keystone.py | remove_tenant_user_role | def remove_tenant_user_role(request, project=None, user=None, role=None,
group=None, domain=None):
"""Removes a given single role for a user from a tenant."""
manager = keystoneclient(request, admin=True).roles
if VERSIONS.active < 3:
return manager.remove_user_role(user, role, project)
else:
return manager.revoke(role, user=user, project=project,
group=group, domain=domain) | python | def remove_tenant_user_role(request, project=None, user=None, role=None,
group=None, domain=None):
manager = keystoneclient(request, admin=True).roles
if VERSIONS.active < 3:
return manager.remove_user_role(user, role, project)
else:
return manager.revoke(role, user=user, project=project,
group=group, domain=domain) | [
"def",
"remove_tenant_user_role",
"(",
"request",
",",
"project",
"=",
"None",
",",
"user",
"=",
"None",
",",
"role",
"=",
"None",
",",
"group",
"=",
"None",
",",
"domain",
"=",
"None",
")",
":",
"manager",
"=",
"keystoneclient",
"(",
"request",
",",
"... | Removes a given single role for a user from a tenant. | [
"Removes",
"a",
"given",
"single",
"role",
"for",
"a",
"user",
"from",
"a",
"tenant",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/keystone.py#L843-L851 |
234,982 | openstack/horizon | openstack_dashboard/api/keystone.py | remove_tenant_user | def remove_tenant_user(request, project=None, user=None, domain=None):
"""Removes all roles from a user on a tenant, removing them from it."""
client = keystoneclient(request, admin=True)
roles = client.roles.roles_for_user(user, project)
for role in roles:
remove_tenant_user_role(request, user=user, role=role.id,
project=project, domain=domain) | python | def remove_tenant_user(request, project=None, user=None, domain=None):
client = keystoneclient(request, admin=True)
roles = client.roles.roles_for_user(user, project)
for role in roles:
remove_tenant_user_role(request, user=user, role=role.id,
project=project, domain=domain) | [
"def",
"remove_tenant_user",
"(",
"request",
",",
"project",
"=",
"None",
",",
"user",
"=",
"None",
",",
"domain",
"=",
"None",
")",
":",
"client",
"=",
"keystoneclient",
"(",
"request",
",",
"admin",
"=",
"True",
")",
"roles",
"=",
"client",
".",
"rol... | Removes all roles from a user on a tenant, removing them from it. | [
"Removes",
"all",
"roles",
"from",
"a",
"user",
"on",
"a",
"tenant",
"removing",
"them",
"from",
"it",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/keystone.py#L854-L860 |
234,983 | openstack/horizon | openstack_dashboard/api/keystone.py | add_group_role | def add_group_role(request, role, group, domain=None, project=None):
"""Adds a role for a group on a domain or project."""
manager = keystoneclient(request, admin=True).roles
return manager.grant(role=role, group=group, domain=domain,
project=project) | python | def add_group_role(request, role, group, domain=None, project=None):
manager = keystoneclient(request, admin=True).roles
return manager.grant(role=role, group=group, domain=domain,
project=project) | [
"def",
"add_group_role",
"(",
"request",
",",
"role",
",",
"group",
",",
"domain",
"=",
"None",
",",
"project",
"=",
"None",
")",
":",
"manager",
"=",
"keystoneclient",
"(",
"request",
",",
"admin",
"=",
"True",
")",
".",
"roles",
"return",
"manager",
... | Adds a role for a group on a domain or project. | [
"Adds",
"a",
"role",
"for",
"a",
"group",
"on",
"a",
"domain",
"or",
"project",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/keystone.py#L870-L874 |
234,984 | openstack/horizon | openstack_dashboard/api/keystone.py | remove_group_role | def remove_group_role(request, role, group, domain=None, project=None):
"""Removes a given single role for a group from a domain or project."""
manager = keystoneclient(request, admin=True).roles
return manager.revoke(role=role, group=group, project=project,
domain=domain) | python | def remove_group_role(request, role, group, domain=None, project=None):
manager = keystoneclient(request, admin=True).roles
return manager.revoke(role=role, group=group, project=project,
domain=domain) | [
"def",
"remove_group_role",
"(",
"request",
",",
"role",
",",
"group",
",",
"domain",
"=",
"None",
",",
"project",
"=",
"None",
")",
":",
"manager",
"=",
"keystoneclient",
"(",
"request",
",",
"admin",
"=",
"True",
")",
".",
"roles",
"return",
"manager",... | Removes a given single role for a group from a domain or project. | [
"Removes",
"a",
"given",
"single",
"role",
"for",
"a",
"group",
"from",
"a",
"domain",
"or",
"project",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/keystone.py#L878-L882 |
234,985 | openstack/horizon | openstack_dashboard/api/keystone.py | remove_group_roles | def remove_group_roles(request, group, domain=None, project=None):
"""Removes all roles from a group on a domain or project."""
client = keystoneclient(request, admin=True)
roles = client.roles.list(group=group, domain=domain, project=project)
for role in roles:
remove_group_role(request, role=role.id, group=group,
domain=domain, project=project) | python | def remove_group_roles(request, group, domain=None, project=None):
client = keystoneclient(request, admin=True)
roles = client.roles.list(group=group, domain=domain, project=project)
for role in roles:
remove_group_role(request, role=role.id, group=group,
domain=domain, project=project) | [
"def",
"remove_group_roles",
"(",
"request",
",",
"group",
",",
"domain",
"=",
"None",
",",
"project",
"=",
"None",
")",
":",
"client",
"=",
"keystoneclient",
"(",
"request",
",",
"admin",
"=",
"True",
")",
"roles",
"=",
"client",
".",
"roles",
".",
"l... | Removes all roles from a group on a domain or project. | [
"Removes",
"all",
"roles",
"from",
"a",
"group",
"on",
"a",
"domain",
"or",
"project",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/keystone.py#L886-L892 |
234,986 | openstack/horizon | openstack_dashboard/api/keystone.py | get_default_role | def get_default_role(request):
"""Gets the default role object from Keystone and saves it as a global.
Since this is configured in settings and should not change from request
to request. Supports lookup by name or id.
"""
global DEFAULT_ROLE
default = getattr(settings, "OPENSTACK_KEYSTONE_DEFAULT_ROLE", None)
if default and DEFAULT_ROLE is None:
try:
roles = keystoneclient(request, admin=True).roles.list()
except Exception:
roles = []
exceptions.handle(request)
for role in roles:
if default in (role.id, role.name):
DEFAULT_ROLE = role
break
return DEFAULT_ROLE | python | def get_default_role(request):
global DEFAULT_ROLE
default = getattr(settings, "OPENSTACK_KEYSTONE_DEFAULT_ROLE", None)
if default and DEFAULT_ROLE is None:
try:
roles = keystoneclient(request, admin=True).roles.list()
except Exception:
roles = []
exceptions.handle(request)
for role in roles:
if default in (role.id, role.name):
DEFAULT_ROLE = role
break
return DEFAULT_ROLE | [
"def",
"get_default_role",
"(",
"request",
")",
":",
"global",
"DEFAULT_ROLE",
"default",
"=",
"getattr",
"(",
"settings",
",",
"\"OPENSTACK_KEYSTONE_DEFAULT_ROLE\"",
",",
"None",
")",
"if",
"default",
"and",
"DEFAULT_ROLE",
"is",
"None",
":",
"try",
":",
"roles... | Gets the default role object from Keystone and saves it as a global.
Since this is configured in settings and should not change from request
to request. Supports lookup by name or id. | [
"Gets",
"the",
"default",
"role",
"object",
"from",
"Keystone",
"and",
"saves",
"it",
"as",
"a",
"global",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/keystone.py#L895-L913 |
234,987 | openstack/horizon | horizon/browsers/breadcrumb.py | Breadcrumb.render | def render(self):
"""Renders the table using the template from the table options."""
breadcrumb_template = template.loader.get_template(self.template)
extra_context = {"breadcrumb": self}
return breadcrumb_template.render(extra_context, self.request) | python | def render(self):
breadcrumb_template = template.loader.get_template(self.template)
extra_context = {"breadcrumb": self}
return breadcrumb_template.render(extra_context, self.request) | [
"def",
"render",
"(",
"self",
")",
":",
"breadcrumb_template",
"=",
"template",
".",
"loader",
".",
"get_template",
"(",
"self",
".",
"template",
")",
"extra_context",
"=",
"{",
"\"breadcrumb\"",
":",
"self",
"}",
"return",
"breadcrumb_template",
".",
"render"... | Renders the table using the template from the table options. | [
"Renders",
"the",
"table",
"using",
"the",
"template",
"from",
"the",
"table",
"options",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/browsers/breadcrumb.py#L41-L45 |
234,988 | openstack/horizon | horizon/tabs/base.py | TabGroup.load_tab_data | def load_tab_data(self):
"""Preload all data that for the tabs that will be displayed."""
for tab in self._tabs.values():
if tab.load and not tab.data_loaded:
try:
tab._data = tab.get_context_data(self.request)
except Exception:
tab._data = False
exceptions.handle(self.request) | python | def load_tab_data(self):
for tab in self._tabs.values():
if tab.load and not tab.data_loaded:
try:
tab._data = tab.get_context_data(self.request)
except Exception:
tab._data = False
exceptions.handle(self.request) | [
"def",
"load_tab_data",
"(",
"self",
")",
":",
"for",
"tab",
"in",
"self",
".",
"_tabs",
".",
"values",
"(",
")",
":",
"if",
"tab",
".",
"load",
"and",
"not",
"tab",
".",
"data_loaded",
":",
"try",
":",
"tab",
".",
"_data",
"=",
"tab",
".",
"get_... | Preload all data that for the tabs that will be displayed. | [
"Preload",
"all",
"data",
"that",
"for",
"the",
"tabs",
"that",
"will",
"be",
"displayed",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/tabs/base.py#L170-L178 |
234,989 | openstack/horizon | horizon/tabs/base.py | TabGroup.get_default_classes | def get_default_classes(self):
"""Returns a list of the default classes for the tab group.
Defaults to ``["nav", "nav-tabs", "ajax-tabs"]``.
"""
default_classes = super(TabGroup, self).get_default_classes()
default_classes.extend(CSS_TAB_GROUP_CLASSES)
return default_classes | python | def get_default_classes(self):
default_classes = super(TabGroup, self).get_default_classes()
default_classes.extend(CSS_TAB_GROUP_CLASSES)
return default_classes | [
"def",
"get_default_classes",
"(",
"self",
")",
":",
"default_classes",
"=",
"super",
"(",
"TabGroup",
",",
"self",
")",
".",
"get_default_classes",
"(",
")",
"default_classes",
".",
"extend",
"(",
"CSS_TAB_GROUP_CLASSES",
")",
"return",
"default_classes"
] | Returns a list of the default classes for the tab group.
Defaults to ``["nav", "nav-tabs", "ajax-tabs"]``. | [
"Returns",
"a",
"list",
"of",
"the",
"default",
"classes",
"for",
"the",
"tab",
"group",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/tabs/base.py#L188-L195 |
234,990 | openstack/horizon | horizon/tabs/base.py | TabGroup.get_tab | def get_tab(self, tab_name, allow_disabled=False):
"""Returns a specific tab from this tab group.
If the tab is not allowed or not enabled this method returns ``None``.
If the tab is disabled but you wish to return it anyway, you can pass
``True`` to the allow_disabled argument.
"""
tab = self._tabs.get(tab_name, None)
if tab and tab._allowed and (tab._enabled or allow_disabled):
return tab
return None | python | def get_tab(self, tab_name, allow_disabled=False):
tab = self._tabs.get(tab_name, None)
if tab and tab._allowed and (tab._enabled or allow_disabled):
return tab
return None | [
"def",
"get_tab",
"(",
"self",
",",
"tab_name",
",",
"allow_disabled",
"=",
"False",
")",
":",
"tab",
"=",
"self",
".",
"_tabs",
".",
"get",
"(",
"tab_name",
",",
"None",
")",
"if",
"tab",
"and",
"tab",
".",
"_allowed",
"and",
"(",
"tab",
".",
"_en... | Returns a specific tab from this tab group.
If the tab is not allowed or not enabled this method returns ``None``.
If the tab is disabled but you wish to return it anyway, you can pass
``True`` to the allow_disabled argument. | [
"Returns",
"a",
"specific",
"tab",
"from",
"this",
"tab",
"group",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/tabs/base.py#L236-L247 |
234,991 | openstack/horizon | horizon/tabs/base.py | TabGroup.get_selected_tab | def get_selected_tab(self):
"""Returns the tab specific by the GET request parameter.
In the event that there is no GET request parameter, the value
of the query parameter is invalid, or the tab is not allowed/enabled,
the return value of this function is None.
"""
selected = self.request.GET.get(self.param_name, None)
if selected:
try:
tab_group, tab_name = selected.split(SEPARATOR)
except ValueError:
return None
if tab_group == self.get_id():
self._selected = self.get_tab(tab_name)
return self._selected | python | def get_selected_tab(self):
selected = self.request.GET.get(self.param_name, None)
if selected:
try:
tab_group, tab_name = selected.split(SEPARATOR)
except ValueError:
return None
if tab_group == self.get_id():
self._selected = self.get_tab(tab_name)
return self._selected | [
"def",
"get_selected_tab",
"(",
"self",
")",
":",
"selected",
"=",
"self",
".",
"request",
".",
"GET",
".",
"get",
"(",
"self",
".",
"param_name",
",",
"None",
")",
"if",
"selected",
":",
"try",
":",
"tab_group",
",",
"tab_name",
"=",
"selected",
".",
... | Returns the tab specific by the GET request parameter.
In the event that there is no GET request parameter, the value
of the query parameter is invalid, or the tab is not allowed/enabled,
the return value of this function is None. | [
"Returns",
"the",
"tab",
"specific",
"by",
"the",
"GET",
"request",
"parameter",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/tabs/base.py#L252-L267 |
234,992 | openstack/horizon | horizon/tabs/base.py | Tab.render | def render(self):
"""Renders the tab to HTML.
:meth:`~horizon.tabs.Tab.get_context_data` method and
the :meth:`~horizon.tabs.Tab.get_template_name` method are called.
If :attr:`~horizon.tabs.Tab.preload` is ``False`` and ``force_load``
is not ``True``, or
either :meth:`~horizon.tabs.Tab.allowed` or
:meth:`~horizon.tabs.Tab.enabled` returns ``False`` this method will
return an empty string.
"""
if not self.load:
return ''
try:
context = self.data
except exceptions.Http302:
raise
except Exception:
exc_type, exc_value, exc_traceback = sys.exc_info()
raise six.reraise(TemplateSyntaxError, exc_value, exc_traceback)
return render_to_string(self.get_template_name(self.request), context) | python | def render(self):
if not self.load:
return ''
try:
context = self.data
except exceptions.Http302:
raise
except Exception:
exc_type, exc_value, exc_traceback = sys.exc_info()
raise six.reraise(TemplateSyntaxError, exc_value, exc_traceback)
return render_to_string(self.get_template_name(self.request), context) | [
"def",
"render",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"load",
":",
"return",
"''",
"try",
":",
"context",
"=",
"self",
".",
"data",
"except",
"exceptions",
".",
"Http302",
":",
"raise",
"except",
"Exception",
":",
"exc_type",
",",
"exc_valu... | Renders the tab to HTML.
:meth:`~horizon.tabs.Tab.get_context_data` method and
the :meth:`~horizon.tabs.Tab.get_template_name` method are called.
If :attr:`~horizon.tabs.Tab.preload` is ``False`` and ``force_load``
is not ``True``, or
either :meth:`~horizon.tabs.Tab.allowed` or
:meth:`~horizon.tabs.Tab.enabled` returns ``False`` this method will
return an empty string. | [
"Renders",
"the",
"tab",
"to",
"HTML",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/tabs/base.py#L356-L377 |
234,993 | openstack/horizon | horizon/tabs/base.py | Tab.get_default_classes | def get_default_classes(self):
"""Returns a list of the default classes for the tab.
Defaults to and empty list (``[]``), however additional classes may
be added depending on the state of the tab as follows:
If the tab is the active tab for the tab group, in which
the class ``"active"`` will be added.
If the tab is not enabled, the classes the class ``"disabled"``
will be added.
"""
default_classes = super(Tab, self).get_default_classes()
if self.is_active():
default_classes.extend(CSS_ACTIVE_TAB_CLASSES)
if not self._enabled:
default_classes.extend(CSS_DISABLED_TAB_CLASSES)
return default_classes | python | def get_default_classes(self):
default_classes = super(Tab, self).get_default_classes()
if self.is_active():
default_classes.extend(CSS_ACTIVE_TAB_CLASSES)
if not self._enabled:
default_classes.extend(CSS_DISABLED_TAB_CLASSES)
return default_classes | [
"def",
"get_default_classes",
"(",
"self",
")",
":",
"default_classes",
"=",
"super",
"(",
"Tab",
",",
"self",
")",
".",
"get_default_classes",
"(",
")",
"if",
"self",
".",
"is_active",
"(",
")",
":",
"default_classes",
".",
"extend",
"(",
"CSS_ACTIVE_TAB_CL... | Returns a list of the default classes for the tab.
Defaults to and empty list (``[]``), however additional classes may
be added depending on the state of the tab as follows:
If the tab is the active tab for the tab group, in which
the class ``"active"`` will be added.
If the tab is not enabled, the classes the class ``"disabled"``
will be added. | [
"Returns",
"a",
"list",
"of",
"the",
"default",
"classes",
"for",
"the",
"tab",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/tabs/base.py#L389-L406 |
234,994 | openstack/horizon | horizon/tabs/base.py | Tab.get_template_name | def get_template_name(self, request):
"""Returns the name of the template to be used for rendering this tab.
By default it returns the value of the ``template_name`` attribute
on the ``Tab`` class.
"""
if not hasattr(self, "template_name"):
raise AttributeError("%s must have a template_name attribute or "
"override the get_template_name method."
% self.__class__.__name__)
return self.template_name | python | def get_template_name(self, request):
if not hasattr(self, "template_name"):
raise AttributeError("%s must have a template_name attribute or "
"override the get_template_name method."
% self.__class__.__name__)
return self.template_name | [
"def",
"get_template_name",
"(",
"self",
",",
"request",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"\"template_name\"",
")",
":",
"raise",
"AttributeError",
"(",
"\"%s must have a template_name attribute or \"",
"\"override the get_template_name method.\"",
"%",... | Returns the name of the template to be used for rendering this tab.
By default it returns the value of the ``template_name`` attribute
on the ``Tab`` class. | [
"Returns",
"the",
"name",
"of",
"the",
"template",
"to",
"be",
"used",
"for",
"rendering",
"this",
"tab",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/tabs/base.py#L408-L418 |
234,995 | openstack/horizon | horizon/templatetags/breadcrumb_nav.py | breadcrumb_nav | def breadcrumb_nav(context):
"""A logic heavy function for automagically creating a breadcrumb.
It uses the dashboard, panel group(if it exists), then current panel.
Can also use a "custom_breadcrumb" context item to add extra items.
"""
breadcrumb = []
dashboard = context.request.horizon['dashboard']
try:
panel_groups = dashboard.get_panel_groups()
except KeyError:
panel_groups = None
panel_group = None
panel = context.request.horizon['panel']
# Add panel group, if there is one
if panel_groups:
for group in panel_groups.values():
if panel.slug in group.panels and group.slug != 'default':
panel_group = group
break
# Remove panel reference if that is the current page
if panel.get_absolute_url() == context.request.path:
panel = None
# Get custom breadcrumb, if there is one.
custom_breadcrumb = context.get('custom_breadcrumb')
# Build list of tuples (name, optional url)
breadcrumb.append((dashboard.name, None))
if panel_group:
breadcrumb.append((panel_group.name, None))
if panel:
breadcrumb.append((panel.name, panel.get_absolute_url()))
if custom_breadcrumb:
breadcrumb.extend(custom_breadcrumb)
breadcrumb.append((context.get('page_title'), None))
return {'breadcrumb': breadcrumb} | python | def breadcrumb_nav(context):
breadcrumb = []
dashboard = context.request.horizon['dashboard']
try:
panel_groups = dashboard.get_panel_groups()
except KeyError:
panel_groups = None
panel_group = None
panel = context.request.horizon['panel']
# Add panel group, if there is one
if panel_groups:
for group in panel_groups.values():
if panel.slug in group.panels and group.slug != 'default':
panel_group = group
break
# Remove panel reference if that is the current page
if panel.get_absolute_url() == context.request.path:
panel = None
# Get custom breadcrumb, if there is one.
custom_breadcrumb = context.get('custom_breadcrumb')
# Build list of tuples (name, optional url)
breadcrumb.append((dashboard.name, None))
if panel_group:
breadcrumb.append((panel_group.name, None))
if panel:
breadcrumb.append((panel.name, panel.get_absolute_url()))
if custom_breadcrumb:
breadcrumb.extend(custom_breadcrumb)
breadcrumb.append((context.get('page_title'), None))
return {'breadcrumb': breadcrumb} | [
"def",
"breadcrumb_nav",
"(",
"context",
")",
":",
"breadcrumb",
"=",
"[",
"]",
"dashboard",
"=",
"context",
".",
"request",
".",
"horizon",
"[",
"'dashboard'",
"]",
"try",
":",
"panel_groups",
"=",
"dashboard",
".",
"get_panel_groups",
"(",
")",
"except",
... | A logic heavy function for automagically creating a breadcrumb.
It uses the dashboard, panel group(if it exists), then current panel.
Can also use a "custom_breadcrumb" context item to add extra items. | [
"A",
"logic",
"heavy",
"function",
"for",
"automagically",
"creating",
"a",
"breadcrumb",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/templatetags/breadcrumb_nav.py#L22-L61 |
234,996 | openstack/horizon | horizon/utils/html.py | HTMLElement.get_final_attrs | def get_final_attrs(self, classes=True):
"""Returns a dict containing the final attributes to be rendered."""
final_attrs = copy.copy(self.get_default_attrs())
final_attrs.update(self.attrs)
if classes:
final_attrs['class'] = self.get_final_css()
else:
final_attrs.pop('class', None)
return final_attrs | python | def get_final_attrs(self, classes=True):
final_attrs = copy.copy(self.get_default_attrs())
final_attrs.update(self.attrs)
if classes:
final_attrs['class'] = self.get_final_css()
else:
final_attrs.pop('class', None)
return final_attrs | [
"def",
"get_final_attrs",
"(",
"self",
",",
"classes",
"=",
"True",
")",
":",
"final_attrs",
"=",
"copy",
".",
"copy",
"(",
"self",
".",
"get_default_attrs",
"(",
")",
")",
"final_attrs",
".",
"update",
"(",
"self",
".",
"attrs",
")",
"if",
"classes",
... | Returns a dict containing the final attributes to be rendered. | [
"Returns",
"a",
"dict",
"containing",
"the",
"final",
"attributes",
"to",
"be",
"rendered",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/utils/html.py#L38-L47 |
234,997 | openstack/horizon | horizon/utils/html.py | HTMLElement.get_final_css | def get_final_css(self):
"""Returns a final css class concatenated string."""
default = " ".join(self.get_default_classes())
defined = self.attrs.get('class', '')
additional = " ".join(getattr(self, "classes", []))
non_empty = [test for test in (defined, default, additional) if test]
final_classes = " ".join(non_empty).strip()
return final_classes | python | def get_final_css(self):
default = " ".join(self.get_default_classes())
defined = self.attrs.get('class', '')
additional = " ".join(getattr(self, "classes", []))
non_empty = [test for test in (defined, default, additional) if test]
final_classes = " ".join(non_empty).strip()
return final_classes | [
"def",
"get_final_css",
"(",
"self",
")",
":",
"default",
"=",
"\" \"",
".",
"join",
"(",
"self",
".",
"get_default_classes",
"(",
")",
")",
"defined",
"=",
"self",
".",
"attrs",
".",
"get",
"(",
"'class'",
",",
"''",
")",
"additional",
"=",
"\" \"",
... | Returns a final css class concatenated string. | [
"Returns",
"a",
"final",
"css",
"class",
"concatenated",
"string",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/utils/html.py#L49-L56 |
234,998 | openstack/horizon | openstack_dashboard/dashboards/project/instances/utils.py | flavor_list | def flavor_list(request):
"""Utility method to retrieve a list of flavors."""
try:
return api.nova.flavor_list(request)
except Exception:
exceptions.handle(request,
_('Unable to retrieve instance flavors.'))
return [] | python | def flavor_list(request):
try:
return api.nova.flavor_list(request)
except Exception:
exceptions.handle(request,
_('Unable to retrieve instance flavors.'))
return [] | [
"def",
"flavor_list",
"(",
"request",
")",
":",
"try",
":",
"return",
"api",
".",
"nova",
".",
"flavor_list",
"(",
"request",
")",
"except",
"Exception",
":",
"exceptions",
".",
"handle",
"(",
"request",
",",
"_",
"(",
"'Unable to retrieve instance flavors.'",... | Utility method to retrieve a list of flavors. | [
"Utility",
"method",
"to",
"retrieve",
"a",
"list",
"of",
"flavors",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/dashboards/project/instances/utils.py#L27-L34 |
234,999 | openstack/horizon | openstack_dashboard/dashboards/project/instances/utils.py | sort_flavor_list | def sort_flavor_list(request, flavors, with_menu_label=True):
"""Utility method to sort a list of flavors.
By default, returns the available flavors, sorted by RAM usage (ascending).
Override these behaviours with a ``CREATE_INSTANCE_FLAVOR_SORT`` dict
in ``local_settings.py``.
"""
def get_key(flavor, sort_key):
try:
return getattr(flavor, sort_key)
except AttributeError:
LOG.warning('Could not find sort key "%s". Using the default '
'"ram" instead.', sort_key)
return getattr(flavor, 'ram')
try:
flavor_sort = getattr(settings, 'CREATE_INSTANCE_FLAVOR_SORT', {})
sort_key = flavor_sort.get('key', 'ram')
rev = flavor_sort.get('reverse', False)
if not callable(sort_key):
def key(flavor):
return get_key(flavor, sort_key)
else:
key = sort_key
if with_menu_label:
flavor_list = [(flavor.id, '%s' % flavor.name)
for flavor in sorted(flavors, key=key, reverse=rev)]
else:
flavor_list = sorted(flavors, key=key, reverse=rev)
return flavor_list
except Exception:
exceptions.handle(request,
_('Unable to sort instance flavors.'))
return [] | python | def sort_flavor_list(request, flavors, with_menu_label=True):
def get_key(flavor, sort_key):
try:
return getattr(flavor, sort_key)
except AttributeError:
LOG.warning('Could not find sort key "%s". Using the default '
'"ram" instead.', sort_key)
return getattr(flavor, 'ram')
try:
flavor_sort = getattr(settings, 'CREATE_INSTANCE_FLAVOR_SORT', {})
sort_key = flavor_sort.get('key', 'ram')
rev = flavor_sort.get('reverse', False)
if not callable(sort_key):
def key(flavor):
return get_key(flavor, sort_key)
else:
key = sort_key
if with_menu_label:
flavor_list = [(flavor.id, '%s' % flavor.name)
for flavor in sorted(flavors, key=key, reverse=rev)]
else:
flavor_list = sorted(flavors, key=key, reverse=rev)
return flavor_list
except Exception:
exceptions.handle(request,
_('Unable to sort instance flavors.'))
return [] | [
"def",
"sort_flavor_list",
"(",
"request",
",",
"flavors",
",",
"with_menu_label",
"=",
"True",
")",
":",
"def",
"get_key",
"(",
"flavor",
",",
"sort_key",
")",
":",
"try",
":",
"return",
"getattr",
"(",
"flavor",
",",
"sort_key",
")",
"except",
"Attribute... | Utility method to sort a list of flavors.
By default, returns the available flavors, sorted by RAM usage (ascending).
Override these behaviours with a ``CREATE_INSTANCE_FLAVOR_SORT`` dict
in ``local_settings.py``. | [
"Utility",
"method",
"to",
"sort",
"a",
"list",
"of",
"flavors",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/dashboards/project/instances/utils.py#L37-L70 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.