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 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
openstack/horizon | openstack_auth/utils.py | fix_auth_url_version_prefix | def fix_auth_url_version_prefix(auth_url):
"""Fix up the auth url if an invalid or no version prefix was given.
People still give a v2 auth_url even when they specify that they want v3
authentication. Fix the URL to say v3 in this case and add version if it is
missing entirely. This should be smarter and use discovery.
"""
auth_url = _augment_url_with_version(auth_url)
url_fixed = False
if get_keystone_version() >= 3 and has_in_url_path(auth_url, ["/v2.0"]):
url_fixed = True
auth_url = url_path_replace(auth_url, "/v2.0", "/v3", 1)
return auth_url, url_fixed | python | def fix_auth_url_version_prefix(auth_url):
"""Fix up the auth url if an invalid or no version prefix was given.
People still give a v2 auth_url even when they specify that they want v3
authentication. Fix the URL to say v3 in this case and add version if it is
missing entirely. This should be smarter and use discovery.
"""
auth_url = _augment_url_with_version(auth_url)
url_fixed = False
if get_keystone_version() >= 3 and has_in_url_path(auth_url, ["/v2.0"]):
url_fixed = True
auth_url = url_path_replace(auth_url, "/v2.0", "/v3", 1)
return auth_url, url_fixed | [
"def",
"fix_auth_url_version_prefix",
"(",
"auth_url",
")",
":",
"auth_url",
"=",
"_augment_url_with_version",
"(",
"auth_url",
")",
"url_fixed",
"=",
"False",
"if",
"get_keystone_version",
"(",
")",
">=",
"3",
"and",
"has_in_url_path",
"(",
"auth_url",
",",
"[",
... | Fix up the auth url if an invalid or no version prefix was given.
People still give a v2 auth_url even when they specify that they want v3
authentication. Fix the URL to say v3 in this case and add version if it is
missing entirely. This should be smarter and use discovery. | [
"Fix",
"up",
"the",
"auth",
"url",
"if",
"an",
"invalid",
"or",
"no",
"version",
"prefix",
"was",
"given",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_auth/utils.py#L306-L320 | train | 215,900 |
openstack/horizon | openstack_auth/utils.py | clean_up_auth_url | def clean_up_auth_url(auth_url):
"""Clean up the auth url to extract the exact Keystone URL"""
# NOTE(mnaser): This drops the query and fragment because we're only
# trying to extract the Keystone URL.
scheme, netloc, path, query, fragment = urlparse.urlsplit(auth_url)
return urlparse.urlunsplit((
scheme, netloc, re.sub(r'/auth.*', '', path), '', '')) | python | def clean_up_auth_url(auth_url):
"""Clean up the auth url to extract the exact Keystone URL"""
# NOTE(mnaser): This drops the query and fragment because we're only
# trying to extract the Keystone URL.
scheme, netloc, path, query, fragment = urlparse.urlsplit(auth_url)
return urlparse.urlunsplit((
scheme, netloc, re.sub(r'/auth.*', '', path), '', '')) | [
"def",
"clean_up_auth_url",
"(",
"auth_url",
")",
":",
"# NOTE(mnaser): This drops the query and fragment because we're only",
"# trying to extract the Keystone URL.",
"scheme",
",",
"netloc",
",",
"path",
",",
"query",
",",
"fragment",
"=",
"urlparse",
".",
"ur... | Clean up the auth url to extract the exact Keystone URL | [
"Clean",
"up",
"the",
"auth",
"url",
"to",
"extract",
"the",
"exact",
"Keystone",
"URL"
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_auth/utils.py#L323-L330 | train | 215,901 |
openstack/horizon | openstack_auth/utils.py | default_services_region | def default_services_region(service_catalog, request=None,
ks_endpoint=None):
"""Return the default service region.
Order of precedence:
1. 'services_region' cookie value
2. Matching endpoint in DEFAULT_SERVICE_REGIONS
3. '*' key in DEFAULT_SERVICE_REGIONS
4. First valid region from catalog
In each case the value must also be present in available_regions or
we move to the next level of precedence.
"""
if service_catalog:
available_regions = [get_endpoint_region(endpoint) for service
in service_catalog for endpoint
in service.get('endpoints', [])
if (service.get('type') is not None and
service.get('type') != 'identity')]
if not available_regions:
# this is very likely an incomplete keystone setup
LOG.warning('No regions could be found excluding identity.')
available_regions = [get_endpoint_region(endpoint) for service
in service_catalog for endpoint
in service.get('endpoints', [])]
if not available_regions:
# if there are no region setup for any service endpoint,
# this is a critical problem and it's not clear how this occurs
LOG.error('No regions can be found in the service catalog.')
return None
region_options = []
if request:
region_options.append(request.COOKIES.get('services_region'))
if ks_endpoint:
default_service_regions = getattr(
settings, 'DEFAULT_SERVICE_REGIONS', {})
region_options.append(default_service_regions.get(ks_endpoint))
region_options.append(
getattr(settings, 'DEFAULT_SERVICE_REGIONS', {}).get('*'))
for region in region_options:
if region in available_regions:
return region
return available_regions[0]
return None | python | def default_services_region(service_catalog, request=None,
ks_endpoint=None):
"""Return the default service region.
Order of precedence:
1. 'services_region' cookie value
2. Matching endpoint in DEFAULT_SERVICE_REGIONS
3. '*' key in DEFAULT_SERVICE_REGIONS
4. First valid region from catalog
In each case the value must also be present in available_regions or
we move to the next level of precedence.
"""
if service_catalog:
available_regions = [get_endpoint_region(endpoint) for service
in service_catalog for endpoint
in service.get('endpoints', [])
if (service.get('type') is not None and
service.get('type') != 'identity')]
if not available_regions:
# this is very likely an incomplete keystone setup
LOG.warning('No regions could be found excluding identity.')
available_regions = [get_endpoint_region(endpoint) for service
in service_catalog for endpoint
in service.get('endpoints', [])]
if not available_regions:
# if there are no region setup for any service endpoint,
# this is a critical problem and it's not clear how this occurs
LOG.error('No regions can be found in the service catalog.')
return None
region_options = []
if request:
region_options.append(request.COOKIES.get('services_region'))
if ks_endpoint:
default_service_regions = getattr(
settings, 'DEFAULT_SERVICE_REGIONS', {})
region_options.append(default_service_regions.get(ks_endpoint))
region_options.append(
getattr(settings, 'DEFAULT_SERVICE_REGIONS', {}).get('*'))
for region in region_options:
if region in available_regions:
return region
return available_regions[0]
return None | [
"def",
"default_services_region",
"(",
"service_catalog",
",",
"request",
"=",
"None",
",",
"ks_endpoint",
"=",
"None",
")",
":",
"if",
"service_catalog",
":",
"available_regions",
"=",
"[",
"get_endpoint_region",
"(",
"endpoint",
")",
"for",
"service",
"in",
"s... | Return the default service region.
Order of precedence:
1. 'services_region' cookie value
2. Matching endpoint in DEFAULT_SERVICE_REGIONS
3. '*' key in DEFAULT_SERVICE_REGIONS
4. First valid region from catalog
In each case the value must also be present in available_regions or
we move to the next level of precedence. | [
"Return",
"the",
"default",
"service",
"region",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_auth/utils.py#L370-L416 | train | 215,902 |
openstack/horizon | openstack_auth/utils.py | set_response_cookie | def set_response_cookie(response, cookie_name, cookie_value):
"""Common function for setting the cookie in the response.
Provides a common policy of setting cookies for last used project
and region, can be reused in other locations.
This method will set the cookie to expire in 365 days.
"""
now = timezone.now()
expire_date = now + datetime.timedelta(days=365)
response.set_cookie(cookie_name, cookie_value, expires=expire_date) | python | def set_response_cookie(response, cookie_name, cookie_value):
"""Common function for setting the cookie in the response.
Provides a common policy of setting cookies for last used project
and region, can be reused in other locations.
This method will set the cookie to expire in 365 days.
"""
now = timezone.now()
expire_date = now + datetime.timedelta(days=365)
response.set_cookie(cookie_name, cookie_value, expires=expire_date) | [
"def",
"set_response_cookie",
"(",
"response",
",",
"cookie_name",
",",
"cookie_value",
")",
":",
"now",
"=",
"timezone",
".",
"now",
"(",
")",
"expire_date",
"=",
"now",
"+",
"datetime",
".",
"timedelta",
"(",
"days",
"=",
"365",
")",
"response",
".",
"... | Common function for setting the cookie in the response.
Provides a common policy of setting cookies for last used project
and region, can be reused in other locations.
This method will set the cookie to expire in 365 days. | [
"Common",
"function",
"for",
"setting",
"the",
"cookie",
"in",
"the",
"response",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_auth/utils.py#L419-L429 | train | 215,903 |
openstack/horizon | openstack_auth/utils.py | get_client_ip | def get_client_ip(request):
"""Return client ip address using SECURE_PROXY_ADDR_HEADER variable.
If not present or not defined on settings then REMOTE_ADDR is used.
:param request: Django http request object.
:type request: django.http.HttpRequest
:returns: Possible client ip address
:rtype: string
"""
_SECURE_PROXY_ADDR_HEADER = getattr(
settings, 'SECURE_PROXY_ADDR_HEADER', False
)
if _SECURE_PROXY_ADDR_HEADER:
return request.META.get(
_SECURE_PROXY_ADDR_HEADER,
request.META.get('REMOTE_ADDR')
)
return request.META.get('REMOTE_ADDR') | python | def get_client_ip(request):
"""Return client ip address using SECURE_PROXY_ADDR_HEADER variable.
If not present or not defined on settings then REMOTE_ADDR is used.
:param request: Django http request object.
:type request: django.http.HttpRequest
:returns: Possible client ip address
:rtype: string
"""
_SECURE_PROXY_ADDR_HEADER = getattr(
settings, 'SECURE_PROXY_ADDR_HEADER', False
)
if _SECURE_PROXY_ADDR_HEADER:
return request.META.get(
_SECURE_PROXY_ADDR_HEADER,
request.META.get('REMOTE_ADDR')
)
return request.META.get('REMOTE_ADDR') | [
"def",
"get_client_ip",
"(",
"request",
")",
":",
"_SECURE_PROXY_ADDR_HEADER",
"=",
"getattr",
"(",
"settings",
",",
"'SECURE_PROXY_ADDR_HEADER'",
",",
"False",
")",
"if",
"_SECURE_PROXY_ADDR_HEADER",
":",
"return",
"request",
".",
"META",
".",
"get",
"(",
"_SECUR... | Return client ip address using SECURE_PROXY_ADDR_HEADER variable.
If not present or not defined on settings then REMOTE_ADDR is used.
:param request: Django http request object.
:type request: django.http.HttpRequest
:returns: Possible client ip address
:rtype: string | [
"Return",
"client",
"ip",
"address",
"using",
"SECURE_PROXY_ADDR_HEADER",
"variable",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_auth/utils.py#L499-L518 | train | 215,904 |
openstack/horizon | openstack_auth/utils.py | store_initial_k2k_session | def store_initial_k2k_session(auth_url, request, scoped_auth_ref,
unscoped_auth_ref):
"""Stores session variables if there are k2k service providers
This stores variables related to Keystone2Keystone federation. This
function gets skipped if there are no Keystone service providers.
An unscoped token to the identity provider keystone gets stored
so that it can be used to do federated login into the service
providers when switching keystone providers.
The settings file can be configured to set the display name
of the local (identity provider) keystone by setting
KEYSTONE_PROVIDER_IDP_NAME. The KEYSTONE_PROVIDER_IDP_ID settings
variable is used for comparison against the service providers.
It should not conflict with any of the service provider ids.
:param auth_url: base token auth url
:param request: Django http request object
:param scoped_auth_ref: Scoped Keystone access info object
:param unscoped_auth_ref: Unscoped Keystone access info object
"""
keystone_provider_id = request.session.get('keystone_provider_id', None)
if keystone_provider_id:
return None
providers = getattr(scoped_auth_ref, 'service_providers', None)
if providers:
providers = getattr(providers, '_service_providers', None)
if providers:
keystone_idp_name = getattr(settings, 'KEYSTONE_PROVIDER_IDP_NAME',
'Local Keystone')
keystone_idp_id = getattr(
settings, 'KEYSTONE_PROVIDER_IDP_ID', 'localkeystone')
keystone_identity_provider = {'name': keystone_idp_name,
'id': keystone_idp_id}
# (edtubill) We will use the IDs as the display names
# We may want to be able to set display names in the future.
keystone_providers = [
{'name': provider_id, 'id': provider_id}
for provider_id in providers]
keystone_providers.append(keystone_identity_provider)
# We treat the Keystone idp ID as None
request.session['keystone_provider_id'] = keystone_idp_id
request.session['keystone_providers'] = keystone_providers
request.session['k2k_base_unscoped_token'] =\
unscoped_auth_ref.auth_token
request.session['k2k_auth_url'] = auth_url | python | def store_initial_k2k_session(auth_url, request, scoped_auth_ref,
unscoped_auth_ref):
"""Stores session variables if there are k2k service providers
This stores variables related to Keystone2Keystone federation. This
function gets skipped if there are no Keystone service providers.
An unscoped token to the identity provider keystone gets stored
so that it can be used to do federated login into the service
providers when switching keystone providers.
The settings file can be configured to set the display name
of the local (identity provider) keystone by setting
KEYSTONE_PROVIDER_IDP_NAME. The KEYSTONE_PROVIDER_IDP_ID settings
variable is used for comparison against the service providers.
It should not conflict with any of the service provider ids.
:param auth_url: base token auth url
:param request: Django http request object
:param scoped_auth_ref: Scoped Keystone access info object
:param unscoped_auth_ref: Unscoped Keystone access info object
"""
keystone_provider_id = request.session.get('keystone_provider_id', None)
if keystone_provider_id:
return None
providers = getattr(scoped_auth_ref, 'service_providers', None)
if providers:
providers = getattr(providers, '_service_providers', None)
if providers:
keystone_idp_name = getattr(settings, 'KEYSTONE_PROVIDER_IDP_NAME',
'Local Keystone')
keystone_idp_id = getattr(
settings, 'KEYSTONE_PROVIDER_IDP_ID', 'localkeystone')
keystone_identity_provider = {'name': keystone_idp_name,
'id': keystone_idp_id}
# (edtubill) We will use the IDs as the display names
# We may want to be able to set display names in the future.
keystone_providers = [
{'name': provider_id, 'id': provider_id}
for provider_id in providers]
keystone_providers.append(keystone_identity_provider)
# We treat the Keystone idp ID as None
request.session['keystone_provider_id'] = keystone_idp_id
request.session['keystone_providers'] = keystone_providers
request.session['k2k_base_unscoped_token'] =\
unscoped_auth_ref.auth_token
request.session['k2k_auth_url'] = auth_url | [
"def",
"store_initial_k2k_session",
"(",
"auth_url",
",",
"request",
",",
"scoped_auth_ref",
",",
"unscoped_auth_ref",
")",
":",
"keystone_provider_id",
"=",
"request",
".",
"session",
".",
"get",
"(",
"'keystone_provider_id'",
",",
"None",
")",
"if",
"keystone_prov... | Stores session variables if there are k2k service providers
This stores variables related to Keystone2Keystone federation. This
function gets skipped if there are no Keystone service providers.
An unscoped token to the identity provider keystone gets stored
so that it can be used to do federated login into the service
providers when switching keystone providers.
The settings file can be configured to set the display name
of the local (identity provider) keystone by setting
KEYSTONE_PROVIDER_IDP_NAME. The KEYSTONE_PROVIDER_IDP_ID settings
variable is used for comparison against the service providers.
It should not conflict with any of the service provider ids.
:param auth_url: base token auth url
:param request: Django http request object
:param scoped_auth_ref: Scoped Keystone access info object
:param unscoped_auth_ref: Unscoped Keystone access info object | [
"Stores",
"session",
"variables",
"if",
"there",
"are",
"k2k",
"service",
"providers"
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_auth/utils.py#L521-L569 | train | 215,905 |
openstack/horizon | openstack_dashboard/utils/filters.py | get_int_or_uuid | def get_int_or_uuid(value):
"""Check if a value is valid as UUID or an integer.
This method is mainly used to convert floating IP id to the
appropriate type. For floating IP id, integer is used in Nova's
original implementation, but UUID is used in Neutron based one.
"""
try:
uuid.UUID(value)
return value
except (ValueError, AttributeError):
return int(value) | python | def get_int_or_uuid(value):
"""Check if a value is valid as UUID or an integer.
This method is mainly used to convert floating IP id to the
appropriate type. For floating IP id, integer is used in Nova's
original implementation, but UUID is used in Neutron based one.
"""
try:
uuid.UUID(value)
return value
except (ValueError, AttributeError):
return int(value) | [
"def",
"get_int_or_uuid",
"(",
"value",
")",
":",
"try",
":",
"uuid",
".",
"UUID",
"(",
"value",
")",
"return",
"value",
"except",
"(",
"ValueError",
",",
"AttributeError",
")",
":",
"return",
"int",
"(",
"value",
")"
] | Check if a value is valid as UUID or an integer.
This method is mainly used to convert floating IP id to the
appropriate type. For floating IP id, integer is used in Nova's
original implementation, but UUID is used in Neutron based one. | [
"Check",
"if",
"a",
"value",
"is",
"valid",
"as",
"UUID",
"or",
"an",
"integer",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/utils/filters.py#L18-L29 | train | 215,906 |
openstack/horizon | openstack_dashboard/utils/filters.py | get_display_label | def get_display_label(choices, status):
"""Get a display label for resource status.
This method is used in places where a resource's status or
admin state labels need to assigned before they are sent to the
view template.
"""
for (value, label) in choices:
if value == (status or '').lower():
display_label = label
break
else:
display_label = status
return display_label | python | def get_display_label(choices, status):
"""Get a display label for resource status.
This method is used in places where a resource's status or
admin state labels need to assigned before they are sent to the
view template.
"""
for (value, label) in choices:
if value == (status or '').lower():
display_label = label
break
else:
display_label = status
return display_label | [
"def",
"get_display_label",
"(",
"choices",
",",
"status",
")",
":",
"for",
"(",
"value",
",",
"label",
")",
"in",
"choices",
":",
"if",
"value",
"==",
"(",
"status",
"or",
"''",
")",
".",
"lower",
"(",
")",
":",
"display_label",
"=",
"label",
"break... | Get a display label for resource status.
This method is used in places where a resource's status or
admin state labels need to assigned before they are sent to the
view template. | [
"Get",
"a",
"display",
"label",
"for",
"resource",
"status",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/utils/filters.py#L32-L47 | train | 215,907 |
openstack/horizon | openstack_auth/backend.py | KeystoneBackend.get_user | def get_user(self, user_id):
"""Returns the current user from the session data.
If authenticated, this return the user object based on the user ID
and session data.
.. note::
This required monkey-patching the ``contrib.auth`` middleware
to make the ``request`` object available to the auth backend class.
"""
if (hasattr(self, 'request') and
user_id == self.request.session["user_id"]):
token = self.request.session['token']
endpoint = self.request.session['region_endpoint']
services_region = self.request.session['services_region']
user = auth_user.create_user_from_token(self.request, token,
endpoint, services_region)
return user
else:
return None | python | def get_user(self, user_id):
"""Returns the current user from the session data.
If authenticated, this return the user object based on the user ID
and session data.
.. note::
This required monkey-patching the ``contrib.auth`` middleware
to make the ``request`` object available to the auth backend class.
"""
if (hasattr(self, 'request') and
user_id == self.request.session["user_id"]):
token = self.request.session['token']
endpoint = self.request.session['region_endpoint']
services_region = self.request.session['services_region']
user = auth_user.create_user_from_token(self.request, token,
endpoint, services_region)
return user
else:
return None | [
"def",
"get_user",
"(",
"self",
",",
"user_id",
")",
":",
"if",
"(",
"hasattr",
"(",
"self",
",",
"'request'",
")",
"and",
"user_id",
"==",
"self",
".",
"request",
".",
"session",
"[",
"\"user_id\"",
"]",
")",
":",
"token",
"=",
"self",
".",
"request... | Returns the current user from the session data.
If authenticated, this return the user object based on the user ID
and session data.
.. note::
This required monkey-patching the ``contrib.auth`` middleware
to make the ``request`` object available to the auth backend class. | [
"Returns",
"the",
"current",
"user",
"from",
"the",
"session",
"data",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_auth/backend.py#L66-L87 | train | 215,908 |
openstack/horizon | openstack_auth/backend.py | KeystoneBackend.get_all_permissions | def get_all_permissions(self, user, obj=None):
"""Returns a set of permission strings that the user has.
This permission available to the user is derived from the user's
Keystone "roles".
The permissions are returned as ``"openstack.{{ role.name }}"``.
"""
if user.is_anonymous or obj is not None:
return set()
# TODO(gabrielhurley): Integrate policy-driven RBAC
# when supported by Keystone.
role_perms = {utils.get_role_permission(role['name'])
for role in user.roles}
services = []
for service in user.service_catalog:
try:
service_type = service['type']
except KeyError:
continue
service_regions = [utils.get_endpoint_region(endpoint) for endpoint
in service.get('endpoints', [])]
if user.services_region in service_regions:
services.append(service_type.lower())
service_perms = {"openstack.services.%s" % service
for service in services}
return role_perms | service_perms | python | def get_all_permissions(self, user, obj=None):
"""Returns a set of permission strings that the user has.
This permission available to the user is derived from the user's
Keystone "roles".
The permissions are returned as ``"openstack.{{ role.name }}"``.
"""
if user.is_anonymous or obj is not None:
return set()
# TODO(gabrielhurley): Integrate policy-driven RBAC
# when supported by Keystone.
role_perms = {utils.get_role_permission(role['name'])
for role in user.roles}
services = []
for service in user.service_catalog:
try:
service_type = service['type']
except KeyError:
continue
service_regions = [utils.get_endpoint_region(endpoint) for endpoint
in service.get('endpoints', [])]
if user.services_region in service_regions:
services.append(service_type.lower())
service_perms = {"openstack.services.%s" % service
for service in services}
return role_perms | service_perms | [
"def",
"get_all_permissions",
"(",
"self",
",",
"user",
",",
"obj",
"=",
"None",
")",
":",
"if",
"user",
".",
"is_anonymous",
"or",
"obj",
"is",
"not",
"None",
":",
"return",
"set",
"(",
")",
"# TODO(gabrielhurley): Integrate policy-driven RBAC",
"# ... | Returns a set of permission strings that the user has.
This permission available to the user is derived from the user's
Keystone "roles".
The permissions are returned as ``"openstack.{{ role.name }}"``. | [
"Returns",
"a",
"set",
"of",
"permission",
"strings",
"that",
"the",
"user",
"has",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_auth/backend.py#L240-L267 | train | 215,909 |
openstack/horizon | openstack_auth/backend.py | KeystoneBackend.has_perm | def has_perm(self, user, perm, obj=None):
"""Returns True if the given user has the specified permission."""
if not user.is_active:
return False
return perm in self.get_all_permissions(user, obj) | python | def has_perm(self, user, perm, obj=None):
"""Returns True if the given user has the specified permission."""
if not user.is_active:
return False
return perm in self.get_all_permissions(user, obj) | [
"def",
"has_perm",
"(",
"self",
",",
"user",
",",
"perm",
",",
"obj",
"=",
"None",
")",
":",
"if",
"not",
"user",
".",
"is_active",
":",
"return",
"False",
"return",
"perm",
"in",
"self",
".",
"get_all_permissions",
"(",
"user",
",",
"obj",
")"
] | Returns True if the given user has the specified permission. | [
"Returns",
"True",
"if",
"the",
"given",
"user",
"has",
"the",
"specified",
"permission",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_auth/backend.py#L269-L273 | train | 215,910 |
openstack/horizon | horizon/exceptions.py | handle | def handle(request, message=None, redirect=None, ignore=False,
escalate=False, log_level=None, force_log=None):
"""Centralized error handling for Horizon.
Because Horizon consumes so many different APIs with completely
different ``Exception`` types, it's necessary to have a centralized
place for handling exceptions which may be raised.
Exceptions are roughly divided into 3 types:
#. ``UNAUTHORIZED``: Errors resulting from authentication or authorization
problems. These result in being logged out and sent to the login screen.
#. ``NOT_FOUND``: Errors resulting from objects which could not be
located via the API. These generally result in a user-facing error
message, but are otherwise returned to the normal code flow. Optionally
a redirect value may be passed to the error handler so users are
returned to a different view than the one requested in addition to the
error message.
#. ``RECOVERABLE``: Generic API errors which generate a user-facing message
but drop directly back to the regular code flow.
All other exceptions bubble the stack as normal unless the ``ignore``
argument is passed in as ``True``, in which case only unrecognized
errors are bubbled.
If the exception is not re-raised, an appropriate wrapper exception
class indicating the type of exception that was encountered will be
returned.
"""
exc_type, exc_value, exc_traceback = sys.exc_info()
log_method = getattr(LOG, log_level or "exception")
force_log = force_log or os.environ.get("HORIZON_TEST_RUN", False)
force_silence = getattr(exc_value, "silence_logging", False)
# Because the same exception may travel through this method more than
# once (if it's re-raised) we may want to treat it differently
# the second time (e.g. no user messages/logging).
handled = issubclass(exc_type, HandledException)
wrap = False
# Restore our original exception information, but re-wrap it at the end
if handled:
exc_type, exc_value, exc_traceback = exc_value.wrapped
wrap = True
log_entry = encoding.force_text(exc_value)
user_message = ""
# We trust messages from our own exceptions
if issubclass(exc_type, HorizonException):
user_message = log_entry
# If the message has a placeholder for the exception, fill it in
elif message and "%(exc)s" in message:
user_message = encoding.force_text(message) % {"exc": log_entry}
elif message:
user_message = encoding.force_text(message)
for exc_handler in HANDLE_EXC_METHODS:
if issubclass(exc_type, exc_handler['exc']):
if exc_handler['set_wrap']:
wrap = True
handler = exc_handler['handler']
ret = handler(request, user_message, redirect, ignore,
exc_handler.get('escalate', escalate),
handled, force_silence, force_log,
log_method, log_entry, log_level)
if ret:
return ret # return to normal code flow
# If we've gotten here, time to wrap and/or raise our exception.
if wrap:
raise HandledException([exc_type, exc_value, exc_traceback])
# assume exceptions handled in the code that pass in a message are already
# handled appropriately and treat as recoverable
if message:
ret = handle_recoverable(request, user_message, redirect, ignore,
escalate, handled, force_silence, force_log,
log_method, log_entry, log_level)
# pylint: disable=using-constant-test
if ret:
return ret
six.reraise(exc_type, exc_value, exc_traceback) | python | def handle(request, message=None, redirect=None, ignore=False,
escalate=False, log_level=None, force_log=None):
"""Centralized error handling for Horizon.
Because Horizon consumes so many different APIs with completely
different ``Exception`` types, it's necessary to have a centralized
place for handling exceptions which may be raised.
Exceptions are roughly divided into 3 types:
#. ``UNAUTHORIZED``: Errors resulting from authentication or authorization
problems. These result in being logged out and sent to the login screen.
#. ``NOT_FOUND``: Errors resulting from objects which could not be
located via the API. These generally result in a user-facing error
message, but are otherwise returned to the normal code flow. Optionally
a redirect value may be passed to the error handler so users are
returned to a different view than the one requested in addition to the
error message.
#. ``RECOVERABLE``: Generic API errors which generate a user-facing message
but drop directly back to the regular code flow.
All other exceptions bubble the stack as normal unless the ``ignore``
argument is passed in as ``True``, in which case only unrecognized
errors are bubbled.
If the exception is not re-raised, an appropriate wrapper exception
class indicating the type of exception that was encountered will be
returned.
"""
exc_type, exc_value, exc_traceback = sys.exc_info()
log_method = getattr(LOG, log_level or "exception")
force_log = force_log or os.environ.get("HORIZON_TEST_RUN", False)
force_silence = getattr(exc_value, "silence_logging", False)
# Because the same exception may travel through this method more than
# once (if it's re-raised) we may want to treat it differently
# the second time (e.g. no user messages/logging).
handled = issubclass(exc_type, HandledException)
wrap = False
# Restore our original exception information, but re-wrap it at the end
if handled:
exc_type, exc_value, exc_traceback = exc_value.wrapped
wrap = True
log_entry = encoding.force_text(exc_value)
user_message = ""
# We trust messages from our own exceptions
if issubclass(exc_type, HorizonException):
user_message = log_entry
# If the message has a placeholder for the exception, fill it in
elif message and "%(exc)s" in message:
user_message = encoding.force_text(message) % {"exc": log_entry}
elif message:
user_message = encoding.force_text(message)
for exc_handler in HANDLE_EXC_METHODS:
if issubclass(exc_type, exc_handler['exc']):
if exc_handler['set_wrap']:
wrap = True
handler = exc_handler['handler']
ret = handler(request, user_message, redirect, ignore,
exc_handler.get('escalate', escalate),
handled, force_silence, force_log,
log_method, log_entry, log_level)
if ret:
return ret # return to normal code flow
# If we've gotten here, time to wrap and/or raise our exception.
if wrap:
raise HandledException([exc_type, exc_value, exc_traceback])
# assume exceptions handled in the code that pass in a message are already
# handled appropriately and treat as recoverable
if message:
ret = handle_recoverable(request, user_message, redirect, ignore,
escalate, handled, force_silence, force_log,
log_method, log_entry, log_level)
# pylint: disable=using-constant-test
if ret:
return ret
six.reraise(exc_type, exc_value, exc_traceback) | [
"def",
"handle",
"(",
"request",
",",
"message",
"=",
"None",
",",
"redirect",
"=",
"None",
",",
"ignore",
"=",
"False",
",",
"escalate",
"=",
"False",
",",
"log_level",
"=",
"None",
",",
"force_log",
"=",
"None",
")",
":",
"exc_type",
",",
"exc_value"... | Centralized error handling for Horizon.
Because Horizon consumes so many different APIs with completely
different ``Exception`` types, it's necessary to have a centralized
place for handling exceptions which may be raised.
Exceptions are roughly divided into 3 types:
#. ``UNAUTHORIZED``: Errors resulting from authentication or authorization
problems. These result in being logged out and sent to the login screen.
#. ``NOT_FOUND``: Errors resulting from objects which could not be
located via the API. These generally result in a user-facing error
message, but are otherwise returned to the normal code flow. Optionally
a redirect value may be passed to the error handler so users are
returned to a different view than the one requested in addition to the
error message.
#. ``RECOVERABLE``: Generic API errors which generate a user-facing message
but drop directly back to the regular code flow.
All other exceptions bubble the stack as normal unless the ``ignore``
argument is passed in as ``True``, in which case only unrecognized
errors are bubbled.
If the exception is not re-raised, an appropriate wrapper exception
class indicating the type of exception that was encountered will be
returned. | [
"Centralized",
"error",
"handling",
"for",
"Horizon",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/exceptions.py#L265-L348 | train | 215,911 |
openstack/horizon | openstack_dashboard/utils/config.py | load_config | def load_config(files=None, root_path=None, local_path=None):
"""Load the configuration from specified files."""
config = cfg.ConfigOpts()
config.register_opts([
cfg.Opt('root_path', default=root_path),
cfg.Opt('local_path', default=local_path),
])
# XXX register actual config groups here
# theme_group = config_theme.register_config(config)
if files is not None:
config(args=[], default_config_files=files)
return config | python | def load_config(files=None, root_path=None, local_path=None):
"""Load the configuration from specified files."""
config = cfg.ConfigOpts()
config.register_opts([
cfg.Opt('root_path', default=root_path),
cfg.Opt('local_path', default=local_path),
])
# XXX register actual config groups here
# theme_group = config_theme.register_config(config)
if files is not None:
config(args=[], default_config_files=files)
return config | [
"def",
"load_config",
"(",
"files",
"=",
"None",
",",
"root_path",
"=",
"None",
",",
"local_path",
"=",
"None",
")",
":",
"config",
"=",
"cfg",
".",
"ConfigOpts",
"(",
")",
"config",
".",
"register_opts",
"(",
"[",
"cfg",
".",
"Opt",
"(",
"'root_path'"... | Load the configuration from specified files. | [
"Load",
"the",
"configuration",
"from",
"specified",
"files",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/utils/config.py#L26-L38 | train | 215,912 |
openstack/horizon | openstack_dashboard/dashboards/identity/projects/tabs.py | UsersTab._update_user_roles_names_from_roles_id | def _update_user_roles_names_from_roles_id(self, user, users_roles,
roles_list):
"""Add roles names to user.roles, based on users_roles.
:param user: user to update
:param users_roles: list of roles ID
:param roles_list: list of roles obtained with keystone
"""
user_roles_names = [role.name for role in roles_list
if role.id in users_roles]
current_user_roles_names = set(getattr(user, "roles", []))
user.roles = list(current_user_roles_names.union(user_roles_names)) | python | def _update_user_roles_names_from_roles_id(self, user, users_roles,
roles_list):
"""Add roles names to user.roles, based on users_roles.
:param user: user to update
:param users_roles: list of roles ID
:param roles_list: list of roles obtained with keystone
"""
user_roles_names = [role.name for role in roles_list
if role.id in users_roles]
current_user_roles_names = set(getattr(user, "roles", []))
user.roles = list(current_user_roles_names.union(user_roles_names)) | [
"def",
"_update_user_roles_names_from_roles_id",
"(",
"self",
",",
"user",
",",
"users_roles",
",",
"roles_list",
")",
":",
"user_roles_names",
"=",
"[",
"role",
".",
"name",
"for",
"role",
"in",
"roles_list",
"if",
"role",
".",
"id",
"in",
"users_roles",
"]",... | Add roles names to user.roles, based on users_roles.
:param user: user to update
:param users_roles: list of roles ID
:param roles_list: list of roles obtained with keystone | [
"Add",
"roles",
"names",
"to",
"user",
".",
"roles",
"based",
"on",
"users_roles",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/dashboards/identity/projects/tabs.py#L76-L87 | train | 215,913 |
openstack/horizon | openstack_dashboard/dashboards/identity/projects/tabs.py | UsersTab._get_users_from_project | def _get_users_from_project(self, project_id, roles, project_users):
"""Update with users which have role on project NOT through a group.
:param project_id: ID of the project
:param roles: list of roles from keystone
:param project_users: list to be updated with the users found
"""
# For keystone.user_list project_id is not passed as argument because
# it is ignored when using admin credentials
# Get all users (to be able to find user name)
users = api.keystone.user_list(self.request)
users = {user.id: user for user in users}
# Get project_users_roles ({user_id: [role_id_1, role_id_2]})
project_users_roles = api.keystone.get_project_users_roles(
self.request,
project=project_id)
for user_id in project_users_roles:
if user_id not in project_users:
# Add user to the project_users
project_users[user_id] = users[user_id]
project_users[user_id].roles = []
project_users[user_id].roles_from_groups = []
# Update the project_user role in order to get:
# project_users[user_id].roles = [role_name1, role_name2]
self._update_user_roles_names_from_roles_id(
user=project_users[user_id],
users_roles=project_users_roles[user_id],
roles_list=roles
) | python | def _get_users_from_project(self, project_id, roles, project_users):
"""Update with users which have role on project NOT through a group.
:param project_id: ID of the project
:param roles: list of roles from keystone
:param project_users: list to be updated with the users found
"""
# For keystone.user_list project_id is not passed as argument because
# it is ignored when using admin credentials
# Get all users (to be able to find user name)
users = api.keystone.user_list(self.request)
users = {user.id: user for user in users}
# Get project_users_roles ({user_id: [role_id_1, role_id_2]})
project_users_roles = api.keystone.get_project_users_roles(
self.request,
project=project_id)
for user_id in project_users_roles:
if user_id not in project_users:
# Add user to the project_users
project_users[user_id] = users[user_id]
project_users[user_id].roles = []
project_users[user_id].roles_from_groups = []
# Update the project_user role in order to get:
# project_users[user_id].roles = [role_name1, role_name2]
self._update_user_roles_names_from_roles_id(
user=project_users[user_id],
users_roles=project_users_roles[user_id],
roles_list=roles
) | [
"def",
"_get_users_from_project",
"(",
"self",
",",
"project_id",
",",
"roles",
",",
"project_users",
")",
":",
"# For keystone.user_list project_id is not passed as argument because",
"# it is ignored when using admin credentials",
"# Get all users (to be able to find user name)",
"us... | Update with users which have role on project NOT through a group.
:param project_id: ID of the project
:param roles: list of roles from keystone
:param project_users: list to be updated with the users found | [
"Update",
"with",
"users",
"which",
"have",
"role",
"on",
"project",
"NOT",
"through",
"a",
"group",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/dashboards/identity/projects/tabs.py#L89-L122 | train | 215,914 |
openstack/horizon | openstack_dashboard/dashboards/identity/projects/tabs.py | UsersTab._get_users_from_groups | def _get_users_from_groups(self, project_id, roles, project_users):
"""Update with users which have role on project through a group.
:param project_id: ID of the project
:param roles: list of roles from keystone
:param project_users: list to be updated with the users found
"""
# For keystone.group_list project_id is not passed as argument because
# it is ignored when using admin credentials
# Get all groups (to be able to find group name)
groups = api.keystone.group_list(self.request)
group_names = {group.id: group.name for group in groups}
# Get a dictionary {group_id: [role_id_1, role_id_2]}
project_groups_roles = api.keystone.get_project_groups_roles(
self.request,
project=project_id)
for group_id in project_groups_roles:
group_users = api.keystone.user_list(self.request,
group=group_id)
group_roles_names = [
role.name for role in roles
if role.id in project_groups_roles[group_id]]
roles_from_group = [(role_name, group_names[group_id])
for role_name in group_roles_names]
for user in group_users:
if user.id not in project_users:
# New user: Add the user to the list
project_users[user.id] = user
project_users[user.id].roles = []
project_users[user.id].roles_from_groups = []
# Add roles from group
project_users[user.id].roles_from_groups.extend(
roles_from_group) | python | def _get_users_from_groups(self, project_id, roles, project_users):
"""Update with users which have role on project through a group.
:param project_id: ID of the project
:param roles: list of roles from keystone
:param project_users: list to be updated with the users found
"""
# For keystone.group_list project_id is not passed as argument because
# it is ignored when using admin credentials
# Get all groups (to be able to find group name)
groups = api.keystone.group_list(self.request)
group_names = {group.id: group.name for group in groups}
# Get a dictionary {group_id: [role_id_1, role_id_2]}
project_groups_roles = api.keystone.get_project_groups_roles(
self.request,
project=project_id)
for group_id in project_groups_roles:
group_users = api.keystone.user_list(self.request,
group=group_id)
group_roles_names = [
role.name for role in roles
if role.id in project_groups_roles[group_id]]
roles_from_group = [(role_name, group_names[group_id])
for role_name in group_roles_names]
for user in group_users:
if user.id not in project_users:
# New user: Add the user to the list
project_users[user.id] = user
project_users[user.id].roles = []
project_users[user.id].roles_from_groups = []
# Add roles from group
project_users[user.id].roles_from_groups.extend(
roles_from_group) | [
"def",
"_get_users_from_groups",
"(",
"self",
",",
"project_id",
",",
"roles",
",",
"project_users",
")",
":",
"# For keystone.group_list project_id is not passed as argument because",
"# it is ignored when using admin credentials",
"# Get all groups (to be able to find group name)",
"... | Update with users which have role on project through a group.
:param project_id: ID of the project
:param roles: list of roles from keystone
:param project_users: list to be updated with the users found | [
"Update",
"with",
"users",
"which",
"have",
"role",
"on",
"project",
"through",
"a",
"group",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/dashboards/identity/projects/tabs.py#L124-L162 | train | 215,915 |
openstack/horizon | openstack_dashboard/dashboards/identity/projects/tabs.py | UsersTab.get_userstable_data | def get_userstable_data(self):
"""Get users with roles on the project.
Roles can be applied directly on the project or through a group.
"""
project_users = {}
project = self.tab_group.kwargs['project']
try:
# Get all global roles once to avoid multiple requests.
roles = api.keystone.role_list(self.request)
# Update project_users with users which have role directly on
# the project, (NOT through a group)
self._get_users_from_project(project_id=project.id,
roles=roles,
project_users=project_users)
# Update project_users with users which have role indirectly on
# the project, (through a group)
self._get_users_from_groups(project_id=project.id,
roles=roles,
project_users=project_users)
except Exception:
exceptions.handle(self.request,
_("Unable to display the users of this project.")
)
return project_users.values() | python | def get_userstable_data(self):
"""Get users with roles on the project.
Roles can be applied directly on the project or through a group.
"""
project_users = {}
project = self.tab_group.kwargs['project']
try:
# Get all global roles once to avoid multiple requests.
roles = api.keystone.role_list(self.request)
# Update project_users with users which have role directly on
# the project, (NOT through a group)
self._get_users_from_project(project_id=project.id,
roles=roles,
project_users=project_users)
# Update project_users with users which have role indirectly on
# the project, (through a group)
self._get_users_from_groups(project_id=project.id,
roles=roles,
project_users=project_users)
except Exception:
exceptions.handle(self.request,
_("Unable to display the users of this project.")
)
return project_users.values() | [
"def",
"get_userstable_data",
"(",
"self",
")",
":",
"project_users",
"=",
"{",
"}",
"project",
"=",
"self",
".",
"tab_group",
".",
"kwargs",
"[",
"'project'",
"]",
"try",
":",
"# Get all global roles once to avoid multiple requests.",
"roles",
"=",
"api",
".",
... | Get users with roles on the project.
Roles can be applied directly on the project or through a group. | [
"Get",
"users",
"with",
"roles",
"on",
"the",
"project",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/dashboards/identity/projects/tabs.py#L164-L193 | train | 215,916 |
openstack/horizon | openstack_dashboard/api/swift.py | _objectify | def _objectify(items, container_name):
"""Splits a listing of objects into their appropriate wrapper classes."""
objects = []
# Deal with objects and object pseudo-folders first, save subdirs for later
for item in items:
if item.get("subdir", None) is not None:
object_cls = PseudoFolder
else:
object_cls = StorageObject
objects.append(object_cls(item, container_name))
return objects | python | def _objectify(items, container_name):
"""Splits a listing of objects into their appropriate wrapper classes."""
objects = []
# Deal with objects and object pseudo-folders first, save subdirs for later
for item in items:
if item.get("subdir", None) is not None:
object_cls = PseudoFolder
else:
object_cls = StorageObject
objects.append(object_cls(item, container_name))
return objects | [
"def",
"_objectify",
"(",
"items",
",",
"container_name",
")",
":",
"objects",
"=",
"[",
"]",
"# Deal with objects and object pseudo-folders first, save subdirs for later",
"for",
"item",
"in",
"items",
":",
"if",
"item",
".",
"get",
"(",
"\"subdir\"",
",",
"None",
... | Splits a listing of objects into their appropriate wrapper classes. | [
"Splits",
"a",
"listing",
"of",
"objects",
"into",
"their",
"appropriate",
"wrapper",
"classes",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/swift.py#L91-L104 | train | 215,917 |
openstack/horizon | openstack_dashboard/utils/config_types.py | Literal.validate | def validate(self, result, spec): # noqa Yes, it's too complex.
"""Validate that the result has the correct structure."""
if spec is None:
# None matches anything.
return
if isinstance(spec, dict):
if not isinstance(result, dict):
raise ValueError('Dictionary expected, but %r found.' % result)
if spec:
spec_value = next(iter(spec.values())) # Yay Python 3!
for value in result.values():
self.validate(value, spec_value)
spec_key = next(iter(spec.keys()))
for key in result:
self.validate(key, spec_key)
if isinstance(spec, list):
if not isinstance(result, list):
raise ValueError('List expected, but %r found.' % result)
if spec:
for value in result:
self.validate(value, spec[0])
if isinstance(spec, tuple):
if not isinstance(result, tuple):
raise ValueError('Tuple expected, but %r found.' % result)
if len(result) != len(spec):
raise ValueError('Expected %d elements in tuple %r.' %
(len(spec), result))
for s, value in zip(spec, result):
self.validate(value, s)
if isinstance(spec, six.string_types):
if not isinstance(result, six.string_types):
raise ValueError('String expected, but %r found.' % result)
if isinstance(spec, int):
if not isinstance(result, int):
raise ValueError('Integer expected, but %r found.' % result)
if isinstance(spec, bool):
if not isinstance(result, bool):
raise ValueError('Boolean expected, but %r found.' % result) | python | def validate(self, result, spec): # noqa Yes, it's too complex.
"""Validate that the result has the correct structure."""
if spec is None:
# None matches anything.
return
if isinstance(spec, dict):
if not isinstance(result, dict):
raise ValueError('Dictionary expected, but %r found.' % result)
if spec:
spec_value = next(iter(spec.values())) # Yay Python 3!
for value in result.values():
self.validate(value, spec_value)
spec_key = next(iter(spec.keys()))
for key in result:
self.validate(key, spec_key)
if isinstance(spec, list):
if not isinstance(result, list):
raise ValueError('List expected, but %r found.' % result)
if spec:
for value in result:
self.validate(value, spec[0])
if isinstance(spec, tuple):
if not isinstance(result, tuple):
raise ValueError('Tuple expected, but %r found.' % result)
if len(result) != len(spec):
raise ValueError('Expected %d elements in tuple %r.' %
(len(spec), result))
for s, value in zip(spec, result):
self.validate(value, s)
if isinstance(spec, six.string_types):
if not isinstance(result, six.string_types):
raise ValueError('String expected, but %r found.' % result)
if isinstance(spec, int):
if not isinstance(result, int):
raise ValueError('Integer expected, but %r found.' % result)
if isinstance(spec, bool):
if not isinstance(result, bool):
raise ValueError('Boolean expected, but %r found.' % result) | [
"def",
"validate",
"(",
"self",
",",
"result",
",",
"spec",
")",
":",
"# noqa Yes, it's too complex.",
"if",
"spec",
"is",
"None",
":",
"# None matches anything.",
"return",
"if",
"isinstance",
"(",
"spec",
",",
"dict",
")",
":",
"if",
"not",
"isinstance",
"... | Validate that the result has the correct structure. | [
"Validate",
"that",
"the",
"result",
"has",
"the",
"correct",
"structure",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/utils/config_types.py#L117-L154 | train | 215,918 |
openstack/horizon | openstack_dashboard/utils/config_types.py | Literal.update | def update(self, result, spec):
"""Replace elements with results of calling callables."""
if isinstance(spec, dict):
if spec:
spec_value = next(iter(spec.values()))
for key, value in result.items():
result[key] = self.update(value, spec_value)
if isinstance(spec, list):
if spec:
for i, value in enumerate(result):
result[i] = self.update(value, spec[0])
if isinstance(spec, tuple):
return tuple(self.update(value, s)
for s, value in zip(spec, result))
if callable(spec):
return spec(result)
return result | python | def update(self, result, spec):
"""Replace elements with results of calling callables."""
if isinstance(spec, dict):
if spec:
spec_value = next(iter(spec.values()))
for key, value in result.items():
result[key] = self.update(value, spec_value)
if isinstance(spec, list):
if spec:
for i, value in enumerate(result):
result[i] = self.update(value, spec[0])
if isinstance(spec, tuple):
return tuple(self.update(value, s)
for s, value in zip(spec, result))
if callable(spec):
return spec(result)
return result | [
"def",
"update",
"(",
"self",
",",
"result",
",",
"spec",
")",
":",
"if",
"isinstance",
"(",
"spec",
",",
"dict",
")",
":",
"if",
"spec",
":",
"spec_value",
"=",
"next",
"(",
"iter",
"(",
"spec",
".",
"values",
"(",
")",
")",
")",
"for",
"key",
... | Replace elements with results of calling callables. | [
"Replace",
"elements",
"with",
"results",
"of",
"calling",
"callables",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/utils/config_types.py#L156-L172 | train | 215,919 |
openstack/horizon | openstack_dashboard/dashboards/project/images/utils.py | get_available_images | def get_available_images(request, project_id=None, images_cache=None):
"""Returns a list of available images
Returns a list of images that are public, shared, community or owned by
the given project_id. If project_id is not specified, only public and
community images are returned.
:param images_cache: An optional dict-like object in which to
cache public and per-project id image metadata.
"""
if images_cache is None:
images_cache = {}
public_images = images_cache.get('public_images', [])
community_images = images_cache.get('community_images', [])
images_by_project = images_cache.get('images_by_project', {})
shared_images = images_cache.get('shared_images', [])
if 'public_images' not in images_cache:
public = {"is_public": True,
"status": "active"}
try:
images, _more, _prev = glance.image_list_detailed(
request, filters=public)
public_images += images
images_cache['public_images'] = public_images
except Exception:
exceptions.handle(request,
_("Unable to retrieve public images."))
# Preempt if we don't have a project_id yet.
if project_id is None:
images_by_project[project_id] = []
if project_id not in images_by_project:
owner = {"property-owner_id": project_id,
"status": "active"}
try:
owned_images, _more, _prev = glance.image_list_detailed(
request, filters=owner)
images_by_project[project_id] = owned_images
except Exception:
owned_images = []
exceptions.handle(request,
_("Unable to retrieve images for "
"the current project."))
else:
owned_images = images_by_project[project_id]
if 'community_images' not in images_cache:
community = {"visibility": "community",
"status": "active"}
try:
images, _more, _prev = glance.image_list_detailed(
request, filters=community)
community_images += images
images_cache['community_images'] = community_images
except Exception:
exceptions.handle(request,
_("Unable to retrieve community images."))
if 'shared_images' not in images_cache:
shared = {"visibility": "shared",
"status": "active"}
try:
shared_images, _more, _prev = \
glance.image_list_detailed(request, filters=shared)
images_cache['shared_images'] = shared_images
except Exception:
exceptions.handle(request,
_("Unable to retrieve shared images."))
if 'images_by_project' not in images_cache:
images_cache['images_by_project'] = images_by_project
images = owned_images + public_images + community_images + shared_images
image_ids = []
final_images = []
for image in images:
if image.id not in image_ids and \
image.container_format not in ('aki', 'ari'):
image_ids.append(image.id)
final_images.append(image)
return final_images | python | def get_available_images(request, project_id=None, images_cache=None):
"""Returns a list of available images
Returns a list of images that are public, shared, community or owned by
the given project_id. If project_id is not specified, only public and
community images are returned.
:param images_cache: An optional dict-like object in which to
cache public and per-project id image metadata.
"""
if images_cache is None:
images_cache = {}
public_images = images_cache.get('public_images', [])
community_images = images_cache.get('community_images', [])
images_by_project = images_cache.get('images_by_project', {})
shared_images = images_cache.get('shared_images', [])
if 'public_images' not in images_cache:
public = {"is_public": True,
"status": "active"}
try:
images, _more, _prev = glance.image_list_detailed(
request, filters=public)
public_images += images
images_cache['public_images'] = public_images
except Exception:
exceptions.handle(request,
_("Unable to retrieve public images."))
# Preempt if we don't have a project_id yet.
if project_id is None:
images_by_project[project_id] = []
if project_id not in images_by_project:
owner = {"property-owner_id": project_id,
"status": "active"}
try:
owned_images, _more, _prev = glance.image_list_detailed(
request, filters=owner)
images_by_project[project_id] = owned_images
except Exception:
owned_images = []
exceptions.handle(request,
_("Unable to retrieve images for "
"the current project."))
else:
owned_images = images_by_project[project_id]
if 'community_images' not in images_cache:
community = {"visibility": "community",
"status": "active"}
try:
images, _more, _prev = glance.image_list_detailed(
request, filters=community)
community_images += images
images_cache['community_images'] = community_images
except Exception:
exceptions.handle(request,
_("Unable to retrieve community images."))
if 'shared_images' not in images_cache:
shared = {"visibility": "shared",
"status": "active"}
try:
shared_images, _more, _prev = \
glance.image_list_detailed(request, filters=shared)
images_cache['shared_images'] = shared_images
except Exception:
exceptions.handle(request,
_("Unable to retrieve shared images."))
if 'images_by_project' not in images_cache:
images_cache['images_by_project'] = images_by_project
images = owned_images + public_images + community_images + shared_images
image_ids = []
final_images = []
for image in images:
if image.id not in image_ids and \
image.container_format not in ('aki', 'ari'):
image_ids.append(image.id)
final_images.append(image)
return final_images | [
"def",
"get_available_images",
"(",
"request",
",",
"project_id",
"=",
"None",
",",
"images_cache",
"=",
"None",
")",
":",
"if",
"images_cache",
"is",
"None",
":",
"images_cache",
"=",
"{",
"}",
"public_images",
"=",
"images_cache",
".",
"get",
"(",
"'public... | Returns a list of available images
Returns a list of images that are public, shared, community or owned by
the given project_id. If project_id is not specified, only public and
community images are returned.
:param images_cache: An optional dict-like object in which to
cache public and per-project id image metadata. | [
"Returns",
"a",
"list",
"of",
"available",
"images"
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/dashboards/project/images/utils.py#L21-L104 | train | 215,920 |
openstack/horizon | openstack_dashboard/dashboards/project/images/utils.py | image_field_data | def image_field_data(request, include_empty_option=False):
"""Returns a list of tuples of all images.
Generates a sorted list of images available. And returns a list of
(id, name) tuples.
:param request: django http request object
:param include_empty_option: flag to include a empty tuple in the front of
the list
:return: list of (id, name) tuples
"""
try:
images = get_available_images(request, request.user.project_id)
except Exception:
exceptions.handle(request, _('Unable to retrieve images'))
images.sort(key=lambda c: c.name)
images_list = [('', _('Select Image'))]
for image in images:
image_label = u"{} ({})".format(image.name, filesizeformat(image.size))
images_list.append((image.id, image_label))
if not images:
return [("", _("No images available")), ]
return images_list | python | def image_field_data(request, include_empty_option=False):
"""Returns a list of tuples of all images.
Generates a sorted list of images available. And returns a list of
(id, name) tuples.
:param request: django http request object
:param include_empty_option: flag to include a empty tuple in the front of
the list
:return: list of (id, name) tuples
"""
try:
images = get_available_images(request, request.user.project_id)
except Exception:
exceptions.handle(request, _('Unable to retrieve images'))
images.sort(key=lambda c: c.name)
images_list = [('', _('Select Image'))]
for image in images:
image_label = u"{} ({})".format(image.name, filesizeformat(image.size))
images_list.append((image.id, image_label))
if not images:
return [("", _("No images available")), ]
return images_list | [
"def",
"image_field_data",
"(",
"request",
",",
"include_empty_option",
"=",
"False",
")",
":",
"try",
":",
"images",
"=",
"get_available_images",
"(",
"request",
",",
"request",
".",
"user",
".",
"project_id",
")",
"except",
"Exception",
":",
"exceptions",
".... | Returns a list of tuples of all images.
Generates a sorted list of images available. And returns a list of
(id, name) tuples.
:param request: django http request object
:param include_empty_option: flag to include a empty tuple in the front of
the list
:return: list of (id, name) tuples | [
"Returns",
"a",
"list",
"of",
"tuples",
"of",
"all",
"images",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/dashboards/project/images/utils.py#L107-L133 | train | 215,921 |
openstack/horizon | horizon/templatetags/horizon.py | horizon_main_nav | def horizon_main_nav(context):
"""Generates top-level dashboard navigation entries."""
if 'request' not in context:
return {}
current_dashboard = context['request'].horizon.get('dashboard', None)
dashboards = []
for dash in Horizon.get_dashboards():
if dash.can_access(context):
if callable(dash.nav) and dash.nav(context):
dashboards.append(dash)
elif dash.nav:
dashboards.append(dash)
return {'components': dashboards,
'user': context['request'].user,
'current': current_dashboard,
'request': context['request']} | python | def horizon_main_nav(context):
"""Generates top-level dashboard navigation entries."""
if 'request' not in context:
return {}
current_dashboard = context['request'].horizon.get('dashboard', None)
dashboards = []
for dash in Horizon.get_dashboards():
if dash.can_access(context):
if callable(dash.nav) and dash.nav(context):
dashboards.append(dash)
elif dash.nav:
dashboards.append(dash)
return {'components': dashboards,
'user': context['request'].user,
'current': current_dashboard,
'request': context['request']} | [
"def",
"horizon_main_nav",
"(",
"context",
")",
":",
"if",
"'request'",
"not",
"in",
"context",
":",
"return",
"{",
"}",
"current_dashboard",
"=",
"context",
"[",
"'request'",
"]",
".",
"horizon",
".",
"get",
"(",
"'dashboard'",
",",
"None",
")",
"dashboar... | Generates top-level dashboard navigation entries. | [
"Generates",
"top",
"-",
"level",
"dashboard",
"navigation",
"entries",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/templatetags/horizon.py#L95-L110 | train | 215,922 |
openstack/horizon | horizon/templatetags/horizon.py | horizon_dashboard_nav | def horizon_dashboard_nav(context):
"""Generates sub-navigation entries for the current dashboard."""
if 'request' not in context:
return {}
dashboard = context['request'].horizon['dashboard']
panel_groups = dashboard.get_panel_groups()
non_empty_groups = []
for group in panel_groups.values():
allowed_panels = []
for panel in group:
if (callable(panel.nav) and panel.nav(context) and
panel.can_access(context)):
allowed_panels.append(panel)
elif (not callable(panel.nav) and panel.nav and
panel.can_access(context)):
allowed_panels.append(panel)
if allowed_panels:
if group.name is None:
non_empty_groups.append((dashboard.name, allowed_panels))
else:
non_empty_groups.append((group.name, allowed_panels))
return {'components': OrderedDict(non_empty_groups),
'user': context['request'].user,
'current': context['request'].horizon['panel'].slug,
'request': context['request']} | python | def horizon_dashboard_nav(context):
"""Generates sub-navigation entries for the current dashboard."""
if 'request' not in context:
return {}
dashboard = context['request'].horizon['dashboard']
panel_groups = dashboard.get_panel_groups()
non_empty_groups = []
for group in panel_groups.values():
allowed_panels = []
for panel in group:
if (callable(panel.nav) and panel.nav(context) and
panel.can_access(context)):
allowed_panels.append(panel)
elif (not callable(panel.nav) and panel.nav and
panel.can_access(context)):
allowed_panels.append(panel)
if allowed_panels:
if group.name is None:
non_empty_groups.append((dashboard.name, allowed_panels))
else:
non_empty_groups.append((group.name, allowed_panels))
return {'components': OrderedDict(non_empty_groups),
'user': context['request'].user,
'current': context['request'].horizon['panel'].slug,
'request': context['request']} | [
"def",
"horizon_dashboard_nav",
"(",
"context",
")",
":",
"if",
"'request'",
"not",
"in",
"context",
":",
"return",
"{",
"}",
"dashboard",
"=",
"context",
"[",
"'request'",
"]",
".",
"horizon",
"[",
"'dashboard'",
"]",
"panel_groups",
"=",
"dashboard",
".",
... | Generates sub-navigation entries for the current dashboard. | [
"Generates",
"sub",
"-",
"navigation",
"entries",
"for",
"the",
"current",
"dashboard",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/templatetags/horizon.py#L114-L140 | train | 215,923 |
openstack/horizon | horizon/templatetags/horizon.py | jstemplate | def jstemplate(parser, token):
"""Templatetag to handle any of the Mustache-based templates.
Replaces ``[[[`` and ``]]]`` with ``{{{`` and ``}}}``,
``[[`` and ``]]`` with ``{{`` and ``}}`` and
``[%`` and ``%]`` with ``{%`` and ``%}`` to avoid conflicts
with Django's template engine when using any of the Mustache-based
templating libraries.
"""
nodelist = parser.parse(('endjstemplate',))
parser.delete_first_token()
return JSTemplateNode(nodelist) | python | def jstemplate(parser, token):
"""Templatetag to handle any of the Mustache-based templates.
Replaces ``[[[`` and ``]]]`` with ``{{{`` and ``}}}``,
``[[`` and ``]]`` with ``{{`` and ``}}`` and
``[%`` and ``%]`` with ``{%`` and ``%}`` to avoid conflicts
with Django's template engine when using any of the Mustache-based
templating libraries.
"""
nodelist = parser.parse(('endjstemplate',))
parser.delete_first_token()
return JSTemplateNode(nodelist) | [
"def",
"jstemplate",
"(",
"parser",
",",
"token",
")",
":",
"nodelist",
"=",
"parser",
".",
"parse",
"(",
"(",
"'endjstemplate'",
",",
")",
")",
"parser",
".",
"delete_first_token",
"(",
")",
"return",
"JSTemplateNode",
"(",
"nodelist",
")"
] | Templatetag to handle any of the Mustache-based templates.
Replaces ``[[[`` and ``]]]`` with ``{{{`` and ``}}}``,
``[[`` and ``]]`` with ``{{`` and ``}}`` and
``[%`` and ``%]`` with ``{%`` and ``%}`` to avoid conflicts
with Django's template engine when using any of the Mustache-based
templating libraries. | [
"Templatetag",
"to",
"handle",
"any",
"of",
"the",
"Mustache",
"-",
"based",
"templates",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/templatetags/horizon.py#L188-L199 | train | 215,924 |
openstack/horizon | horizon/templatetags/horizon.py | minifyspace | def minifyspace(parser, token):
"""Removes whitespace including tab and newline characters.
Do not use this if you are using a <pre> tag.
Example usage::
{% minifyspace %}
<p>
<a title="foo"
href="foo/">
Foo
</a>
</p>
{% endminifyspace %}
This example would return this HTML::
<p><a title="foo" href="foo/">Foo</a></p>
"""
nodelist = parser.parse(('endminifyspace',))
parser.delete_first_token()
return MinifiedNode(nodelist) | python | def minifyspace(parser, token):
"""Removes whitespace including tab and newline characters.
Do not use this if you are using a <pre> tag.
Example usage::
{% minifyspace %}
<p>
<a title="foo"
href="foo/">
Foo
</a>
</p>
{% endminifyspace %}
This example would return this HTML::
<p><a title="foo" href="foo/">Foo</a></p>
"""
nodelist = parser.parse(('endminifyspace',))
parser.delete_first_token()
return MinifiedNode(nodelist) | [
"def",
"minifyspace",
"(",
"parser",
",",
"token",
")",
":",
"nodelist",
"=",
"parser",
".",
"parse",
"(",
"(",
"'endminifyspace'",
",",
")",
")",
"parser",
".",
"delete_first_token",
"(",
")",
"return",
"MinifiedNode",
"(",
"nodelist",
")"
] | Removes whitespace including tab and newline characters.
Do not use this if you are using a <pre> tag.
Example usage::
{% minifyspace %}
<p>
<a title="foo"
href="foo/">
Foo
</a>
</p>
{% endminifyspace %}
This example would return this HTML::
<p><a title="foo" href="foo/">Foo</a></p> | [
"Removes",
"whitespace",
"including",
"tab",
"and",
"newline",
"characters",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/templatetags/horizon.py#L220-L243 | train | 215,925 |
openstack/horizon | horizon/notifications.py | process_message_notification | def process_message_notification(request, messages_path):
"""Process all the msg file found in the message directory"""
if not messages_path:
return
global _MESSAGES_CACHE
global _MESSAGES_MTIME
# NOTE (lhcheng): Cache the processed messages to avoid parsing
# the files every time. Check directory modification time if
# reload is necessary.
if (_MESSAGES_CACHE is None or
_MESSAGES_MTIME != os.path.getmtime(messages_path)):
_MESSAGES_CACHE = _get_processed_messages(messages_path)
_MESSAGES_MTIME = os.path.getmtime(messages_path)
for msg in _MESSAGES_CACHE:
msg.send_message(request) | python | def process_message_notification(request, messages_path):
"""Process all the msg file found in the message directory"""
if not messages_path:
return
global _MESSAGES_CACHE
global _MESSAGES_MTIME
# NOTE (lhcheng): Cache the processed messages to avoid parsing
# the files every time. Check directory modification time if
# reload is necessary.
if (_MESSAGES_CACHE is None or
_MESSAGES_MTIME != os.path.getmtime(messages_path)):
_MESSAGES_CACHE = _get_processed_messages(messages_path)
_MESSAGES_MTIME = os.path.getmtime(messages_path)
for msg in _MESSAGES_CACHE:
msg.send_message(request) | [
"def",
"process_message_notification",
"(",
"request",
",",
"messages_path",
")",
":",
"if",
"not",
"messages_path",
":",
"return",
"global",
"_MESSAGES_CACHE",
"global",
"_MESSAGES_MTIME",
"# NOTE (lhcheng): Cache the processed messages to avoid parsing",
"# the files every time... | Process all the msg file found in the message directory | [
"Process",
"all",
"the",
"msg",
"file",
"found",
"in",
"the",
"message",
"directory"
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/notifications.py#L132-L149 | train | 215,926 |
openstack/horizon | horizon/notifications.py | JSONMessage.load | def load(self):
"""Read and parse the message file."""
try:
self._read()
self._parse()
except Exception as exc:
self.failed = True
params = {'path': self._path, 'exception': exc}
if self.fail_silently:
LOG.warning("Error processing message json file '%(path)s': "
"%(exception)s", params)
else:
raise exceptions.MessageFailure(
_("Error processing message json file '%(path)s': "
"%(exception)s") % params) | python | def load(self):
"""Read and parse the message file."""
try:
self._read()
self._parse()
except Exception as exc:
self.failed = True
params = {'path': self._path, 'exception': exc}
if self.fail_silently:
LOG.warning("Error processing message json file '%(path)s': "
"%(exception)s", params)
else:
raise exceptions.MessageFailure(
_("Error processing message json file '%(path)s': "
"%(exception)s") % params) | [
"def",
"load",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"_read",
"(",
")",
"self",
".",
"_parse",
"(",
")",
"except",
"Exception",
"as",
"exc",
":",
"self",
".",
"failed",
"=",
"True",
"params",
"=",
"{",
"'path'",
":",
"self",
".",
"_path... | Read and parse the message file. | [
"Read",
"and",
"parse",
"the",
"message",
"file",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/notifications.py#L85-L100 | train | 215,927 |
openstack/horizon | horizon/tables/views.py | MultiTableMixin.handle_server_filter | def handle_server_filter(self, request, table=None):
"""Update the table server filter information in the session.
Returns True if the filter has been changed.
"""
if not table:
table = self.get_table()
filter_info = self.get_server_filter_info(request, table)
if filter_info is None:
return False
request.session[filter_info['value_param']] = filter_info['value']
if filter_info['field_param']:
request.session[filter_info['field_param']] = filter_info['field']
return filter_info['changed'] | python | def handle_server_filter(self, request, table=None):
"""Update the table server filter information in the session.
Returns True if the filter has been changed.
"""
if not table:
table = self.get_table()
filter_info = self.get_server_filter_info(request, table)
if filter_info is None:
return False
request.session[filter_info['value_param']] = filter_info['value']
if filter_info['field_param']:
request.session[filter_info['field_param']] = filter_info['field']
return filter_info['changed'] | [
"def",
"handle_server_filter",
"(",
"self",
",",
"request",
",",
"table",
"=",
"None",
")",
":",
"if",
"not",
"table",
":",
"table",
"=",
"self",
".",
"get_table",
"(",
")",
"filter_info",
"=",
"self",
".",
"get_server_filter_info",
"(",
"request",
",",
... | Update the table server filter information in the session.
Returns True if the filter has been changed. | [
"Update",
"the",
"table",
"server",
"filter",
"information",
"in",
"the",
"session",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/tables/views.py#L160-L173 | train | 215,928 |
openstack/horizon | horizon/tables/views.py | MultiTableMixin.update_server_filter_action | def update_server_filter_action(self, request, table=None):
"""Update the table server side filter action.
It is done based on the current filter. The filter info may be stored
in the session and this will restore it.
"""
if not table:
table = self.get_table()
filter_info = self.get_server_filter_info(request, table)
if filter_info is not None:
action = filter_info['action']
setattr(action, 'filter_string', filter_info['value'])
if filter_info['field_param']:
setattr(action, 'filter_field', filter_info['field']) | python | def update_server_filter_action(self, request, table=None):
"""Update the table server side filter action.
It is done based on the current filter. The filter info may be stored
in the session and this will restore it.
"""
if not table:
table = self.get_table()
filter_info = self.get_server_filter_info(request, table)
if filter_info is not None:
action = filter_info['action']
setattr(action, 'filter_string', filter_info['value'])
if filter_info['field_param']:
setattr(action, 'filter_field', filter_info['field']) | [
"def",
"update_server_filter_action",
"(",
"self",
",",
"request",
",",
"table",
"=",
"None",
")",
":",
"if",
"not",
"table",
":",
"table",
"=",
"self",
".",
"get_table",
"(",
")",
"filter_info",
"=",
"self",
".",
"get_server_filter_info",
"(",
"request",
... | Update the table server side filter action.
It is done based on the current filter. The filter info may be stored
in the session and this will restore it. | [
"Update",
"the",
"table",
"server",
"side",
"filter",
"action",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/tables/views.py#L175-L188 | train | 215,929 |
openstack/horizon | horizon/tables/views.py | DataTableView.get_filters | def get_filters(self, filters=None, filters_map=None):
"""Converts a string given by the user into a valid api filter value.
:filters: Default filter values.
{'filter1': filter_value, 'filter2': filter_value}
:filters_map: mapping between user input and valid api filter values.
{'filter_name':{_("true_value"):True, _("false_value"):False}
"""
filters = filters or {}
filters_map = filters_map or {}
filter_action = self.table._meta._filter_action
if filter_action:
filter_field = self.table.get_filter_field()
if filter_action.is_api_filter(filter_field):
filter_string = self.table.get_filter_string().strip()
if filter_field and filter_string:
filter_map = filters_map.get(filter_field, {})
filters[filter_field] = filter_string
for k, v in filter_map.items():
# k is django.utils.functional.__proxy__
# and could not be searched in dict
if filter_string.lower() == k:
filters[filter_field] = v
break
return filters | python | def get_filters(self, filters=None, filters_map=None):
"""Converts a string given by the user into a valid api filter value.
:filters: Default filter values.
{'filter1': filter_value, 'filter2': filter_value}
:filters_map: mapping between user input and valid api filter values.
{'filter_name':{_("true_value"):True, _("false_value"):False}
"""
filters = filters or {}
filters_map = filters_map or {}
filter_action = self.table._meta._filter_action
if filter_action:
filter_field = self.table.get_filter_field()
if filter_action.is_api_filter(filter_field):
filter_string = self.table.get_filter_string().strip()
if filter_field and filter_string:
filter_map = filters_map.get(filter_field, {})
filters[filter_field] = filter_string
for k, v in filter_map.items():
# k is django.utils.functional.__proxy__
# and could not be searched in dict
if filter_string.lower() == k:
filters[filter_field] = v
break
return filters | [
"def",
"get_filters",
"(",
"self",
",",
"filters",
"=",
"None",
",",
"filters_map",
"=",
"None",
")",
":",
"filters",
"=",
"filters",
"or",
"{",
"}",
"filters_map",
"=",
"filters_map",
"or",
"{",
"}",
"filter_action",
"=",
"self",
".",
"table",
".",
"_... | Converts a string given by the user into a valid api filter value.
:filters: Default filter values.
{'filter1': filter_value, 'filter2': filter_value}
:filters_map: mapping between user input and valid api filter values.
{'filter_name':{_("true_value"):True, _("false_value"):False} | [
"Converts",
"a",
"string",
"given",
"by",
"the",
"user",
"into",
"a",
"valid",
"api",
"filter",
"value",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/tables/views.py#L290-L314 | train | 215,930 |
openstack/horizon | openstack_dashboard/dashboards/project/networks/workflows.py | CreateNetwork._setup_subnet_parameters | def _setup_subnet_parameters(self, params, data, is_create=True):
"""Setup subnet parameters
This methods setups subnet parameters which are available
in both create and update.
"""
is_update = not is_create
params['enable_dhcp'] = data['enable_dhcp']
if int(data['ip_version']) == 6:
ipv6_modes = utils.get_ipv6_modes_attrs_from_menu(
data['ipv6_modes'])
if ipv6_modes[0] and is_create:
params['ipv6_ra_mode'] = ipv6_modes[0]
if ipv6_modes[1] and is_create:
params['ipv6_address_mode'] = ipv6_modes[1]
if data['allocation_pools']:
pools = [dict(zip(['start', 'end'], pool.strip().split(',')))
for pool in data['allocation_pools'].splitlines()
if pool.strip()]
params['allocation_pools'] = pools
if data['host_routes'] or is_update:
routes = [dict(zip(['destination', 'nexthop'],
route.strip().split(',')))
for route in data['host_routes'].splitlines()
if route.strip()]
params['host_routes'] = routes
if data['dns_nameservers'] or is_update:
nameservers = [ns.strip()
for ns in data['dns_nameservers'].splitlines()
if ns.strip()]
params['dns_nameservers'] = nameservers | python | def _setup_subnet_parameters(self, params, data, is_create=True):
"""Setup subnet parameters
This methods setups subnet parameters which are available
in both create and update.
"""
is_update = not is_create
params['enable_dhcp'] = data['enable_dhcp']
if int(data['ip_version']) == 6:
ipv6_modes = utils.get_ipv6_modes_attrs_from_menu(
data['ipv6_modes'])
if ipv6_modes[0] and is_create:
params['ipv6_ra_mode'] = ipv6_modes[0]
if ipv6_modes[1] and is_create:
params['ipv6_address_mode'] = ipv6_modes[1]
if data['allocation_pools']:
pools = [dict(zip(['start', 'end'], pool.strip().split(',')))
for pool in data['allocation_pools'].splitlines()
if pool.strip()]
params['allocation_pools'] = pools
if data['host_routes'] or is_update:
routes = [dict(zip(['destination', 'nexthop'],
route.strip().split(',')))
for route in data['host_routes'].splitlines()
if route.strip()]
params['host_routes'] = routes
if data['dns_nameservers'] or is_update:
nameservers = [ns.strip()
for ns in data['dns_nameservers'].splitlines()
if ns.strip()]
params['dns_nameservers'] = nameservers | [
"def",
"_setup_subnet_parameters",
"(",
"self",
",",
"params",
",",
"data",
",",
"is_create",
"=",
"True",
")",
":",
"is_update",
"=",
"not",
"is_create",
"params",
"[",
"'enable_dhcp'",
"]",
"=",
"data",
"[",
"'enable_dhcp'",
"]",
"if",
"int",
"(",
"data"... | Setup subnet parameters
This methods setups subnet parameters which are available
in both create and update. | [
"Setup",
"subnet",
"parameters"
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/dashboards/project/networks/workflows.py#L498-L528 | train | 215,931 |
openstack/horizon | openstack_dashboard/dashboards/project/networks/workflows.py | CreateNetwork._delete_network | def _delete_network(self, request, network):
"""Delete the created network when subnet creation failed."""
try:
api.neutron.network_delete(request, network.id)
LOG.debug('Delete the created network %s '
'due to subnet creation failure.', network.id)
msg = _('Delete the created network "%s" '
'due to subnet creation failure.') % network.name
redirect = self.get_failure_url()
messages.info(request, msg)
raise exceptions.Http302(redirect)
except Exception as e:
LOG.info('Failed to delete network %(id)s: %(exc)s',
{'id': network.id, 'exc': e})
msg = _('Failed to delete network "%s"') % network.name
redirect = self.get_failure_url()
exceptions.handle(request, msg, redirect=redirect) | python | def _delete_network(self, request, network):
"""Delete the created network when subnet creation failed."""
try:
api.neutron.network_delete(request, network.id)
LOG.debug('Delete the created network %s '
'due to subnet creation failure.', network.id)
msg = _('Delete the created network "%s" '
'due to subnet creation failure.') % network.name
redirect = self.get_failure_url()
messages.info(request, msg)
raise exceptions.Http302(redirect)
except Exception as e:
LOG.info('Failed to delete network %(id)s: %(exc)s',
{'id': network.id, 'exc': e})
msg = _('Failed to delete network "%s"') % network.name
redirect = self.get_failure_url()
exceptions.handle(request, msg, redirect=redirect) | [
"def",
"_delete_network",
"(",
"self",
",",
"request",
",",
"network",
")",
":",
"try",
":",
"api",
".",
"neutron",
".",
"network_delete",
"(",
"request",
",",
"network",
".",
"id",
")",
"LOG",
".",
"debug",
"(",
"'Delete the created network %s '",
"'due to ... | Delete the created network when subnet creation failed. | [
"Delete",
"the",
"created",
"network",
"when",
"subnet",
"creation",
"failed",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/dashboards/project/networks/workflows.py#L578-L594 | train | 215,932 |
openstack/horizon | horizon/templatetags/bootstrap.py | bs_progress_bar | def bs_progress_bar(*args, **kwargs):
"""A Standard Bootstrap Progress Bar.
http://getbootstrap.com/components/#progress
param args (Array of Numbers: 0-100): Percent of Progress Bars
param context (String): Adds 'progress-bar-{context} to the class attribute
param contexts (Array of Strings): Cycles through contexts for stacked bars
param text (String): True: shows value within the bar, False: uses sr span
param striped (Boolean): Adds 'progress-bar-striped' to the class attribute
param animated (Boolean): Adds 'active' to the class attribute if striped
param min_val (0): Used for the aria-min value
param max_val (0): Used for the aria-max value
"""
bars = []
contexts = kwargs.get(
'contexts',
['', 'success', 'info', 'warning', 'danger']
)
for ndx, arg in enumerate(args):
bars.append(
dict(percent=arg,
context=kwargs.get('context', contexts[ndx % len(contexts)]))
)
return {
'bars': bars,
'text': kwargs.pop('text', False),
'striped': kwargs.pop('striped', False),
'animated': kwargs.pop('animated', False),
'min_val': kwargs.pop('min_val', 0),
'max_val': kwargs.pop('max_val', 100),
} | python | def bs_progress_bar(*args, **kwargs):
"""A Standard Bootstrap Progress Bar.
http://getbootstrap.com/components/#progress
param args (Array of Numbers: 0-100): Percent of Progress Bars
param context (String): Adds 'progress-bar-{context} to the class attribute
param contexts (Array of Strings): Cycles through contexts for stacked bars
param text (String): True: shows value within the bar, False: uses sr span
param striped (Boolean): Adds 'progress-bar-striped' to the class attribute
param animated (Boolean): Adds 'active' to the class attribute if striped
param min_val (0): Used for the aria-min value
param max_val (0): Used for the aria-max value
"""
bars = []
contexts = kwargs.get(
'contexts',
['', 'success', 'info', 'warning', 'danger']
)
for ndx, arg in enumerate(args):
bars.append(
dict(percent=arg,
context=kwargs.get('context', contexts[ndx % len(contexts)]))
)
return {
'bars': bars,
'text': kwargs.pop('text', False),
'striped': kwargs.pop('striped', False),
'animated': kwargs.pop('animated', False),
'min_val': kwargs.pop('min_val', 0),
'max_val': kwargs.pop('max_val', 100),
} | [
"def",
"bs_progress_bar",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"bars",
"=",
"[",
"]",
"contexts",
"=",
"kwargs",
".",
"get",
"(",
"'contexts'",
",",
"[",
"''",
",",
"'success'",
",",
"'info'",
",",
"'warning'",
",",
"'danger'",
"]",
... | A Standard Bootstrap Progress Bar.
http://getbootstrap.com/components/#progress
param args (Array of Numbers: 0-100): Percent of Progress Bars
param context (String): Adds 'progress-bar-{context} to the class attribute
param contexts (Array of Strings): Cycles through contexts for stacked bars
param text (String): True: shows value within the bar, False: uses sr span
param striped (Boolean): Adds 'progress-bar-striped' to the class attribute
param animated (Boolean): Adds 'active' to the class attribute if striped
param min_val (0): Used for the aria-min value
param max_val (0): Used for the aria-max value | [
"A",
"Standard",
"Bootstrap",
"Progress",
"Bar",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/templatetags/bootstrap.py#L25-L59 | train | 215,933 |
openstack/horizon | horizon/utils/filters.py | timesince_or_never | def timesince_or_never(dt, default=None):
"""Call the Django ``timesince`` filter or a given default string.
It returns the string *default* if *dt* is not a valid ``date``
or ``datetime`` object.
When *default* is None, "Never" is returned.
"""
if default is None:
default = _("Never")
if isinstance(dt, datetime.date):
return timesince(dt)
else:
return default | python | def timesince_or_never(dt, default=None):
"""Call the Django ``timesince`` filter or a given default string.
It returns the string *default* if *dt* is not a valid ``date``
or ``datetime`` object.
When *default* is None, "Never" is returned.
"""
if default is None:
default = _("Never")
if isinstance(dt, datetime.date):
return timesince(dt)
else:
return default | [
"def",
"timesince_or_never",
"(",
"dt",
",",
"default",
"=",
"None",
")",
":",
"if",
"default",
"is",
"None",
":",
"default",
"=",
"_",
"(",
"\"Never\"",
")",
"if",
"isinstance",
"(",
"dt",
",",
"datetime",
".",
"date",
")",
":",
"return",
"timesince",... | Call the Django ``timesince`` filter or a given default string.
It returns the string *default* if *dt* is not a valid ``date``
or ``datetime`` object.
When *default* is None, "Never" is returned. | [
"Call",
"the",
"Django",
"timesince",
"filter",
"or",
"a",
"given",
"default",
"string",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/utils/filters.py#L42-L55 | train | 215,934 |
openstack/horizon | openstack_auth/plugin/k2k.py | K2KAuthPlugin.get_plugin | def get_plugin(self, service_provider=None, auth_url=None, plugins=None,
**kwargs):
"""Authenticate using keystone to keystone federation.
This plugin uses other v3 plugins to authenticate a user to a
identity provider in order to authenticate the user to a service
provider
:param service_provider: service provider ID
:param auth_url: Keystone auth url
:param plugins: list of openstack_auth plugins to check
:returns Keystone2Keystone keystone auth plugin
"""
# Avoid mutable default arg for plugins
plugins = plugins or []
# service_provider being None prevents infinite recursion
if utils.get_keystone_version() < 3 or not service_provider:
return None
keystone_idp_id = getattr(settings, 'KEYSTONE_PROVIDER_IDP_ID',
'localkeystone')
if service_provider == keystone_idp_id:
return None
for plugin in plugins:
unscoped_idp_auth = plugin.get_plugin(plugins=plugins,
auth_url=auth_url, **kwargs)
if unscoped_idp_auth:
break
else:
LOG.debug('Could not find base authentication backend for '
'K2K plugin with the provided credentials.')
return None
idp_exception = None
scoped_idp_auth = None
unscoped_auth_ref = base.BasePlugin.get_access_info(
self, unscoped_idp_auth)
try:
scoped_idp_auth, __ = self.get_project_scoped_auth(
unscoped_idp_auth, unscoped_auth_ref,
recent_project=kwargs['recent_project'])
except exceptions.KeystoneAuthException as idp_excp:
idp_exception = idp_excp
if not scoped_idp_auth or idp_exception:
msg = _('Identity provider authentication failed.')
raise exceptions.KeystoneAuthException(msg)
session = utils.get_session()
if scoped_idp_auth.get_sp_auth_url(session, service_provider) is None:
msg = _('Could not find service provider ID on keystone.')
raise exceptions.KeystoneAuthException(msg)
unscoped_auth = v3_auth.Keystone2Keystone(
base_plugin=scoped_idp_auth,
service_provider=service_provider)
return unscoped_auth | python | def get_plugin(self, service_provider=None, auth_url=None, plugins=None,
**kwargs):
"""Authenticate using keystone to keystone federation.
This plugin uses other v3 plugins to authenticate a user to a
identity provider in order to authenticate the user to a service
provider
:param service_provider: service provider ID
:param auth_url: Keystone auth url
:param plugins: list of openstack_auth plugins to check
:returns Keystone2Keystone keystone auth plugin
"""
# Avoid mutable default arg for plugins
plugins = plugins or []
# service_provider being None prevents infinite recursion
if utils.get_keystone_version() < 3 or not service_provider:
return None
keystone_idp_id = getattr(settings, 'KEYSTONE_PROVIDER_IDP_ID',
'localkeystone')
if service_provider == keystone_idp_id:
return None
for plugin in plugins:
unscoped_idp_auth = plugin.get_plugin(plugins=plugins,
auth_url=auth_url, **kwargs)
if unscoped_idp_auth:
break
else:
LOG.debug('Could not find base authentication backend for '
'K2K plugin with the provided credentials.')
return None
idp_exception = None
scoped_idp_auth = None
unscoped_auth_ref = base.BasePlugin.get_access_info(
self, unscoped_idp_auth)
try:
scoped_idp_auth, __ = self.get_project_scoped_auth(
unscoped_idp_auth, unscoped_auth_ref,
recent_project=kwargs['recent_project'])
except exceptions.KeystoneAuthException as idp_excp:
idp_exception = idp_excp
if not scoped_idp_auth or idp_exception:
msg = _('Identity provider authentication failed.')
raise exceptions.KeystoneAuthException(msg)
session = utils.get_session()
if scoped_idp_auth.get_sp_auth_url(session, service_provider) is None:
msg = _('Could not find service provider ID on keystone.')
raise exceptions.KeystoneAuthException(msg)
unscoped_auth = v3_auth.Keystone2Keystone(
base_plugin=scoped_idp_auth,
service_provider=service_provider)
return unscoped_auth | [
"def",
"get_plugin",
"(",
"self",
",",
"service_provider",
"=",
"None",
",",
"auth_url",
"=",
"None",
",",
"plugins",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# Avoid mutable default arg for plugins",
"plugins",
"=",
"plugins",
"or",
"[",
"]",
"# ser... | Authenticate using keystone to keystone federation.
This plugin uses other v3 plugins to authenticate a user to a
identity provider in order to authenticate the user to a service
provider
:param service_provider: service provider ID
:param auth_url: Keystone auth url
:param plugins: list of openstack_auth plugins to check
:returns Keystone2Keystone keystone auth plugin | [
"Authenticate",
"using",
"keystone",
"to",
"keystone",
"federation",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_auth/plugin/k2k.py#L31-L91 | train | 215,935 |
openstack/horizon | openstack_auth/plugin/k2k.py | K2KAuthPlugin.get_access_info | def get_access_info(self, unscoped_auth):
"""Get the access info object
We attempt to get the auth ref. If it fails and if the K2K auth plugin
was being used then we will prepend a message saying that the error was
on the service provider side.
:param: unscoped_auth: Keystone auth plugin for unscoped user
:returns: keystoneclient.access.AccessInfo object
"""
try:
unscoped_auth_ref = base.BasePlugin.get_access_info(
self, unscoped_auth)
except exceptions.KeystoneAuthException as excp:
msg = _('Service provider authentication failed. %s')
raise exceptions.KeystoneAuthException(msg % str(excp))
return unscoped_auth_ref | python | def get_access_info(self, unscoped_auth):
"""Get the access info object
We attempt to get the auth ref. If it fails and if the K2K auth plugin
was being used then we will prepend a message saying that the error was
on the service provider side.
:param: unscoped_auth: Keystone auth plugin for unscoped user
:returns: keystoneclient.access.AccessInfo object
"""
try:
unscoped_auth_ref = base.BasePlugin.get_access_info(
self, unscoped_auth)
except exceptions.KeystoneAuthException as excp:
msg = _('Service provider authentication failed. %s')
raise exceptions.KeystoneAuthException(msg % str(excp))
return unscoped_auth_ref | [
"def",
"get_access_info",
"(",
"self",
",",
"unscoped_auth",
")",
":",
"try",
":",
"unscoped_auth_ref",
"=",
"base",
".",
"BasePlugin",
".",
"get_access_info",
"(",
"self",
",",
"unscoped_auth",
")",
"except",
"exceptions",
".",
"KeystoneAuthException",
"as",
"e... | Get the access info object
We attempt to get the auth ref. If it fails and if the K2K auth plugin
was being used then we will prepend a message saying that the error was
on the service provider side.
:param: unscoped_auth: Keystone auth plugin for unscoped user
:returns: keystoneclient.access.AccessInfo object | [
"Get",
"the",
"access",
"info",
"object"
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_auth/plugin/k2k.py#L93-L108 | train | 215,936 |
openstack/horizon | openstack_auth/user.py | User.is_token_expired | def is_token_expired(self, margin=None):
"""Determine if the token is expired.
:returns:
``True`` if the token is expired, ``False`` if not, and
``None`` if there is no token set.
:param margin:
A security time margin in seconds before real expiration.
Will return ``True`` if the token expires in less than ``margin``
seconds of time.
A default margin can be set by the TOKEN_TIMEOUT_MARGIN in the
django settings.
"""
if self.token is None:
return None
return not utils.is_token_valid(self.token, margin) | python | def is_token_expired(self, margin=None):
"""Determine if the token is expired.
:returns:
``True`` if the token is expired, ``False`` if not, and
``None`` if there is no token set.
:param margin:
A security time margin in seconds before real expiration.
Will return ``True`` if the token expires in less than ``margin``
seconds of time.
A default margin can be set by the TOKEN_TIMEOUT_MARGIN in the
django settings.
"""
if self.token is None:
return None
return not utils.is_token_valid(self.token, margin) | [
"def",
"is_token_expired",
"(",
"self",
",",
"margin",
"=",
"None",
")",
":",
"if",
"self",
".",
"token",
"is",
"None",
":",
"return",
"None",
"return",
"not",
"utils",
".",
"is_token_valid",
"(",
"self",
".",
"token",
",",
"margin",
")"
] | Determine if the token is expired.
:returns:
``True`` if the token is expired, ``False`` if not, and
``None`` if there is no token set.
:param margin:
A security time margin in seconds before real expiration.
Will return ``True`` if the token expires in less than ``margin``
seconds of time.
A default margin can be set by the TOKEN_TIMEOUT_MARGIN in the
django settings. | [
"Determine",
"if",
"the",
"token",
"is",
"expired",
"."
] | 5601ea9477323e599d9b766fcac1f8be742935b2 | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_auth/user.py#L245-L262 | train | 215,937 |
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):
"""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) | [
"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 | train | 215,938 |
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):
"""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 [] | [
"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 | train | 215,939 |
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):
"""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 | [
"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 | train | 215,940 |
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):
"""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 | [
"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 | train | 215,941 |
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):
"""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 | [
"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 | train | 215,942 |
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):
"""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() | [
"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 | train | 215,943 |
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):
"""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) | [
"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 | train | 215,944 |
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):
"""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 | [
"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 | train | 215,945 |
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):
"""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 | [
"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 | train | 215,946 |
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'):
"""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 | [
"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 | train | 215,947 |
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):
"""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 | [
"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 | train | 215,948 |
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):
"""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 | [
"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 | train | 215,949 |
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):
"""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 | [
"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 | train | 215,950 |
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):
"""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)) | [
"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 | train | 215,951 |
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):
"""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) | [
"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 | train | 215,952 |
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):
"""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 | [
"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 | train | 215,953 |
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):
"""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) | [
"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 | train | 215,954 |
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):
"""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] | [
"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 | train | 215,955 |
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):
"""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)
) | [
"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 | train | 215,956 |
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):
"""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.') | [
"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 | train | 215,957 |
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):
"""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 | [
"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 | train | 215,958 |
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):
"""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')
) | [
"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 | train | 215,959 |
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):
"""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 | [
"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 | train | 215,960 |
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):
"""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) | [
"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 | train | 215,961 |
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 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 | [
"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 | train | 215,962 |
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):
"""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) | [
"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 | train | 215,963 |
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):
"""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 | [
"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 | train | 215,964 |
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):
"""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 | [
"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 | train | 215,965 |
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):
"""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 | [
"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 | train | 215,966 |
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):
"""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 | [
"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 | train | 215,967 |
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):
"""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 | [
"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 | train | 215,968 |
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):
"""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 | [
"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 | train | 215,969 |
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):
"""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 | [
"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 | train | 215,970 |
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):
"""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 | [
"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 | train | 215,971 |
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):
"""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 | [
"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 | train | 215,972 |
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):
"""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) | [
"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 | train | 215,973 |
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):
"""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,
} | [
"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 | train | 215,974 |
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):
"""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()) | [
"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 | train | 215,975 |
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):
"""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) | [
"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 | train | 215,976 |
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):
"""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
} | [
"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 | train | 215,977 |
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):
"""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 | [
"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 | train | 215,978 |
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):
"""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] | [
"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 | train | 215,979 |
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):
"""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 | [
"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 | train | 215,980 |
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):
"""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 | [
"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 | train | 215,981 |
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):
"""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 | [
"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 | train | 215,982 |
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):
"""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 | [
"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 | train | 215,983 |
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):
"""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 | [
"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 | train | 215,984 |
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):
"""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 | [
"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 | train | 215,985 |
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):
"""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() | [
"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 | train | 215,986 |
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):
"""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 | [
"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 | train | 215,987 |
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):
"""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 | [
"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 | train | 215,988 |
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):
"""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 | [
"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 | train | 215,989 |
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):
"""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) | [
"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 | train | 215,990 |
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):
"""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}) | [
"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 | train | 215,991 |
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):
"""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}) | [
"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 | train | 215,992 |
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):
"""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) | [
"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 | train | 215,993 |
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):
"""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 | [
"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 | train | 215,994 |
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):
"""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 | [
"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 | train | 215,995 |
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):
"""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 | [
"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 | train | 215,996 |
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):
"""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) | [
"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 | train | 215,997 |
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):
"""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) | [
"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 | train | 215,998 |
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):
"""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.')) | [
"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 | train | 215,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.