id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
51
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
234,800
zarr-developers/zarr
zarr/creation.py
array
def array(data, **kwargs): """Create an array filled with `data`. The `data` argument should be a NumPy array or array-like object. For other parameter definitions see :func:`zarr.creation.create`. Examples -------- >>> import numpy as np >>> import zarr >>> a = np.arange(100000000).reshape(10000, 10000) >>> z = zarr.array(a, chunks=(1000, 1000)) >>> z <zarr.core.Array (10000, 10000) int64> """ # ensure data is array-like if not hasattr(data, 'shape') or not hasattr(data, 'dtype'): data = np.asanyarray(data) # setup dtype kw_dtype = kwargs.get('dtype', None) if kw_dtype is None: kwargs['dtype'] = data.dtype else: kwargs['dtype'] = kw_dtype # setup shape and chunks data_shape, data_chunks = _get_shape_chunks(data) kwargs['shape'] = data_shape kw_chunks = kwargs.get('chunks', None) if kw_chunks is None: kwargs['chunks'] = data_chunks else: kwargs['chunks'] = kw_chunks # pop read-only to apply after storing the data read_only = kwargs.pop('read_only', False) # instantiate array z = create(**kwargs) # fill with data z[...] = data # set read_only property afterwards z.read_only = read_only return z
python
def array(data, **kwargs): # ensure data is array-like if not hasattr(data, 'shape') or not hasattr(data, 'dtype'): data = np.asanyarray(data) # setup dtype kw_dtype = kwargs.get('dtype', None) if kw_dtype is None: kwargs['dtype'] = data.dtype else: kwargs['dtype'] = kw_dtype # setup shape and chunks data_shape, data_chunks = _get_shape_chunks(data) kwargs['shape'] = data_shape kw_chunks = kwargs.get('chunks', None) if kw_chunks is None: kwargs['chunks'] = data_chunks else: kwargs['chunks'] = kw_chunks # pop read-only to apply after storing the data read_only = kwargs.pop('read_only', False) # instantiate array z = create(**kwargs) # fill with data z[...] = data # set read_only property afterwards z.read_only = read_only return z
[ "def", "array", "(", "data", ",", "*", "*", "kwargs", ")", ":", "# ensure data is array-like", "if", "not", "hasattr", "(", "data", ",", "'shape'", ")", "or", "not", "hasattr", "(", "data", ",", "'dtype'", ")", ":", "data", "=", "np", ".", "asanyarray"...
Create an array filled with `data`. The `data` argument should be a NumPy array or array-like object. For other parameter definitions see :func:`zarr.creation.create`. Examples -------- >>> import numpy as np >>> import zarr >>> a = np.arange(100000000).reshape(10000, 10000) >>> z = zarr.array(a, chunks=(1000, 1000)) >>> z <zarr.core.Array (10000, 10000) int64>
[ "Create", "an", "array", "filled", "with", "data", "." ]
fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5
https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/creation.py#L300-L349
234,801
zarr-developers/zarr
zarr/creation.py
open_array
def open_array(store=None, mode='a', shape=None, chunks=True, dtype=None, compressor='default', fill_value=0, order='C', synchronizer=None, filters=None, cache_metadata=True, cache_attrs=True, path=None, object_codec=None, chunk_store=None, **kwargs): """Open an array using file-mode-like semantics. Parameters ---------- store : MutableMapping or string, optional Store or path to directory in file system or name of zip file. mode : {'r', 'r+', 'a', 'w', 'w-'}, optional Persistence mode: 'r' means read only (must exist); 'r+' means read/write (must exist); 'a' means read/write (create if doesn't exist); 'w' means create (overwrite if exists); 'w-' means create (fail if exists). shape : int or tuple of ints, optional Array shape. chunks : int or tuple of ints, optional Chunk shape. If True, will be guessed from `shape` and `dtype`. If False, will be set to `shape`, i.e., single chunk for the whole array. dtype : string or dtype, optional NumPy dtype. compressor : Codec, optional Primary compressor. fill_value : object, optional Default value to use for uninitialized portions of the array. order : {'C', 'F'}, optional Memory layout to be used within each chunk. synchronizer : object, optional Array synchronizer. filters : sequence, optional Sequence of filters to use to encode chunk data prior to compression. cache_metadata : bool, optional If True, array configuration metadata will be cached for the lifetime of the object. If False, array metadata will be reloaded prior to all data access and modification operations (may incur overhead depending on storage and data access pattern). cache_attrs : bool, optional If True (default), user attributes will be cached for attribute read operations. If False, user attributes are reloaded from the store prior to all attribute read operations. path : string, optional Array path within store. object_codec : Codec, optional A codec to encode object arrays, only needed if dtype=object. chunk_store : MutableMapping or string, optional Store or path to directory in file system or name of zip file. Returns ------- z : zarr.core.Array Examples -------- >>> import numpy as np >>> import zarr >>> z1 = zarr.open_array('data/example.zarr', mode='w', shape=(10000, 10000), ... chunks=(1000, 1000), fill_value=0) >>> z1[:] = np.arange(100000000).reshape(10000, 10000) >>> z1 <zarr.core.Array (10000, 10000) float64> >>> z2 = zarr.open_array('data/example.zarr', mode='r') >>> z2 <zarr.core.Array (10000, 10000) float64 read-only> >>> np.all(z1[:] == z2[:]) True Notes ----- There is no need to close an array. Data are automatically flushed to the file system. """ # use same mode semantics as h5py # r : read only, must exist # r+ : read/write, must exist # w : create, delete if exists # w- or x : create, fail if exists # a : read/write if exists, create otherwise (default) # handle polymorphic store arg clobber = mode == 'w' store = normalize_store_arg(store, clobber=clobber) if chunk_store is not None: chunk_store = normalize_store_arg(chunk_store, clobber=clobber) path = normalize_storage_path(path) # API compatibility with h5py compressor, fill_value = _kwargs_compat(compressor, fill_value, kwargs) # ensure fill_value of correct type if fill_value is not None: fill_value = np.array(fill_value, dtype=dtype)[()] # ensure store is initialized if mode in ['r', 'r+']: if contains_group(store, path=path): err_contains_group(path) elif not contains_array(store, path=path): err_array_not_found(path) elif mode == 'w': init_array(store, shape=shape, chunks=chunks, dtype=dtype, compressor=compressor, fill_value=fill_value, order=order, filters=filters, overwrite=True, path=path, object_codec=object_codec, chunk_store=chunk_store) elif mode == 'a': if contains_group(store, path=path): err_contains_group(path) elif not contains_array(store, path=path): init_array(store, shape=shape, chunks=chunks, dtype=dtype, compressor=compressor, fill_value=fill_value, order=order, filters=filters, path=path, object_codec=object_codec, chunk_store=chunk_store) elif mode in ['w-', 'x']: if contains_group(store, path=path): err_contains_group(path) elif contains_array(store, path=path): err_contains_array(path) else: init_array(store, shape=shape, chunks=chunks, dtype=dtype, compressor=compressor, fill_value=fill_value, order=order, filters=filters, path=path, object_codec=object_codec, chunk_store=chunk_store) # determine read only status read_only = mode == 'r' # instantiate array z = Array(store, read_only=read_only, synchronizer=synchronizer, cache_metadata=cache_metadata, cache_attrs=cache_attrs, path=path, chunk_store=chunk_store) return z
python
def open_array(store=None, mode='a', shape=None, chunks=True, dtype=None, compressor='default', fill_value=0, order='C', synchronizer=None, filters=None, cache_metadata=True, cache_attrs=True, path=None, object_codec=None, chunk_store=None, **kwargs): # use same mode semantics as h5py # r : read only, must exist # r+ : read/write, must exist # w : create, delete if exists # w- or x : create, fail if exists # a : read/write if exists, create otherwise (default) # handle polymorphic store arg clobber = mode == 'w' store = normalize_store_arg(store, clobber=clobber) if chunk_store is not None: chunk_store = normalize_store_arg(chunk_store, clobber=clobber) path = normalize_storage_path(path) # API compatibility with h5py compressor, fill_value = _kwargs_compat(compressor, fill_value, kwargs) # ensure fill_value of correct type if fill_value is not None: fill_value = np.array(fill_value, dtype=dtype)[()] # ensure store is initialized if mode in ['r', 'r+']: if contains_group(store, path=path): err_contains_group(path) elif not contains_array(store, path=path): err_array_not_found(path) elif mode == 'w': init_array(store, shape=shape, chunks=chunks, dtype=dtype, compressor=compressor, fill_value=fill_value, order=order, filters=filters, overwrite=True, path=path, object_codec=object_codec, chunk_store=chunk_store) elif mode == 'a': if contains_group(store, path=path): err_contains_group(path) elif not contains_array(store, path=path): init_array(store, shape=shape, chunks=chunks, dtype=dtype, compressor=compressor, fill_value=fill_value, order=order, filters=filters, path=path, object_codec=object_codec, chunk_store=chunk_store) elif mode in ['w-', 'x']: if contains_group(store, path=path): err_contains_group(path) elif contains_array(store, path=path): err_contains_array(path) else: init_array(store, shape=shape, chunks=chunks, dtype=dtype, compressor=compressor, fill_value=fill_value, order=order, filters=filters, path=path, object_codec=object_codec, chunk_store=chunk_store) # determine read only status read_only = mode == 'r' # instantiate array z = Array(store, read_only=read_only, synchronizer=synchronizer, cache_metadata=cache_metadata, cache_attrs=cache_attrs, path=path, chunk_store=chunk_store) return z
[ "def", "open_array", "(", "store", "=", "None", ",", "mode", "=", "'a'", ",", "shape", "=", "None", ",", "chunks", "=", "True", ",", "dtype", "=", "None", ",", "compressor", "=", "'default'", ",", "fill_value", "=", "0", ",", "order", "=", "'C'", "...
Open an array using file-mode-like semantics. Parameters ---------- store : MutableMapping or string, optional Store or path to directory in file system or name of zip file. mode : {'r', 'r+', 'a', 'w', 'w-'}, optional Persistence mode: 'r' means read only (must exist); 'r+' means read/write (must exist); 'a' means read/write (create if doesn't exist); 'w' means create (overwrite if exists); 'w-' means create (fail if exists). shape : int or tuple of ints, optional Array shape. chunks : int or tuple of ints, optional Chunk shape. If True, will be guessed from `shape` and `dtype`. If False, will be set to `shape`, i.e., single chunk for the whole array. dtype : string or dtype, optional NumPy dtype. compressor : Codec, optional Primary compressor. fill_value : object, optional Default value to use for uninitialized portions of the array. order : {'C', 'F'}, optional Memory layout to be used within each chunk. synchronizer : object, optional Array synchronizer. filters : sequence, optional Sequence of filters to use to encode chunk data prior to compression. cache_metadata : bool, optional If True, array configuration metadata will be cached for the lifetime of the object. If False, array metadata will be reloaded prior to all data access and modification operations (may incur overhead depending on storage and data access pattern). cache_attrs : bool, optional If True (default), user attributes will be cached for attribute read operations. If False, user attributes are reloaded from the store prior to all attribute read operations. path : string, optional Array path within store. object_codec : Codec, optional A codec to encode object arrays, only needed if dtype=object. chunk_store : MutableMapping or string, optional Store or path to directory in file system or name of zip file. Returns ------- z : zarr.core.Array Examples -------- >>> import numpy as np >>> import zarr >>> z1 = zarr.open_array('data/example.zarr', mode='w', shape=(10000, 10000), ... chunks=(1000, 1000), fill_value=0) >>> z1[:] = np.arange(100000000).reshape(10000, 10000) >>> z1 <zarr.core.Array (10000, 10000) float64> >>> z2 = zarr.open_array('data/example.zarr', mode='r') >>> z2 <zarr.core.Array (10000, 10000) float64 read-only> >>> np.all(z1[:] == z2[:]) True Notes ----- There is no need to close an array. Data are automatically flushed to the file system.
[ "Open", "an", "array", "using", "file", "-", "mode", "-", "like", "semantics", "." ]
fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5
https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/creation.py#L352-L489
234,802
zarr-developers/zarr
zarr/creation.py
full_like
def full_like(a, **kwargs): """Create a filled array like `a`.""" _like_args(a, kwargs) if isinstance(a, Array): kwargs.setdefault('fill_value', a.fill_value) return full(**kwargs)
python
def full_like(a, **kwargs): _like_args(a, kwargs) if isinstance(a, Array): kwargs.setdefault('fill_value', a.fill_value) return full(**kwargs)
[ "def", "full_like", "(", "a", ",", "*", "*", "kwargs", ")", ":", "_like_args", "(", "a", ",", "kwargs", ")", "if", "isinstance", "(", "a", ",", "Array", ")", ":", "kwargs", ".", "setdefault", "(", "'fill_value'", ",", "a", ".", "fill_value", ")", "...
Create a filled array like `a`.
[ "Create", "a", "filled", "array", "like", "a", "." ]
fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5
https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/creation.py#L530-L535
234,803
zarr-developers/zarr
zarr/creation.py
open_like
def open_like(a, path, **kwargs): """Open a persistent array like `a`.""" _like_args(a, kwargs) if isinstance(a, Array): kwargs.setdefault('fill_value', a.fill_value) return open_array(path, **kwargs)
python
def open_like(a, path, **kwargs): _like_args(a, kwargs) if isinstance(a, Array): kwargs.setdefault('fill_value', a.fill_value) return open_array(path, **kwargs)
[ "def", "open_like", "(", "a", ",", "path", ",", "*", "*", "kwargs", ")", ":", "_like_args", "(", "a", ",", "kwargs", ")", "if", "isinstance", "(", "a", ",", "Array", ")", ":", "kwargs", ".", "setdefault", "(", "'fill_value'", ",", "a", ".", "fill_v...
Open a persistent array like `a`.
[ "Open", "a", "persistent", "array", "like", "a", "." ]
fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5
https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/creation.py#L538-L543
234,804
zarr-developers/zarr
zarr/convenience.py
open
def open(store=None, mode='a', **kwargs): """Convenience function to open a group or array using file-mode-like semantics. Parameters ---------- store : MutableMapping or string, optional Store or path to directory in file system or name of zip file. mode : {'r', 'r+', 'a', 'w', 'w-'}, optional Persistence mode: 'r' means read only (must exist); 'r+' means read/write (must exist); 'a' means read/write (create if doesn't exist); 'w' means create (overwrite if exists); 'w-' means create (fail if exists). **kwargs Additional parameters are passed through to :func:`zarr.creation.open_array` or :func:`zarr.hierarchy.open_group`. Returns ------- z : :class:`zarr.core.Array` or :class:`zarr.hierarchy.Group` Array or group, depending on what exists in the given store. See Also -------- zarr.creation.open_array, zarr.hierarchy.open_group Examples -------- Storing data in a directory 'data/example.zarr' on the local file system:: >>> import zarr >>> store = 'data/example.zarr' >>> zw = zarr.open(store, mode='w', shape=100, dtype='i4') # open new array >>> zw <zarr.core.Array (100,) int32> >>> za = zarr.open(store, mode='a') # open existing array for reading and writing >>> za <zarr.core.Array (100,) int32> >>> zr = zarr.open(store, mode='r') # open existing array read-only >>> zr <zarr.core.Array (100,) int32 read-only> >>> gw = zarr.open(store, mode='w') # open new group, overwriting previous data >>> gw <zarr.hierarchy.Group '/'> >>> ga = zarr.open(store, mode='a') # open existing group for reading and writing >>> ga <zarr.hierarchy.Group '/'> >>> gr = zarr.open(store, mode='r') # open existing group read-only >>> gr <zarr.hierarchy.Group '/' read-only> """ path = kwargs.get('path', None) # handle polymorphic store arg clobber = mode == 'w' store = normalize_store_arg(store, clobber=clobber) path = normalize_storage_path(path) if mode in {'w', 'w-', 'x'}: if 'shape' in kwargs: return open_array(store, mode=mode, **kwargs) else: return open_group(store, mode=mode, **kwargs) elif mode == 'a': if contains_array(store, path): return open_array(store, mode=mode, **kwargs) elif contains_group(store, path): return open_group(store, mode=mode, **kwargs) elif 'shape' in kwargs: return open_array(store, mode=mode, **kwargs) else: return open_group(store, mode=mode, **kwargs) else: if contains_array(store, path): return open_array(store, mode=mode, **kwargs) elif contains_group(store, path): return open_group(store, mode=mode, **kwargs) else: err_path_not_found(path)
python
def open(store=None, mode='a', **kwargs): path = kwargs.get('path', None) # handle polymorphic store arg clobber = mode == 'w' store = normalize_store_arg(store, clobber=clobber) path = normalize_storage_path(path) if mode in {'w', 'w-', 'x'}: if 'shape' in kwargs: return open_array(store, mode=mode, **kwargs) else: return open_group(store, mode=mode, **kwargs) elif mode == 'a': if contains_array(store, path): return open_array(store, mode=mode, **kwargs) elif contains_group(store, path): return open_group(store, mode=mode, **kwargs) elif 'shape' in kwargs: return open_array(store, mode=mode, **kwargs) else: return open_group(store, mode=mode, **kwargs) else: if contains_array(store, path): return open_array(store, mode=mode, **kwargs) elif contains_group(store, path): return open_group(store, mode=mode, **kwargs) else: err_path_not_found(path)
[ "def", "open", "(", "store", "=", "None", ",", "mode", "=", "'a'", ",", "*", "*", "kwargs", ")", ":", "path", "=", "kwargs", ".", "get", "(", "'path'", ",", "None", ")", "# handle polymorphic store arg", "clobber", "=", "mode", "==", "'w'", "store", ...
Convenience function to open a group or array using file-mode-like semantics. Parameters ---------- store : MutableMapping or string, optional Store or path to directory in file system or name of zip file. mode : {'r', 'r+', 'a', 'w', 'w-'}, optional Persistence mode: 'r' means read only (must exist); 'r+' means read/write (must exist); 'a' means read/write (create if doesn't exist); 'w' means create (overwrite if exists); 'w-' means create (fail if exists). **kwargs Additional parameters are passed through to :func:`zarr.creation.open_array` or :func:`zarr.hierarchy.open_group`. Returns ------- z : :class:`zarr.core.Array` or :class:`zarr.hierarchy.Group` Array or group, depending on what exists in the given store. See Also -------- zarr.creation.open_array, zarr.hierarchy.open_group Examples -------- Storing data in a directory 'data/example.zarr' on the local file system:: >>> import zarr >>> store = 'data/example.zarr' >>> zw = zarr.open(store, mode='w', shape=100, dtype='i4') # open new array >>> zw <zarr.core.Array (100,) int32> >>> za = zarr.open(store, mode='a') # open existing array for reading and writing >>> za <zarr.core.Array (100,) int32> >>> zr = zarr.open(store, mode='r') # open existing array read-only >>> zr <zarr.core.Array (100,) int32 read-only> >>> gw = zarr.open(store, mode='w') # open new group, overwriting previous data >>> gw <zarr.hierarchy.Group '/'> >>> ga = zarr.open(store, mode='a') # open existing group for reading and writing >>> ga <zarr.hierarchy.Group '/'> >>> gr = zarr.open(store, mode='r') # open existing group read-only >>> gr <zarr.hierarchy.Group '/' read-only>
[ "Convenience", "function", "to", "open", "a", "group", "or", "array", "using", "file", "-", "mode", "-", "like", "semantics", "." ]
fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5
https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/convenience.py#L21-L102
234,805
zarr-developers/zarr
zarr/convenience.py
save
def save(store, *args, **kwargs): """Convenience function to save an array or group of arrays to the local file system. Parameters ---------- store : MutableMapping or string Store or path to directory in file system or name of zip file. args : ndarray NumPy arrays with data to save. kwargs NumPy arrays with data to save. Examples -------- Save an array to a directory on the file system (uses a :class:`DirectoryStore`):: >>> import zarr >>> import numpy as np >>> arr = np.arange(10000) >>> zarr.save('data/example.zarr', arr) >>> zarr.load('data/example.zarr') array([ 0, 1, 2, ..., 9997, 9998, 9999]) Save an array to a Zip file (uses a :class:`ZipStore`):: >>> zarr.save('data/example.zip', arr) >>> zarr.load('data/example.zip') array([ 0, 1, 2, ..., 9997, 9998, 9999]) Save several arrays to a directory on the file system (uses a :class:`DirectoryStore` and stores arrays in a group):: >>> import zarr >>> import numpy as np >>> a1 = np.arange(10000) >>> a2 = np.arange(10000, 0, -1) >>> zarr.save('data/example.zarr', a1, a2) >>> loader = zarr.load('data/example.zarr') >>> loader <LazyLoader: arr_0, arr_1> >>> loader['arr_0'] array([ 0, 1, 2, ..., 9997, 9998, 9999]) >>> loader['arr_1'] array([10000, 9999, 9998, ..., 3, 2, 1]) Save several arrays using named keyword arguments:: >>> zarr.save('data/example.zarr', foo=a1, bar=a2) >>> loader = zarr.load('data/example.zarr') >>> loader <LazyLoader: bar, foo> >>> loader['foo'] array([ 0, 1, 2, ..., 9997, 9998, 9999]) >>> loader['bar'] array([10000, 9999, 9998, ..., 3, 2, 1]) Store several arrays in a single zip file (uses a :class:`ZipStore`):: >>> zarr.save('data/example.zip', foo=a1, bar=a2) >>> loader = zarr.load('data/example.zip') >>> loader <LazyLoader: bar, foo> >>> loader['foo'] array([ 0, 1, 2, ..., 9997, 9998, 9999]) >>> loader['bar'] array([10000, 9999, 9998, ..., 3, 2, 1]) See Also -------- save_array, save_group """ if len(args) == 0 and len(kwargs) == 0: raise ValueError('at least one array must be provided') if len(args) == 1 and len(kwargs) == 0: save_array(store, args[0]) else: save_group(store, *args, **kwargs)
python
def save(store, *args, **kwargs): if len(args) == 0 and len(kwargs) == 0: raise ValueError('at least one array must be provided') if len(args) == 1 and len(kwargs) == 0: save_array(store, args[0]) else: save_group(store, *args, **kwargs)
[ "def", "save", "(", "store", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "len", "(", "args", ")", "==", "0", "and", "len", "(", "kwargs", ")", "==", "0", ":", "raise", "ValueError", "(", "'at least one array must be provided'", ")", "i...
Convenience function to save an array or group of arrays to the local file system. Parameters ---------- store : MutableMapping or string Store or path to directory in file system or name of zip file. args : ndarray NumPy arrays with data to save. kwargs NumPy arrays with data to save. Examples -------- Save an array to a directory on the file system (uses a :class:`DirectoryStore`):: >>> import zarr >>> import numpy as np >>> arr = np.arange(10000) >>> zarr.save('data/example.zarr', arr) >>> zarr.load('data/example.zarr') array([ 0, 1, 2, ..., 9997, 9998, 9999]) Save an array to a Zip file (uses a :class:`ZipStore`):: >>> zarr.save('data/example.zip', arr) >>> zarr.load('data/example.zip') array([ 0, 1, 2, ..., 9997, 9998, 9999]) Save several arrays to a directory on the file system (uses a :class:`DirectoryStore` and stores arrays in a group):: >>> import zarr >>> import numpy as np >>> a1 = np.arange(10000) >>> a2 = np.arange(10000, 0, -1) >>> zarr.save('data/example.zarr', a1, a2) >>> loader = zarr.load('data/example.zarr') >>> loader <LazyLoader: arr_0, arr_1> >>> loader['arr_0'] array([ 0, 1, 2, ..., 9997, 9998, 9999]) >>> loader['arr_1'] array([10000, 9999, 9998, ..., 3, 2, 1]) Save several arrays using named keyword arguments:: >>> zarr.save('data/example.zarr', foo=a1, bar=a2) >>> loader = zarr.load('data/example.zarr') >>> loader <LazyLoader: bar, foo> >>> loader['foo'] array([ 0, 1, 2, ..., 9997, 9998, 9999]) >>> loader['bar'] array([10000, 9999, 9998, ..., 3, 2, 1]) Store several arrays in a single zip file (uses a :class:`ZipStore`):: >>> zarr.save('data/example.zip', foo=a1, bar=a2) >>> loader = zarr.load('data/example.zip') >>> loader <LazyLoader: bar, foo> >>> loader['foo'] array([ 0, 1, 2, ..., 9997, 9998, 9999]) >>> loader['bar'] array([10000, 9999, 9998, ..., 3, 2, 1]) See Also -------- save_array, save_group
[ "Convenience", "function", "to", "save", "an", "array", "or", "group", "of", "arrays", "to", "the", "local", "file", "system", "." ]
fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5
https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/convenience.py#L222-L299
234,806
zarr-developers/zarr
zarr/convenience.py
load
def load(store): """Load data from an array or group into memory. Parameters ---------- store : MutableMapping or string Store or path to directory in file system or name of zip file. Returns ------- out If the store contains an array, out will be a numpy array. If the store contains a group, out will be a dict-like object where keys are array names and values are numpy arrays. See Also -------- save, savez Notes ----- If loading data from a group of arrays, data will not be immediately loaded into memory. Rather, arrays will be loaded into memory as they are requested. """ # handle polymorphic store arg store = normalize_store_arg(store) if contains_array(store, path=None): return Array(store=store, path=None)[...] elif contains_group(store, path=None): grp = Group(store=store, path=None) return LazyLoader(grp)
python
def load(store): # handle polymorphic store arg store = normalize_store_arg(store) if contains_array(store, path=None): return Array(store=store, path=None)[...] elif contains_group(store, path=None): grp = Group(store=store, path=None) return LazyLoader(grp)
[ "def", "load", "(", "store", ")", ":", "# handle polymorphic store arg", "store", "=", "normalize_store_arg", "(", "store", ")", "if", "contains_array", "(", "store", ",", "path", "=", "None", ")", ":", "return", "Array", "(", "store", "=", "store", ",", "...
Load data from an array or group into memory. Parameters ---------- store : MutableMapping or string Store or path to directory in file system or name of zip file. Returns ------- out If the store contains an array, out will be a numpy array. If the store contains a group, out will be a dict-like object where keys are array names and values are numpy arrays. See Also -------- save, savez Notes ----- If loading data from a group of arrays, data will not be immediately loaded into memory. Rather, arrays will be loaded into memory as they are requested.
[ "Load", "data", "from", "an", "array", "or", "group", "into", "memory", "." ]
fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5
https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/convenience.py#L332-L363
234,807
zarr-developers/zarr
zarr/convenience.py
copy
def copy(source, dest, name=None, shallow=False, without_attrs=False, log=None, if_exists='raise', dry_run=False, **create_kws): """Copy the `source` array or group into the `dest` group. Parameters ---------- source : group or array/dataset A zarr group or array, or an h5py group or dataset. dest : group A zarr or h5py group. name : str, optional Name to copy the object to. shallow : bool, optional If True, only copy immediate children of `source`. without_attrs : bool, optional Do not copy user attributes. log : callable, file path or file-like object, optional If provided, will be used to log progress information. if_exists : {'raise', 'replace', 'skip', 'skip_initialized'}, optional How to handle arrays that already exist in the destination group. If 'raise' then a CopyError is raised on the first array already present in the destination group. If 'replace' then any array will be replaced in the destination. If 'skip' then any existing arrays will not be copied. If 'skip_initialized' then any existing arrays with all chunks initialized will not be copied (not available when copying to h5py). dry_run : bool, optional If True, don't actually copy anything, just log what would have happened. **create_kws Passed through to the create_dataset method when copying an array/dataset. Returns ------- n_copied : int Number of items copied. n_skipped : int Number of items skipped. n_bytes_copied : int Number of bytes of data that were actually copied. Examples -------- Here's an example of copying a group named 'foo' from an HDF5 file to a Zarr group:: >>> import h5py >>> import zarr >>> import numpy as np >>> source = h5py.File('data/example.h5', mode='w') >>> foo = source.create_group('foo') >>> baz = foo.create_dataset('bar/baz', data=np.arange(100), chunks=(50,)) >>> spam = source.create_dataset('spam', data=np.arange(100, 200), chunks=(30,)) >>> zarr.tree(source) / ├── foo │ └── bar │ └── baz (100,) int64 └── spam (100,) int64 >>> dest = zarr.group() >>> from sys import stdout >>> zarr.copy(source['foo'], dest, log=stdout) copy /foo copy /foo/bar copy /foo/bar/baz (100,) int64 all done: 3 copied, 0 skipped, 800 bytes copied (3, 0, 800) >>> dest.tree() # N.B., no spam / └── foo └── bar └── baz (100,) int64 >>> source.close() The ``if_exists`` parameter provides options for how to handle pre-existing data in the destination. Here are some examples of these options, also using ``dry_run=True`` to find out what would happen without actually copying anything:: >>> source = zarr.group() >>> dest = zarr.group() >>> baz = source.create_dataset('foo/bar/baz', data=np.arange(100)) >>> spam = source.create_dataset('foo/spam', data=np.arange(1000)) >>> existing_spam = dest.create_dataset('foo/spam', data=np.arange(1000)) >>> from sys import stdout >>> try: ... zarr.copy(source['foo'], dest, log=stdout, dry_run=True) ... except zarr.CopyError as e: ... print(e) ... copy /foo copy /foo/bar copy /foo/bar/baz (100,) int64 an object 'spam' already exists in destination '/foo' >>> zarr.copy(source['foo'], dest, log=stdout, if_exists='replace', dry_run=True) copy /foo copy /foo/bar copy /foo/bar/baz (100,) int64 copy /foo/spam (1000,) int64 dry run: 4 copied, 0 skipped (4, 0, 0) >>> zarr.copy(source['foo'], dest, log=stdout, if_exists='skip', dry_run=True) copy /foo copy /foo/bar copy /foo/bar/baz (100,) int64 skip /foo/spam (1000,) int64 dry run: 3 copied, 1 skipped (3, 1, 0) Notes ----- Please note that this is an experimental feature. The behaviour of this function is still evolving and the default behaviour and/or parameters may change in future versions. """ # value checks _check_dest_is_group(dest) # setup logging with _LogWriter(log) as log: # do the copying n_copied, n_skipped, n_bytes_copied = _copy( log, source, dest, name=name, root=True, shallow=shallow, without_attrs=without_attrs, if_exists=if_exists, dry_run=dry_run, **create_kws ) # log a final message with a summary of what happened _log_copy_summary(log, dry_run, n_copied, n_skipped, n_bytes_copied) return n_copied, n_skipped, n_bytes_copied
python
def copy(source, dest, name=None, shallow=False, without_attrs=False, log=None, if_exists='raise', dry_run=False, **create_kws): # value checks _check_dest_is_group(dest) # setup logging with _LogWriter(log) as log: # do the copying n_copied, n_skipped, n_bytes_copied = _copy( log, source, dest, name=name, root=True, shallow=shallow, without_attrs=without_attrs, if_exists=if_exists, dry_run=dry_run, **create_kws ) # log a final message with a summary of what happened _log_copy_summary(log, dry_run, n_copied, n_skipped, n_bytes_copied) return n_copied, n_skipped, n_bytes_copied
[ "def", "copy", "(", "source", ",", "dest", ",", "name", "=", "None", ",", "shallow", "=", "False", ",", "without_attrs", "=", "False", ",", "log", "=", "None", ",", "if_exists", "=", "'raise'", ",", "dry_run", "=", "False", ",", "*", "*", "create_kws...
Copy the `source` array or group into the `dest` group. Parameters ---------- source : group or array/dataset A zarr group or array, or an h5py group or dataset. dest : group A zarr or h5py group. name : str, optional Name to copy the object to. shallow : bool, optional If True, only copy immediate children of `source`. without_attrs : bool, optional Do not copy user attributes. log : callable, file path or file-like object, optional If provided, will be used to log progress information. if_exists : {'raise', 'replace', 'skip', 'skip_initialized'}, optional How to handle arrays that already exist in the destination group. If 'raise' then a CopyError is raised on the first array already present in the destination group. If 'replace' then any array will be replaced in the destination. If 'skip' then any existing arrays will not be copied. If 'skip_initialized' then any existing arrays with all chunks initialized will not be copied (not available when copying to h5py). dry_run : bool, optional If True, don't actually copy anything, just log what would have happened. **create_kws Passed through to the create_dataset method when copying an array/dataset. Returns ------- n_copied : int Number of items copied. n_skipped : int Number of items skipped. n_bytes_copied : int Number of bytes of data that were actually copied. Examples -------- Here's an example of copying a group named 'foo' from an HDF5 file to a Zarr group:: >>> import h5py >>> import zarr >>> import numpy as np >>> source = h5py.File('data/example.h5', mode='w') >>> foo = source.create_group('foo') >>> baz = foo.create_dataset('bar/baz', data=np.arange(100), chunks=(50,)) >>> spam = source.create_dataset('spam', data=np.arange(100, 200), chunks=(30,)) >>> zarr.tree(source) / ├── foo │ └── bar │ └── baz (100,) int64 └── spam (100,) int64 >>> dest = zarr.group() >>> from sys import stdout >>> zarr.copy(source['foo'], dest, log=stdout) copy /foo copy /foo/bar copy /foo/bar/baz (100,) int64 all done: 3 copied, 0 skipped, 800 bytes copied (3, 0, 800) >>> dest.tree() # N.B., no spam / └── foo └── bar └── baz (100,) int64 >>> source.close() The ``if_exists`` parameter provides options for how to handle pre-existing data in the destination. Here are some examples of these options, also using ``dry_run=True`` to find out what would happen without actually copying anything:: >>> source = zarr.group() >>> dest = zarr.group() >>> baz = source.create_dataset('foo/bar/baz', data=np.arange(100)) >>> spam = source.create_dataset('foo/spam', data=np.arange(1000)) >>> existing_spam = dest.create_dataset('foo/spam', data=np.arange(1000)) >>> from sys import stdout >>> try: ... zarr.copy(source['foo'], dest, log=stdout, dry_run=True) ... except zarr.CopyError as e: ... print(e) ... copy /foo copy /foo/bar copy /foo/bar/baz (100,) int64 an object 'spam' already exists in destination '/foo' >>> zarr.copy(source['foo'], dest, log=stdout, if_exists='replace', dry_run=True) copy /foo copy /foo/bar copy /foo/bar/baz (100,) int64 copy /foo/spam (1000,) int64 dry run: 4 copied, 0 skipped (4, 0, 0) >>> zarr.copy(source['foo'], dest, log=stdout, if_exists='skip', dry_run=True) copy /foo copy /foo/bar copy /foo/bar/baz (100,) int64 skip /foo/spam (1000,) int64 dry run: 3 copied, 1 skipped (3, 1, 0) Notes ----- Please note that this is an experimental feature. The behaviour of this function is still evolving and the default behaviour and/or parameters may change in future versions.
[ "Copy", "the", "source", "array", "or", "group", "into", "the", "dest", "group", "." ]
fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5
https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/convenience.py#L664-L796
234,808
zarr-developers/zarr
zarr/convenience.py
copy_all
def copy_all(source, dest, shallow=False, without_attrs=False, log=None, if_exists='raise', dry_run=False, **create_kws): """Copy all children of the `source` group into the `dest` group. Parameters ---------- source : group or array/dataset A zarr group or array, or an h5py group or dataset. dest : group A zarr or h5py group. shallow : bool, optional If True, only copy immediate children of `source`. without_attrs : bool, optional Do not copy user attributes. log : callable, file path or file-like object, optional If provided, will be used to log progress information. if_exists : {'raise', 'replace', 'skip', 'skip_initialized'}, optional How to handle arrays that already exist in the destination group. If 'raise' then a CopyError is raised on the first array already present in the destination group. If 'replace' then any array will be replaced in the destination. If 'skip' then any existing arrays will not be copied. If 'skip_initialized' then any existing arrays with all chunks initialized will not be copied (not available when copying to h5py). dry_run : bool, optional If True, don't actually copy anything, just log what would have happened. **create_kws Passed through to the create_dataset method when copying an array/dataset. Returns ------- n_copied : int Number of items copied. n_skipped : int Number of items skipped. n_bytes_copied : int Number of bytes of data that were actually copied. Examples -------- >>> import h5py >>> import zarr >>> import numpy as np >>> source = h5py.File('data/example.h5', mode='w') >>> foo = source.create_group('foo') >>> baz = foo.create_dataset('bar/baz', data=np.arange(100), chunks=(50,)) >>> spam = source.create_dataset('spam', data=np.arange(100, 200), chunks=(30,)) >>> zarr.tree(source) / ├── foo │ └── bar │ └── baz (100,) int64 └── spam (100,) int64 >>> dest = zarr.group() >>> import sys >>> zarr.copy_all(source, dest, log=sys.stdout) copy /foo copy /foo/bar copy /foo/bar/baz (100,) int64 copy /spam (100,) int64 all done: 4 copied, 0 skipped, 1,600 bytes copied (4, 0, 1600) >>> dest.tree() / ├── foo │ └── bar │ └── baz (100,) int64 └── spam (100,) int64 >>> source.close() Notes ----- Please note that this is an experimental feature. The behaviour of this function is still evolving and the default behaviour and/or parameters may change in future versions. """ # value checks _check_dest_is_group(dest) # setup counting variables n_copied = n_skipped = n_bytes_copied = 0 # setup logging with _LogWriter(log) as log: for k in source.keys(): c, s, b = _copy( log, source[k], dest, name=k, root=False, shallow=shallow, without_attrs=without_attrs, if_exists=if_exists, dry_run=dry_run, **create_kws) n_copied += c n_skipped += s n_bytes_copied += b # log a final message with a summary of what happened _log_copy_summary(log, dry_run, n_copied, n_skipped, n_bytes_copied) return n_copied, n_skipped, n_bytes_copied
python
def copy_all(source, dest, shallow=False, without_attrs=False, log=None, if_exists='raise', dry_run=False, **create_kws): # value checks _check_dest_is_group(dest) # setup counting variables n_copied = n_skipped = n_bytes_copied = 0 # setup logging with _LogWriter(log) as log: for k in source.keys(): c, s, b = _copy( log, source[k], dest, name=k, root=False, shallow=shallow, without_attrs=without_attrs, if_exists=if_exists, dry_run=dry_run, **create_kws) n_copied += c n_skipped += s n_bytes_copied += b # log a final message with a summary of what happened _log_copy_summary(log, dry_run, n_copied, n_skipped, n_bytes_copied) return n_copied, n_skipped, n_bytes_copied
[ "def", "copy_all", "(", "source", ",", "dest", ",", "shallow", "=", "False", ",", "without_attrs", "=", "False", ",", "log", "=", "None", ",", "if_exists", "=", "'raise'", ",", "dry_run", "=", "False", ",", "*", "*", "create_kws", ")", ":", "# value ch...
Copy all children of the `source` group into the `dest` group. Parameters ---------- source : group or array/dataset A zarr group or array, or an h5py group or dataset. dest : group A zarr or h5py group. shallow : bool, optional If True, only copy immediate children of `source`. without_attrs : bool, optional Do not copy user attributes. log : callable, file path or file-like object, optional If provided, will be used to log progress information. if_exists : {'raise', 'replace', 'skip', 'skip_initialized'}, optional How to handle arrays that already exist in the destination group. If 'raise' then a CopyError is raised on the first array already present in the destination group. If 'replace' then any array will be replaced in the destination. If 'skip' then any existing arrays will not be copied. If 'skip_initialized' then any existing arrays with all chunks initialized will not be copied (not available when copying to h5py). dry_run : bool, optional If True, don't actually copy anything, just log what would have happened. **create_kws Passed through to the create_dataset method when copying an array/dataset. Returns ------- n_copied : int Number of items copied. n_skipped : int Number of items skipped. n_bytes_copied : int Number of bytes of data that were actually copied. Examples -------- >>> import h5py >>> import zarr >>> import numpy as np >>> source = h5py.File('data/example.h5', mode='w') >>> foo = source.create_group('foo') >>> baz = foo.create_dataset('bar/baz', data=np.arange(100), chunks=(50,)) >>> spam = source.create_dataset('spam', data=np.arange(100, 200), chunks=(30,)) >>> zarr.tree(source) / ├── foo │ └── bar │ └── baz (100,) int64 └── spam (100,) int64 >>> dest = zarr.group() >>> import sys >>> zarr.copy_all(source, dest, log=sys.stdout) copy /foo copy /foo/bar copy /foo/bar/baz (100,) int64 copy /spam (100,) int64 all done: 4 copied, 0 skipped, 1,600 bytes copied (4, 0, 1600) >>> dest.tree() / ├── foo │ └── bar │ └── baz (100,) int64 └── spam (100,) int64 >>> source.close() Notes ----- Please note that this is an experimental feature. The behaviour of this function is still evolving and the default behaviour and/or parameters may change in future versions.
[ "Copy", "all", "children", "of", "the", "source", "group", "into", "the", "dest", "group", "." ]
fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5
https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/convenience.py#L976-L1077
234,809
zarr-developers/zarr
zarr/convenience.py
consolidate_metadata
def consolidate_metadata(store, metadata_key='.zmetadata'): """ Consolidate all metadata for groups and arrays within the given store into a single resource and put it under the given key. This produces a single object in the backend store, containing all the metadata read from all the zarr-related keys that can be found. After metadata have been consolidated, use :func:`open_consolidated` to open the root group in optimised, read-only mode, using the consolidated metadata to reduce the number of read operations on the backend store. Note, that if the metadata in the store is changed after this consolidation, then the metadata read by :func:`open_consolidated` would be incorrect unless this function is called again. .. note:: This is an experimental feature. Parameters ---------- store : MutableMapping or string Store or path to directory in file system or name of zip file. metadata_key : str Key to put the consolidated metadata under. Returns ------- g : :class:`zarr.hierarchy.Group` Group instance, opened with the new consolidated metadata. See Also -------- open_consolidated """ store = normalize_store_arg(store) def is_zarr_key(key): return (key.endswith('.zarray') or key.endswith('.zgroup') or key.endswith('.zattrs')) out = { 'zarr_consolidated_format': 1, 'metadata': { key: json_loads(store[key]) for key in store if is_zarr_key(key) } } store[metadata_key] = json_dumps(out) return open_consolidated(store, metadata_key=metadata_key)
python
def consolidate_metadata(store, metadata_key='.zmetadata'): store = normalize_store_arg(store) def is_zarr_key(key): return (key.endswith('.zarray') or key.endswith('.zgroup') or key.endswith('.zattrs')) out = { 'zarr_consolidated_format': 1, 'metadata': { key: json_loads(store[key]) for key in store if is_zarr_key(key) } } store[metadata_key] = json_dumps(out) return open_consolidated(store, metadata_key=metadata_key)
[ "def", "consolidate_metadata", "(", "store", ",", "metadata_key", "=", "'.zmetadata'", ")", ":", "store", "=", "normalize_store_arg", "(", "store", ")", "def", "is_zarr_key", "(", "key", ")", ":", "return", "(", "key", ".", "endswith", "(", "'.zarray'", ")",...
Consolidate all metadata for groups and arrays within the given store into a single resource and put it under the given key. This produces a single object in the backend store, containing all the metadata read from all the zarr-related keys that can be found. After metadata have been consolidated, use :func:`open_consolidated` to open the root group in optimised, read-only mode, using the consolidated metadata to reduce the number of read operations on the backend store. Note, that if the metadata in the store is changed after this consolidation, then the metadata read by :func:`open_consolidated` would be incorrect unless this function is called again. .. note:: This is an experimental feature. Parameters ---------- store : MutableMapping or string Store or path to directory in file system or name of zip file. metadata_key : str Key to put the consolidated metadata under. Returns ------- g : :class:`zarr.hierarchy.Group` Group instance, opened with the new consolidated metadata. See Also -------- open_consolidated
[ "Consolidate", "all", "metadata", "for", "groups", "and", "arrays", "within", "the", "given", "store", "into", "a", "single", "resource", "and", "put", "it", "under", "the", "given", "key", "." ]
fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5
https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/convenience.py#L1080-L1128
234,810
zarr-developers/zarr
zarr/convenience.py
open_consolidated
def open_consolidated(store, metadata_key='.zmetadata', mode='r+', **kwargs): """Open group using metadata previously consolidated into a single key. This is an optimised method for opening a Zarr group, where instead of traversing the group/array hierarchy by accessing the metadata keys at each level, a single key contains all of the metadata for everything. For remote data sources where the overhead of accessing a key is large compared to the time to read data. The group accessed must have already had its metadata consolidated into a single key using the function :func:`consolidate_metadata`. This optimised method only works in modes which do not change the metadata, although the data may still be written/updated. Parameters ---------- store : MutableMapping or string Store or path to directory in file system or name of zip file. metadata_key : str Key to read the consolidated metadata from. The default (.zmetadata) corresponds to the default used by :func:`consolidate_metadata`. mode : {'r', 'r+'}, optional Persistence mode: 'r' means read only (must exist); 'r+' means read/write (must exist) although only writes to data are allowed, changes to metadata including creation of new arrays or group are not allowed. **kwargs Additional parameters are passed through to :func:`zarr.creation.open_array` or :func:`zarr.hierarchy.open_group`. Returns ------- g : :class:`zarr.hierarchy.Group` Group instance, opened with the consolidated metadata. See Also -------- consolidate_metadata """ from .storage import ConsolidatedMetadataStore # normalize parameters store = normalize_store_arg(store) if mode not in {'r', 'r+'}: raise ValueError("invalid mode, expected either 'r' or 'r+'; found {!r}" .format(mode)) # setup metadata sotre meta_store = ConsolidatedMetadataStore(store, metadata_key=metadata_key) # pass through return open(store=meta_store, chunk_store=store, mode=mode, **kwargs)
python
def open_consolidated(store, metadata_key='.zmetadata', mode='r+', **kwargs): from .storage import ConsolidatedMetadataStore # normalize parameters store = normalize_store_arg(store) if mode not in {'r', 'r+'}: raise ValueError("invalid mode, expected either 'r' or 'r+'; found {!r}" .format(mode)) # setup metadata sotre meta_store = ConsolidatedMetadataStore(store, metadata_key=metadata_key) # pass through return open(store=meta_store, chunk_store=store, mode=mode, **kwargs)
[ "def", "open_consolidated", "(", "store", ",", "metadata_key", "=", "'.zmetadata'", ",", "mode", "=", "'r+'", ",", "*", "*", "kwargs", ")", ":", "from", ".", "storage", "import", "ConsolidatedMetadataStore", "# normalize parameters", "store", "=", "normalize_store...
Open group using metadata previously consolidated into a single key. This is an optimised method for opening a Zarr group, where instead of traversing the group/array hierarchy by accessing the metadata keys at each level, a single key contains all of the metadata for everything. For remote data sources where the overhead of accessing a key is large compared to the time to read data. The group accessed must have already had its metadata consolidated into a single key using the function :func:`consolidate_metadata`. This optimised method only works in modes which do not change the metadata, although the data may still be written/updated. Parameters ---------- store : MutableMapping or string Store or path to directory in file system or name of zip file. metadata_key : str Key to read the consolidated metadata from. The default (.zmetadata) corresponds to the default used by :func:`consolidate_metadata`. mode : {'r', 'r+'}, optional Persistence mode: 'r' means read only (must exist); 'r+' means read/write (must exist) although only writes to data are allowed, changes to metadata including creation of new arrays or group are not allowed. **kwargs Additional parameters are passed through to :func:`zarr.creation.open_array` or :func:`zarr.hierarchy.open_group`. Returns ------- g : :class:`zarr.hierarchy.Group` Group instance, opened with the consolidated metadata. See Also -------- consolidate_metadata
[ "Open", "group", "using", "metadata", "previously", "consolidated", "into", "a", "single", "key", "." ]
fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5
https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/convenience.py#L1131-L1185
234,811
openstack/horizon
openstack_dashboard/api/cinder.py
volume_list_paged
def volume_list_paged(request, search_opts=None, marker=None, paginate=False, sort_dir="desc"): """List volumes with pagination. To see all volumes in the cloud as an admin you can pass in a special search option: {'all_tenants': 1} """ has_more_data = False has_prev_data = False volumes = [] # To support filtering with group_id, we need to use the microversion. c_client = _cinderclient_with_generic_groups(request) if c_client is None: return volumes, has_more_data, has_prev_data # build a dictionary of volume_id -> transfer transfers = {t.volume_id: t for t in transfer_list(request, search_opts=search_opts)} if VERSIONS.active > 1 and paginate: page_size = utils.get_page_size(request) # sort_key and sort_dir deprecated in kilo, use sort # if pagination is true, we use a single sort parameter # by default, it is "created_at" sort = 'created_at:' + sort_dir for v in c_client.volumes.list(search_opts=search_opts, limit=page_size + 1, marker=marker, sort=sort): v.transfer = transfers.get(v.id) volumes.append(Volume(v)) volumes, has_more_data, has_prev_data = update_pagination( volumes, page_size, marker, sort_dir) else: for v in c_client.volumes.list(search_opts=search_opts): v.transfer = transfers.get(v.id) volumes.append(Volume(v)) return volumes, has_more_data, has_prev_data
python
def volume_list_paged(request, search_opts=None, marker=None, paginate=False, sort_dir="desc"): has_more_data = False has_prev_data = False volumes = [] # To support filtering with group_id, we need to use the microversion. c_client = _cinderclient_with_generic_groups(request) if c_client is None: return volumes, has_more_data, has_prev_data # build a dictionary of volume_id -> transfer transfers = {t.volume_id: t for t in transfer_list(request, search_opts=search_opts)} if VERSIONS.active > 1 and paginate: page_size = utils.get_page_size(request) # sort_key and sort_dir deprecated in kilo, use sort # if pagination is true, we use a single sort parameter # by default, it is "created_at" sort = 'created_at:' + sort_dir for v in c_client.volumes.list(search_opts=search_opts, limit=page_size + 1, marker=marker, sort=sort): v.transfer = transfers.get(v.id) volumes.append(Volume(v)) volumes, has_more_data, has_prev_data = update_pagination( volumes, page_size, marker, sort_dir) else: for v in c_client.volumes.list(search_opts=search_opts): v.transfer = transfers.get(v.id) volumes.append(Volume(v)) return volumes, has_more_data, has_prev_data
[ "def", "volume_list_paged", "(", "request", ",", "search_opts", "=", "None", ",", "marker", "=", "None", ",", "paginate", "=", "False", ",", "sort_dir", "=", "\"desc\"", ")", ":", "has_more_data", "=", "False", "has_prev_data", "=", "False", "volumes", "=", ...
List volumes with pagination. To see all volumes in the cloud as an admin you can pass in a special search option: {'all_tenants': 1}
[ "List", "volumes", "with", "pagination", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/cinder.py#L341-L380
234,812
openstack/horizon
openstack_dashboard/api/cinder.py
extension_supported
def extension_supported(request, extension_name): """This method will determine if Cinder supports a given extension name.""" for extension in list_extensions(request): if extension.name == extension_name: return True return False
python
def extension_supported(request, extension_name): for extension in list_extensions(request): if extension.name == extension_name: return True return False
[ "def", "extension_supported", "(", "request", ",", "extension_name", ")", ":", "for", "extension", "in", "list_extensions", "(", "request", ")", ":", "if", "extension", ".", "name", "==", "extension_name", ":", "return", "True", "return", "False" ]
This method will determine if Cinder supports a given extension name.
[ "This", "method", "will", "determine", "if", "Cinder", "supports", "a", "given", "extension", "name", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/cinder.py#L1069-L1074
234,813
openstack/horizon
openstack_dashboard/api/cinder.py
transfer_list
def transfer_list(request, detailed=True, search_opts=None): """List volume transfers. To see all volumes transfers as an admin pass in a special search option: {'all_tenants': 1} """ c_client = cinderclient(request) try: return [VolumeTransfer(v) for v in c_client.transfers.list( detailed=detailed, search_opts=search_opts)] except cinder_exception.Forbidden as error: LOG.error(error) return []
python
def transfer_list(request, detailed=True, search_opts=None): c_client = cinderclient(request) try: return [VolumeTransfer(v) for v in c_client.transfers.list( detailed=detailed, search_opts=search_opts)] except cinder_exception.Forbidden as error: LOG.error(error) return []
[ "def", "transfer_list", "(", "request", ",", "detailed", "=", "True", ",", "search_opts", "=", "None", ")", ":", "c_client", "=", "cinderclient", "(", "request", ")", "try", ":", "return", "[", "VolumeTransfer", "(", "v", ")", "for", "v", "in", "c_client...
List volume transfers. To see all volumes transfers as an admin pass in a special search option: {'all_tenants': 1}
[ "List", "volume", "transfers", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/cinder.py#L1078-L1090
234,814
openstack/horizon
openstack_dashboard/usage/quotas.py
tenant_quota_usages
def tenant_quota_usages(request, tenant_id=None, targets=None): """Get our quotas and construct our usage object. :param tenant_id: Target tenant ID. If no tenant_id is provided, a the request.user.project_id is assumed to be used. :param targets: A tuple of quota names to be retrieved. If unspecified, all quota and usage information is retrieved. """ if not tenant_id: tenant_id = request.user.project_id disabled_quotas = get_disabled_quotas(request, targets) usages = QuotaUsage() futurist_utils.call_functions_parallel( (_get_tenant_compute_usages, [request, usages, disabled_quotas, tenant_id]), (_get_tenant_network_usages, [request, usages, disabled_quotas, tenant_id]), (_get_tenant_volume_usages, [request, usages, disabled_quotas, tenant_id])) return usages
python
def tenant_quota_usages(request, tenant_id=None, targets=None): if not tenant_id: tenant_id = request.user.project_id disabled_quotas = get_disabled_quotas(request, targets) usages = QuotaUsage() futurist_utils.call_functions_parallel( (_get_tenant_compute_usages, [request, usages, disabled_quotas, tenant_id]), (_get_tenant_network_usages, [request, usages, disabled_quotas, tenant_id]), (_get_tenant_volume_usages, [request, usages, disabled_quotas, tenant_id])) return usages
[ "def", "tenant_quota_usages", "(", "request", ",", "tenant_id", "=", "None", ",", "targets", "=", "None", ")", ":", "if", "not", "tenant_id", ":", "tenant_id", "=", "request", ".", "user", ".", "project_id", "disabled_quotas", "=", "get_disabled_quotas", "(", ...
Get our quotas and construct our usage object. :param tenant_id: Target tenant ID. If no tenant_id is provided, a the request.user.project_id is assumed to be used. :param targets: A tuple of quota names to be retrieved. If unspecified, all quota and usage information is retrieved.
[ "Get", "our", "quotas", "and", "construct", "our", "usage", "object", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/usage/quotas.py#L413-L435
234,815
openstack/horizon
openstack_dashboard/usage/quotas.py
QuotaUsage.add_quota
def add_quota(self, quota): """Adds an internal tracking reference for the given quota.""" if quota.limit in (None, -1, float('inf')): # Handle "unlimited" quotas. self.usages[quota.name]['quota'] = float("inf") self.usages[quota.name]['available'] = float("inf") else: self.usages[quota.name]['quota'] = int(quota.limit)
python
def add_quota(self, quota): if quota.limit in (None, -1, float('inf')): # Handle "unlimited" quotas. self.usages[quota.name]['quota'] = float("inf") self.usages[quota.name]['available'] = float("inf") else: self.usages[quota.name]['quota'] = int(quota.limit)
[ "def", "add_quota", "(", "self", ",", "quota", ")", ":", "if", "quota", ".", "limit", "in", "(", "None", ",", "-", "1", ",", "float", "(", "'inf'", ")", ")", ":", "# Handle \"unlimited\" quotas.", "self", ".", "usages", "[", "quota", ".", "name", "]"...
Adds an internal tracking reference for the given quota.
[ "Adds", "an", "internal", "tracking", "reference", "for", "the", "given", "quota", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/usage/quotas.py#L141-L148
234,816
openstack/horizon
openstack_dashboard/usage/quotas.py
QuotaUsage.tally
def tally(self, name, value): """Adds to the "used" metric for the given quota.""" value = value or 0 # Protection against None. # Start at 0 if this is the first value. if 'used' not in self.usages[name]: self.usages[name]['used'] = 0 # Increment our usage and update the "available" metric. self.usages[name]['used'] += int(value) # Fail if can't coerce to int. self.update_available(name)
python
def tally(self, name, value): value = value or 0 # Protection against None. # Start at 0 if this is the first value. if 'used' not in self.usages[name]: self.usages[name]['used'] = 0 # Increment our usage and update the "available" metric. self.usages[name]['used'] += int(value) # Fail if can't coerce to int. self.update_available(name)
[ "def", "tally", "(", "self", ",", "name", ",", "value", ")", ":", "value", "=", "value", "or", "0", "# Protection against None.", "# Start at 0 if this is the first value.", "if", "'used'", "not", "in", "self", ".", "usages", "[", "name", "]", ":", "self", "...
Adds to the "used" metric for the given quota.
[ "Adds", "to", "the", "used", "metric", "for", "the", "given", "quota", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/usage/quotas.py#L150-L158
234,817
openstack/horizon
openstack_dashboard/usage/quotas.py
QuotaUsage.update_available
def update_available(self, name): """Updates the "available" metric for the given quota.""" quota = self.usages.get(name, {}).get('quota', float('inf')) available = quota - self.usages[name]['used'] if available < 0: available = 0 self.usages[name]['available'] = available
python
def update_available(self, name): quota = self.usages.get(name, {}).get('quota', float('inf')) available = quota - self.usages[name]['used'] if available < 0: available = 0 self.usages[name]['available'] = available
[ "def", "update_available", "(", "self", ",", "name", ")", ":", "quota", "=", "self", ".", "usages", ".", "get", "(", "name", ",", "{", "}", ")", ".", "get", "(", "'quota'", ",", "float", "(", "'inf'", ")", ")", "available", "=", "quota", "-", "se...
Updates the "available" metric for the given quota.
[ "Updates", "the", "available", "metric", "for", "the", "given", "quota", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/usage/quotas.py#L160-L166
234,818
openstack/horizon
openstack_dashboard/dashboards/project/instances/views.py
process_non_api_filters
def process_non_api_filters(search_opts, non_api_filter_info): """Process filters by non-API fields There are cases where it is useful to provide a filter field which does not exist in a resource in a backend service. For example, nova server list provides 'image' field with image ID but 'image name' is more useful for GUI users. This function replaces fake fields into corresponding real fields. The format of non_api_filter_info is a tuple/list of (fake_field, real_field, resources). This returns True if further lookup is required. It returns False if there are no matching resources, for example, if no corresponding real field exists. """ for fake_field, real_field, resources in non_api_filter_info: if not _swap_filter(resources, search_opts, fake_field, real_field): return False return True
python
def process_non_api_filters(search_opts, non_api_filter_info): for fake_field, real_field, resources in non_api_filter_info: if not _swap_filter(resources, search_opts, fake_field, real_field): return False return True
[ "def", "process_non_api_filters", "(", "search_opts", ",", "non_api_filter_info", ")", ":", "for", "fake_field", ",", "real_field", ",", "resources", "in", "non_api_filter_info", ":", "if", "not", "_swap_filter", "(", "resources", ",", "search_opts", ",", "fake_fiel...
Process filters by non-API fields There are cases where it is useful to provide a filter field which does not exist in a resource in a backend service. For example, nova server list provides 'image' field with image ID but 'image name' is more useful for GUI users. This function replaces fake fields into corresponding real fields. The format of non_api_filter_info is a tuple/list of (fake_field, real_field, resources). This returns True if further lookup is required. It returns False if there are no matching resources, for example, if no corresponding real field exists.
[ "Process", "filters", "by", "non", "-", "API", "fields" ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/dashboards/project/instances/views.py#L202-L221
234,819
openstack/horizon
horizon/utils/validators.py
validate_port_or_colon_separated_port_range
def validate_port_or_colon_separated_port_range(port_range): """Accepts a port number or a single-colon separated range.""" if port_range.count(':') > 1: raise ValidationError(_("One colon allowed in port range")) ports = port_range.split(':') for port in ports: validate_port_range(port)
python
def validate_port_or_colon_separated_port_range(port_range): if port_range.count(':') > 1: raise ValidationError(_("One colon allowed in port range")) ports = port_range.split(':') for port in ports: validate_port_range(port)
[ "def", "validate_port_or_colon_separated_port_range", "(", "port_range", ")", ":", "if", "port_range", ".", "count", "(", "':'", ")", ">", "1", ":", "raise", "ValidationError", "(", "_", "(", "\"One colon allowed in port range\"", ")", ")", "ports", "=", "port_ran...
Accepts a port number or a single-colon separated range.
[ "Accepts", "a", "port", "number", "or", "a", "single", "-", "colon", "separated", "range", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/utils/validators.py#L58-L64
234,820
openstack/horizon
openstack_dashboard/utils/settings.py
import_submodules
def import_submodules(module): """Import all submodules and make them available in a dict.""" submodules = {} for loader, name, ispkg in pkgutil.iter_modules(module.__path__, module.__name__ + '.'): try: submodule = import_module(name) except ImportError as e: # FIXME: Make the errors non-fatal (do we want that?). logging.warning("Error importing %s", name) logging.exception(e) else: parent, child = name.rsplit('.', 1) submodules[child] = submodule return submodules
python
def import_submodules(module): submodules = {} for loader, name, ispkg in pkgutil.iter_modules(module.__path__, module.__name__ + '.'): try: submodule = import_module(name) except ImportError as e: # FIXME: Make the errors non-fatal (do we want that?). logging.warning("Error importing %s", name) logging.exception(e) else: parent, child = name.rsplit('.', 1) submodules[child] = submodule return submodules
[ "def", "import_submodules", "(", "module", ")", ":", "submodules", "=", "{", "}", "for", "loader", ",", "name", ",", "ispkg", "in", "pkgutil", ".", "iter_modules", "(", "module", ".", "__path__", ",", "module", ".", "__name__", "+", "'.'", ")", ":", "t...
Import all submodules and make them available in a dict.
[ "Import", "all", "submodules", "and", "make", "them", "available", "in", "a", "dict", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/utils/settings.py#L24-L38
234,821
openstack/horizon
openstack_dashboard/utils/settings.py
import_dashboard_config
def import_dashboard_config(modules): """Imports configuration from all the modules and merges it.""" config = collections.defaultdict(dict) for module in modules: for submodule in import_submodules(module).values(): if hasattr(submodule, 'DASHBOARD'): dashboard = submodule.DASHBOARD config[dashboard].update(submodule.__dict__) elif (hasattr(submodule, 'PANEL') or hasattr(submodule, 'PANEL_GROUP') or hasattr(submodule, 'FEATURE')): # If enabled and local.enabled contains a same filename, # the file loaded later (i.e., local.enabled) will be used. name = submodule.__name__.rsplit('.', 1)[1] config[name] = submodule.__dict__ else: logging.warning("Skipping %s because it doesn't have DASHBOARD" ", PANEL, PANEL_GROUP, or FEATURE defined.", submodule.__name__) return sorted(config.items(), key=lambda c: c[1]['__name__'].rsplit('.', 1)[1])
python
def import_dashboard_config(modules): config = collections.defaultdict(dict) for module in modules: for submodule in import_submodules(module).values(): if hasattr(submodule, 'DASHBOARD'): dashboard = submodule.DASHBOARD config[dashboard].update(submodule.__dict__) elif (hasattr(submodule, 'PANEL') or hasattr(submodule, 'PANEL_GROUP') or hasattr(submodule, 'FEATURE')): # If enabled and local.enabled contains a same filename, # the file loaded later (i.e., local.enabled) will be used. name = submodule.__name__.rsplit('.', 1)[1] config[name] = submodule.__dict__ else: logging.warning("Skipping %s because it doesn't have DASHBOARD" ", PANEL, PANEL_GROUP, or FEATURE defined.", submodule.__name__) return sorted(config.items(), key=lambda c: c[1]['__name__'].rsplit('.', 1)[1])
[ "def", "import_dashboard_config", "(", "modules", ")", ":", "config", "=", "collections", ".", "defaultdict", "(", "dict", ")", "for", "module", "in", "modules", ":", "for", "submodule", "in", "import_submodules", "(", "module", ")", ".", "values", "(", ")",...
Imports configuration from all the modules and merges it.
[ "Imports", "configuration", "from", "all", "the", "modules", "and", "merges", "it", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/utils/settings.py#L41-L61
234,822
openstack/horizon
openstack_dashboard/utils/settings.py
get_xstatic_dirs
def get_xstatic_dirs(XSTATIC_MODULES, HORIZON_CONFIG): """Discover static file configuration of the xstatic modules. For each entry in the XSTATIC_MODULES list we determine the entry point files (which may come from the xstatic MAIN var) and then determine where in the Django static tree the xstatic package's contents should be placed. For jquery.bootstrap.wizard.js the module name is None the static file is actually a 3rd-party file but resides in the Horizon source tree and not an xstatic package. The xstatic.pkg.jquery_ui package had its contents moved by packagers so it must be handled as a special case. """ STATICFILES_DIRS = [] HORIZON_CONFIG.setdefault('xstatic_lib_files', []) for module_name, files in XSTATIC_MODULES: module = import_module(module_name) if module_name == 'xstatic.pkg.jquery_ui': # determine the correct path for jquery-ui which packagers moved if module.VERSION.startswith('1.10.'): # The 1.10.x versions already contain 'ui' directory. files = ['ui/' + files[0]] STATICFILES_DIRS.append( ('horizon/lib/' + module.NAME, module.BASE_DIR) ) # pull the file entry points from the xstatic package MAIN if possible if hasattr(module, 'MAIN'): files = module.MAIN if not isinstance(files, list): files = [files] # just the Javascript files, please (don't <script> css, etc # which is explicitly included in style/themes as appropriate) files = [file for file in files if file.endswith('.js')] # add to the list of files to link in the HTML try: for file in files: file = 'horizon/lib/' + module.NAME + '/' + file HORIZON_CONFIG['xstatic_lib_files'].append(file) except TypeError: raise Exception( '%s: Nothing to include because files to include are not ' 'defined (i.e., None) in BASE_XSTATIC_MODULES list and ' 'a corresponding XStatic module does not define MAIN list.' % module_name) return STATICFILES_DIRS
python
def get_xstatic_dirs(XSTATIC_MODULES, HORIZON_CONFIG): STATICFILES_DIRS = [] HORIZON_CONFIG.setdefault('xstatic_lib_files', []) for module_name, files in XSTATIC_MODULES: module = import_module(module_name) if module_name == 'xstatic.pkg.jquery_ui': # determine the correct path for jquery-ui which packagers moved if module.VERSION.startswith('1.10.'): # The 1.10.x versions already contain 'ui' directory. files = ['ui/' + files[0]] STATICFILES_DIRS.append( ('horizon/lib/' + module.NAME, module.BASE_DIR) ) # pull the file entry points from the xstatic package MAIN if possible if hasattr(module, 'MAIN'): files = module.MAIN if not isinstance(files, list): files = [files] # just the Javascript files, please (don't <script> css, etc # which is explicitly included in style/themes as appropriate) files = [file for file in files if file.endswith('.js')] # add to the list of files to link in the HTML try: for file in files: file = 'horizon/lib/' + module.NAME + '/' + file HORIZON_CONFIG['xstatic_lib_files'].append(file) except TypeError: raise Exception( '%s: Nothing to include because files to include are not ' 'defined (i.e., None) in BASE_XSTATIC_MODULES list and ' 'a corresponding XStatic module does not define MAIN list.' % module_name) return STATICFILES_DIRS
[ "def", "get_xstatic_dirs", "(", "XSTATIC_MODULES", ",", "HORIZON_CONFIG", ")", ":", "STATICFILES_DIRS", "=", "[", "]", "HORIZON_CONFIG", ".", "setdefault", "(", "'xstatic_lib_files'", ",", "[", "]", ")", "for", "module_name", ",", "files", "in", "XSTATIC_MODULES",...
Discover static file configuration of the xstatic modules. For each entry in the XSTATIC_MODULES list we determine the entry point files (which may come from the xstatic MAIN var) and then determine where in the Django static tree the xstatic package's contents should be placed. For jquery.bootstrap.wizard.js the module name is None the static file is actually a 3rd-party file but resides in the Horizon source tree and not an xstatic package. The xstatic.pkg.jquery_ui package had its contents moved by packagers so it must be handled as a special case.
[ "Discover", "static", "file", "configuration", "of", "the", "xstatic", "modules", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/utils/settings.py#L242-L293
234,823
openstack/horizon
openstack_dashboard/api/nova.py
upgrade_api
def upgrade_api(request, client, version): """Ugrade the nova API to the specified version if possible.""" min_ver, max_ver = api_versions._get_server_version_range(client) if min_ver <= api_versions.APIVersion(version) <= max_ver: client = _nova.novaclient(request, version) return client
python
def upgrade_api(request, client, version): min_ver, max_ver = api_versions._get_server_version_range(client) if min_ver <= api_versions.APIVersion(version) <= max_ver: client = _nova.novaclient(request, version) return client
[ "def", "upgrade_api", "(", "request", ",", "client", ",", "version", ")", ":", "min_ver", ",", "max_ver", "=", "api_versions", ".", "_get_server_version_range", "(", "client", ")", "if", "min_ver", "<=", "api_versions", ".", "APIVersion", "(", "version", ")", ...
Ugrade the nova API to the specified version if possible.
[ "Ugrade", "the", "nova", "API", "to", "the", "specified", "version", "if", "possible", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/nova.py#L192-L198
234,824
openstack/horizon
openstack_dashboard/api/nova.py
add_tenant_to_flavor
def add_tenant_to_flavor(request, flavor, tenant): """Add a tenant to the given flavor access list.""" return _nova.novaclient(request).flavor_access.add_tenant_access( flavor=flavor, tenant=tenant)
python
def add_tenant_to_flavor(request, flavor, tenant): return _nova.novaclient(request).flavor_access.add_tenant_access( flavor=flavor, tenant=tenant)
[ "def", "add_tenant_to_flavor", "(", "request", ",", "flavor", ",", "tenant", ")", ":", "return", "_nova", ".", "novaclient", "(", "request", ")", ".", "flavor_access", ".", "add_tenant_access", "(", "flavor", "=", "flavor", ",", "tenant", "=", "tenant", ")" ...
Add a tenant to the given flavor access list.
[ "Add", "a", "tenant", "to", "the", "given", "flavor", "access", "list", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/nova.py#L336-L339
234,825
openstack/horizon
openstack_dashboard/api/nova.py
remove_tenant_from_flavor
def remove_tenant_from_flavor(request, flavor, tenant): """Remove a tenant from the given flavor access list.""" return _nova.novaclient(request).flavor_access.remove_tenant_access( flavor=flavor, tenant=tenant)
python
def remove_tenant_from_flavor(request, flavor, tenant): return _nova.novaclient(request).flavor_access.remove_tenant_access( flavor=flavor, tenant=tenant)
[ "def", "remove_tenant_from_flavor", "(", "request", ",", "flavor", ",", "tenant", ")", ":", "return", "_nova", ".", "novaclient", "(", "request", ")", ".", "flavor_access", ".", "remove_tenant_access", "(", "flavor", "=", "flavor", ",", "tenant", "=", "tenant"...
Remove a tenant from the given flavor access list.
[ "Remove", "a", "tenant", "from", "the", "given", "flavor", "access", "list", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/nova.py#L343-L346
234,826
openstack/horizon
openstack_dashboard/api/nova.py
flavor_get_extras
def flavor_get_extras(request, flavor_id, raw=False, flavor=None): """Get flavor extra specs.""" if flavor is None: flavor = _nova.novaclient(request).flavors.get(flavor_id) extras = flavor.get_keys() if raw: return extras return [FlavorExtraSpec(flavor_id, key, value) for key, value in extras.items()]
python
def flavor_get_extras(request, flavor_id, raw=False, flavor=None): if flavor is None: flavor = _nova.novaclient(request).flavors.get(flavor_id) extras = flavor.get_keys() if raw: return extras return [FlavorExtraSpec(flavor_id, key, value) for key, value in extras.items()]
[ "def", "flavor_get_extras", "(", "request", ",", "flavor_id", ",", "raw", "=", "False", ",", "flavor", "=", "None", ")", ":", "if", "flavor", "is", "None", ":", "flavor", "=", "_nova", ".", "novaclient", "(", "request", ")", ".", "flavors", ".", "get",...
Get flavor extra specs.
[ "Get", "flavor", "extra", "specs", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/nova.py#L350-L358
234,827
openstack/horizon
openstack_dashboard/api/nova.py
flavor_extra_delete
def flavor_extra_delete(request, flavor_id, keys): """Unset the flavor extra spec keys.""" flavor = _nova.novaclient(request).flavors.get(flavor_id) return flavor.unset_keys(keys)
python
def flavor_extra_delete(request, flavor_id, keys): flavor = _nova.novaclient(request).flavors.get(flavor_id) return flavor.unset_keys(keys)
[ "def", "flavor_extra_delete", "(", "request", ",", "flavor_id", ",", "keys", ")", ":", "flavor", "=", "_nova", ".", "novaclient", "(", "request", ")", ".", "flavors", ".", "get", "(", "flavor_id", ")", "return", "flavor", ".", "unset_keys", "(", "keys", ...
Unset the flavor extra spec keys.
[ "Unset", "the", "flavor", "extra", "spec", "keys", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/nova.py#L362-L365
234,828
openstack/horizon
openstack_dashboard/api/nova.py
flavor_extra_set
def flavor_extra_set(request, flavor_id, metadata): """Set the flavor extra spec keys.""" flavor = _nova.novaclient(request).flavors.get(flavor_id) if (not metadata): # not a way to delete keys return None return flavor.set_keys(metadata)
python
def flavor_extra_set(request, flavor_id, metadata): flavor = _nova.novaclient(request).flavors.get(flavor_id) if (not metadata): # not a way to delete keys return None return flavor.set_keys(metadata)
[ "def", "flavor_extra_set", "(", "request", ",", "flavor_id", ",", "metadata", ")", ":", "flavor", "=", "_nova", ".", "novaclient", "(", "request", ")", ".", "flavors", ".", "get", "(", "flavor_id", ")", "if", "(", "not", "metadata", ")", ":", "# not a wa...
Set the flavor extra spec keys.
[ "Set", "the", "flavor", "extra", "spec", "keys", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/nova.py#L369-L374
234,829
openstack/horizon
openstack_dashboard/api/nova.py
server_console_output
def server_console_output(request, instance_id, tail_length=None): """Gets console output of an instance.""" nc = _nova.novaclient(request) return nc.servers.get_console_output(instance_id, length=tail_length)
python
def server_console_output(request, instance_id, tail_length=None): nc = _nova.novaclient(request) return nc.servers.get_console_output(instance_id, length=tail_length)
[ "def", "server_console_output", "(", "request", ",", "instance_id", ",", "tail_length", "=", "None", ")", ":", "nc", "=", "_nova", ".", "novaclient", "(", "request", ")", "return", "nc", ".", "servers", ".", "get_console_output", "(", "instance_id", ",", "le...
Gets console output of an instance.
[ "Gets", "console", "output", "of", "an", "instance", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/nova.py#L533-L536
234,830
openstack/horizon
openstack_dashboard/api/nova.py
list_extensions
def list_extensions(request): """List all nova extensions, except the ones in the blacklist.""" blacklist = set(getattr(settings, 'OPENSTACK_NOVA_EXTENSIONS_BLACKLIST', [])) nova_api = _nova.novaclient(request) return tuple( extension for extension in nova_list_extensions.ListExtManager(nova_api).show_all() if extension.name not in blacklist )
python
def list_extensions(request): blacklist = set(getattr(settings, 'OPENSTACK_NOVA_EXTENSIONS_BLACKLIST', [])) nova_api = _nova.novaclient(request) return tuple( extension for extension in nova_list_extensions.ListExtManager(nova_api).show_all() if extension.name not in blacklist )
[ "def", "list_extensions", "(", "request", ")", ":", "blacklist", "=", "set", "(", "getattr", "(", "settings", ",", "'OPENSTACK_NOVA_EXTENSIONS_BLACKLIST'", ",", "[", "]", ")", ")", "nova_api", "=", "_nova", ".", "novaclient", "(", "request", ")", "return", "...
List all nova extensions, except the ones in the blacklist.
[ "List", "all", "nova", "extensions", "except", "the", "ones", "in", "the", "blacklist", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/nova.py#L1012-L1021
234,831
openstack/horizon
openstack_dashboard/api/nova.py
extension_supported
def extension_supported(extension_name, request): """Determine if nova supports a given extension name. Example values for the extension_name include AdminActions, ConsoleOutput, etc. """ for ext in list_extensions(request): if ext.name == extension_name: return True return False
python
def extension_supported(extension_name, request): for ext in list_extensions(request): if ext.name == extension_name: return True return False
[ "def", "extension_supported", "(", "extension_name", ",", "request", ")", ":", "for", "ext", "in", "list_extensions", "(", "request", ")", ":", "if", "ext", ".", "name", "==", "extension_name", ":", "return", "True", "return", "False" ]
Determine if nova supports a given extension name. Example values for the extension_name include AdminActions, ConsoleOutput, etc.
[ "Determine", "if", "nova", "supports", "a", "given", "extension", "name", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/nova.py#L1026-L1035
234,832
openstack/horizon
openstack_dashboard/utils/futurist_utils.py
call_functions_parallel
def call_functions_parallel(*worker_defs): """Call specified functions in parallel. :param *worker_defs: Each positional argument can be either of a function to be called or a tuple which consists of a function, a list of positional arguments) and keyword arguments (optional). If you need to pass arguments, you need to pass a tuple. Example usages are like: call_functions_parallel(func1, func2, func3) call_functions_parallel(func1, (func2, [1, 2])) call_functions_parallel((func1, [], {'a': 1}), (func2, [], {'a': 2, 'b': 10})) :returns: a tuple of values returned from individual functions. None is returned if a corresponding function does not return. It is better to return values other than None from individual functions. """ # TODO(amotoki): Needs to figure out what max_workers can be specified. # According to e0ne, the apache default configuration in devstack allows # only 10 threads. What happens if max_worker=11 is specified? max_workers = len(worker_defs) # Prepare a list with enough length. futures = [None] * len(worker_defs) with futurist.ThreadPoolExecutor(max_workers=max_workers) as e: for index, func_def in enumerate(worker_defs): if callable(func_def): func_def = [func_def] args = func_def[1] if len(func_def) > 1 else [] kwargs = func_def[2] if len(func_def) > 2 else {} func = functools.partial(func_def[0], *args, **kwargs) futures[index] = e.submit(fn=func) return tuple(f.result() for f in futures)
python
def call_functions_parallel(*worker_defs): # TODO(amotoki): Needs to figure out what max_workers can be specified. # According to e0ne, the apache default configuration in devstack allows # only 10 threads. What happens if max_worker=11 is specified? max_workers = len(worker_defs) # Prepare a list with enough length. futures = [None] * len(worker_defs) with futurist.ThreadPoolExecutor(max_workers=max_workers) as e: for index, func_def in enumerate(worker_defs): if callable(func_def): func_def = [func_def] args = func_def[1] if len(func_def) > 1 else [] kwargs = func_def[2] if len(func_def) > 2 else {} func = functools.partial(func_def[0], *args, **kwargs) futures[index] = e.submit(fn=func) return tuple(f.result() for f in futures)
[ "def", "call_functions_parallel", "(", "*", "worker_defs", ")", ":", "# TODO(amotoki): Needs to figure out what max_workers can be specified.", "# According to e0ne, the apache default configuration in devstack allows", "# only 10 threads. What happens if max_worker=11 is specified?", "max_work...
Call specified functions in parallel. :param *worker_defs: Each positional argument can be either of a function to be called or a tuple which consists of a function, a list of positional arguments) and keyword arguments (optional). If you need to pass arguments, you need to pass a tuple. Example usages are like: call_functions_parallel(func1, func2, func3) call_functions_parallel(func1, (func2, [1, 2])) call_functions_parallel((func1, [], {'a': 1}), (func2, [], {'a': 2, 'b': 10})) :returns: a tuple of values returned from individual functions. None is returned if a corresponding function does not return. It is better to return values other than None from individual functions.
[ "Call", "specified", "functions", "in", "parallel", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/utils/futurist_utils.py#L18-L50
234,833
openstack/horizon
horizon/utils/secret_key.py
generate_key
def generate_key(key_length=64): """Secret key generator. The quality of randomness depends on operating system support, see http://docs.python.org/library/random.html#random.SystemRandom. """ if hasattr(random, 'SystemRandom'): logging.info('Generating a secure random key using SystemRandom.') choice = random.SystemRandom().choice else: msg = "WARNING: SystemRandom not present. Generating a random "\ "key using random.choice (NOT CRYPTOGRAPHICALLY SECURE)." logging.warning(msg) choice = random.choice return ''.join(map(lambda x: choice(string.digits + string.ascii_letters), range(key_length)))
python
def generate_key(key_length=64): if hasattr(random, 'SystemRandom'): logging.info('Generating a secure random key using SystemRandom.') choice = random.SystemRandom().choice else: msg = "WARNING: SystemRandom not present. Generating a random "\ "key using random.choice (NOT CRYPTOGRAPHICALLY SECURE)." logging.warning(msg) choice = random.choice return ''.join(map(lambda x: choice(string.digits + string.ascii_letters), range(key_length)))
[ "def", "generate_key", "(", "key_length", "=", "64", ")", ":", "if", "hasattr", "(", "random", ",", "'SystemRandom'", ")", ":", "logging", ".", "info", "(", "'Generating a secure random key using SystemRandom.'", ")", "choice", "=", "random", ".", "SystemRandom", ...
Secret key generator. The quality of randomness depends on operating system support, see http://docs.python.org/library/random.html#random.SystemRandom.
[ "Secret", "key", "generator", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/utils/secret_key.py#L28-L43
234,834
openstack/horizon
horizon/utils/secret_key.py
generate_or_read_from_file
def generate_or_read_from_file(key_file='.secret_key', key_length=64): """Multiprocess-safe secret key file generator. Useful to replace the default (and thus unsafe) SECRET_KEY in settings.py upon first start. Save to use, i.e. when multiple Python interpreters serve the dashboard Django application (e.g. in a mod_wsgi + daemonized environment). Also checks if file permissions are set correctly and throws an exception if not. """ abspath = os.path.abspath(key_file) # check, if key_file already exists # if yes, then just read and return key if os.path.exists(key_file): key = read_from_file(key_file) return key # otherwise, first lock to make sure only one process lock = lockutils.external_lock(key_file + ".lock", lock_path=os.path.dirname(abspath)) with lock: if not os.path.exists(key_file): key = generate_key(key_length) old_umask = os.umask(0o177) # Use '0600' file permissions with open(key_file, 'w') as f: f.write(key) os.umask(old_umask) else: key = read_from_file(key_file) return key
python
def generate_or_read_from_file(key_file='.secret_key', key_length=64): abspath = os.path.abspath(key_file) # check, if key_file already exists # if yes, then just read and return key if os.path.exists(key_file): key = read_from_file(key_file) return key # otherwise, first lock to make sure only one process lock = lockutils.external_lock(key_file + ".lock", lock_path=os.path.dirname(abspath)) with lock: if not os.path.exists(key_file): key = generate_key(key_length) old_umask = os.umask(0o177) # Use '0600' file permissions with open(key_file, 'w') as f: f.write(key) os.umask(old_umask) else: key = read_from_file(key_file) return key
[ "def", "generate_or_read_from_file", "(", "key_file", "=", "'.secret_key'", ",", "key_length", "=", "64", ")", ":", "abspath", "=", "os", ".", "path", ".", "abspath", "(", "key_file", ")", "# check, if key_file already exists", "# if yes, then just read and return key",...
Multiprocess-safe secret key file generator. Useful to replace the default (and thus unsafe) SECRET_KEY in settings.py upon first start. Save to use, i.e. when multiple Python interpreters serve the dashboard Django application (e.g. in a mod_wsgi + daemonized environment). Also checks if file permissions are set correctly and throws an exception if not.
[ "Multiprocess", "-", "safe", "secret", "key", "file", "generator", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/utils/secret_key.py#L56-L84
234,835
openstack/horizon
openstack_dashboard/api/rest/urls.py
register
def register(view): """Register API views to respond to a regex pattern. ``url_regex`` on a wrapped view class is used as the regex pattern. The view should be a standard Django class-based view implementing an as_view() method. The url_regex attribute of the view should be a standard Django URL regex pattern. """ p = urls.url(view.url_regex, view.as_view()) urlpatterns.append(p) return view
python
def register(view): p = urls.url(view.url_regex, view.as_view()) urlpatterns.append(p) return view
[ "def", "register", "(", "view", ")", ":", "p", "=", "urls", ".", "url", "(", "view", ".", "url_regex", ",", "view", ".", "as_view", "(", ")", ")", "urlpatterns", ".", "append", "(", "p", ")", "return", "view" ]
Register API views to respond to a regex pattern. ``url_regex`` on a wrapped view class is used as the regex pattern. The view should be a standard Django class-based view implementing an as_view() method. The url_regex attribute of the view should be a standard Django URL regex pattern.
[ "Register", "API", "views", "to", "respond", "to", "a", "regex", "pattern", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/rest/urls.py#L22-L32
234,836
openstack/horizon
horizon/templatetags/shellfilter.py
shellfilter
def shellfilter(value): """Replace HTML chars for shell usage.""" replacements = {'\\': '\\\\', '`': '\\`', "'": "\\'", '"': '\\"'} for search, repl in replacements.items(): value = value.replace(search, repl) return safestring.mark_safe(value)
python
def shellfilter(value): replacements = {'\\': '\\\\', '`': '\\`', "'": "\\'", '"': '\\"'} for search, repl in replacements.items(): value = value.replace(search, repl) return safestring.mark_safe(value)
[ "def", "shellfilter", "(", "value", ")", ":", "replacements", "=", "{", "'\\\\'", ":", "'\\\\\\\\'", ",", "'`'", ":", "'\\\\`'", ",", "\"'\"", ":", "\"\\\\'\"", ",", "'\"'", ":", "'\\\\\"'", "}", "for", "search", ",", "repl", "in", "replacements", ".", ...
Replace HTML chars for shell usage.
[ "Replace", "HTML", "chars", "for", "shell", "usage", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/templatetags/shellfilter.py#L22-L30
234,837
openstack/horizon
openstack_auth/views.py
websso
def websso(request): """Logs a user in using a token from Keystone's POST.""" referer = request.META.get('HTTP_REFERER', settings.OPENSTACK_KEYSTONE_URL) auth_url = utils.clean_up_auth_url(referer) token = request.POST.get('token') try: request.user = auth.authenticate(request=request, auth_url=auth_url, token=token) except exceptions.KeystoneAuthException as exc: if utils.is_websso_default_redirect(): res = django_http.HttpResponseRedirect(settings.LOGIN_ERROR) else: msg = 'Login failed: %s' % six.text_type(exc) res = django_http.HttpResponseRedirect(settings.LOGIN_URL) res.set_cookie('logout_reason', msg, max_age=10) return res auth_user.set_session_from_user(request, request.user) auth.login(request, request.user) if request.session.test_cookie_worked(): request.session.delete_test_cookie() return django_http.HttpResponseRedirect(settings.LOGIN_REDIRECT_URL)
python
def websso(request): referer = request.META.get('HTTP_REFERER', settings.OPENSTACK_KEYSTONE_URL) auth_url = utils.clean_up_auth_url(referer) token = request.POST.get('token') try: request.user = auth.authenticate(request=request, auth_url=auth_url, token=token) except exceptions.KeystoneAuthException as exc: if utils.is_websso_default_redirect(): res = django_http.HttpResponseRedirect(settings.LOGIN_ERROR) else: msg = 'Login failed: %s' % six.text_type(exc) res = django_http.HttpResponseRedirect(settings.LOGIN_URL) res.set_cookie('logout_reason', msg, max_age=10) return res auth_user.set_session_from_user(request, request.user) auth.login(request, request.user) if request.session.test_cookie_worked(): request.session.delete_test_cookie() return django_http.HttpResponseRedirect(settings.LOGIN_REDIRECT_URL)
[ "def", "websso", "(", "request", ")", ":", "referer", "=", "request", ".", "META", ".", "get", "(", "'HTTP_REFERER'", ",", "settings", ".", "OPENSTACK_KEYSTONE_URL", ")", "auth_url", "=", "utils", ".", "clean_up_auth_url", "(", "referer", ")", "token", "=", ...
Logs a user in using a token from Keystone's POST.
[ "Logs", "a", "user", "in", "using", "a", "token", "from", "Keystone", "s", "POST", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_auth/views.py#L159-L180
234,838
openstack/horizon
openstack_auth/views.py
logout
def logout(request, login_url=None, **kwargs): """Logs out the user if he is logged in. Then redirects to the log-in page. :param login_url: Once logged out, defines the URL where to redirect after login :param kwargs: see django.contrib.auth.views.logout_then_login extra parameters. """ msg = 'Logging out user "%(username)s".' % \ {'username': request.user.username} LOG.info(msg) """ Securely logs a user out. """ if (utils.is_websso_enabled and utils.is_websso_default_redirect() and utils.get_websso_default_redirect_logout()): auth_user.unset_session_user_variables(request) return django_http.HttpResponseRedirect( utils.get_websso_default_redirect_logout()) else: return django_auth_views.logout_then_login(request, login_url=login_url, **kwargs)
python
def logout(request, login_url=None, **kwargs): msg = 'Logging out user "%(username)s".' % \ {'username': request.user.username} LOG.info(msg) """ Securely logs a user out. """ if (utils.is_websso_enabled and utils.is_websso_default_redirect() and utils.get_websso_default_redirect_logout()): auth_user.unset_session_user_variables(request) return django_http.HttpResponseRedirect( utils.get_websso_default_redirect_logout()) else: return django_auth_views.logout_then_login(request, login_url=login_url, **kwargs)
[ "def", "logout", "(", "request", ",", "login_url", "=", "None", ",", "*", "*", "kwargs", ")", ":", "msg", "=", "'Logging out user \"%(username)s\".'", "%", "{", "'username'", ":", "request", ".", "user", ".", "username", "}", "LOG", ".", "info", "(", "ms...
Logs out the user if he is logged in. Then redirects to the log-in page. :param login_url: Once logged out, defines the URL where to redirect after login :param kwargs: see django.contrib.auth.views.logout_then_login extra parameters.
[ "Logs", "out", "the", "user", "if", "he", "is", "logged", "in", ".", "Then", "redirects", "to", "the", "log", "-", "in", "page", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_auth/views.py#L183-L206
234,839
openstack/horizon
openstack_auth/views.py
switch
def switch(request, tenant_id, redirect_field_name=auth.REDIRECT_FIELD_NAME): """Switches an authenticated user from one project to another.""" LOG.debug('Switching to tenant %s for user "%s".', tenant_id, request.user.username) endpoint, __ = utils.fix_auth_url_version_prefix(request.user.endpoint) session = utils.get_session() # Keystone can be configured to prevent exchanging a scoped token for # another token. Always use the unscoped token for requesting a # scoped token. unscoped_token = request.user.unscoped_token auth = utils.get_token_auth_plugin(auth_url=endpoint, token=unscoped_token, project_id=tenant_id) try: auth_ref = auth.get_access(session) msg = 'Project switch successful for user "%(username)s".' % \ {'username': request.user.username} LOG.info(msg) except keystone_exceptions.ClientException: msg = ( _('Project switch failed for user "%(username)s".') % {'username': request.user.username}) messages.error(request, msg) auth_ref = None LOG.exception('An error occurred while switching sessions.') # Ensure the user-originating redirection url is safe. # Taken from django.contrib.auth.views.login() redirect_to = request.GET.get(redirect_field_name, '') if not is_safe_url(url=redirect_to, host=request.get_host()): redirect_to = settings.LOGIN_REDIRECT_URL if auth_ref: user = auth_user.create_user_from_token( request, auth_user.Token(auth_ref, unscoped_token=unscoped_token), endpoint) auth_user.set_session_from_user(request, user) message = ( _('Switch to project "%(project_name)s" successful.') % {'project_name': request.user.project_name}) messages.success(request, message) response = shortcuts.redirect(redirect_to) utils.set_response_cookie(response, 'recent_project', request.user.project_id) return response
python
def switch(request, tenant_id, redirect_field_name=auth.REDIRECT_FIELD_NAME): LOG.debug('Switching to tenant %s for user "%s".', tenant_id, request.user.username) endpoint, __ = utils.fix_auth_url_version_prefix(request.user.endpoint) session = utils.get_session() # Keystone can be configured to prevent exchanging a scoped token for # another token. Always use the unscoped token for requesting a # scoped token. unscoped_token = request.user.unscoped_token auth = utils.get_token_auth_plugin(auth_url=endpoint, token=unscoped_token, project_id=tenant_id) try: auth_ref = auth.get_access(session) msg = 'Project switch successful for user "%(username)s".' % \ {'username': request.user.username} LOG.info(msg) except keystone_exceptions.ClientException: msg = ( _('Project switch failed for user "%(username)s".') % {'username': request.user.username}) messages.error(request, msg) auth_ref = None LOG.exception('An error occurred while switching sessions.') # Ensure the user-originating redirection url is safe. # Taken from django.contrib.auth.views.login() redirect_to = request.GET.get(redirect_field_name, '') if not is_safe_url(url=redirect_to, host=request.get_host()): redirect_to = settings.LOGIN_REDIRECT_URL if auth_ref: user = auth_user.create_user_from_token( request, auth_user.Token(auth_ref, unscoped_token=unscoped_token), endpoint) auth_user.set_session_from_user(request, user) message = ( _('Switch to project "%(project_name)s" successful.') % {'project_name': request.user.project_name}) messages.success(request, message) response = shortcuts.redirect(redirect_to) utils.set_response_cookie(response, 'recent_project', request.user.project_id) return response
[ "def", "switch", "(", "request", ",", "tenant_id", ",", "redirect_field_name", "=", "auth", ".", "REDIRECT_FIELD_NAME", ")", ":", "LOG", ".", "debug", "(", "'Switching to tenant %s for user \"%s\".'", ",", "tenant_id", ",", "request", ".", "user", ".", "username",...
Switches an authenticated user from one project to another.
[ "Switches", "an", "authenticated", "user", "from", "one", "project", "to", "another", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_auth/views.py#L210-L257
234,840
openstack/horizon
openstack_auth/views.py
switch_region
def switch_region(request, region_name, redirect_field_name=auth.REDIRECT_FIELD_NAME): """Switches the user's region for all services except Identity service. The region will be switched if the given region is one of the regions available for the scoped project. Otherwise the region is not switched. """ if region_name in request.user.available_services_regions: request.session['services_region'] = region_name LOG.debug('Switching services region to %s for user "%s".', region_name, request.user.username) redirect_to = request.GET.get(redirect_field_name, '') if not is_safe_url(url=redirect_to, host=request.get_host()): redirect_to = settings.LOGIN_REDIRECT_URL response = shortcuts.redirect(redirect_to) utils.set_response_cookie(response, 'services_region', request.session['services_region']) return response
python
def switch_region(request, region_name, redirect_field_name=auth.REDIRECT_FIELD_NAME): if region_name in request.user.available_services_regions: request.session['services_region'] = region_name LOG.debug('Switching services region to %s for user "%s".', region_name, request.user.username) redirect_to = request.GET.get(redirect_field_name, '') if not is_safe_url(url=redirect_to, host=request.get_host()): redirect_to = settings.LOGIN_REDIRECT_URL response = shortcuts.redirect(redirect_to) utils.set_response_cookie(response, 'services_region', request.session['services_region']) return response
[ "def", "switch_region", "(", "request", ",", "region_name", ",", "redirect_field_name", "=", "auth", ".", "REDIRECT_FIELD_NAME", ")", ":", "if", "region_name", "in", "request", ".", "user", ".", "available_services_regions", ":", "request", ".", "session", "[", ...
Switches the user's region for all services except Identity service. The region will be switched if the given region is one of the regions available for the scoped project. Otherwise the region is not switched.
[ "Switches", "the", "user", "s", "region", "for", "all", "services", "except", "Identity", "service", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_auth/views.py#L261-L280
234,841
openstack/horizon
openstack_auth/views.py
switch_keystone_provider
def switch_keystone_provider(request, keystone_provider=None, redirect_field_name=auth.REDIRECT_FIELD_NAME): """Switches the user's keystone provider using K2K Federation If keystone_provider is given then we switch the user to the keystone provider using K2K federation. Otherwise if keystone_provider is None then we switch the user back to the Identity Provider Keystone which a non federated token auth will be used. """ base_token = request.session.get('k2k_base_unscoped_token', None) k2k_auth_url = request.session.get('k2k_auth_url', None) keystone_providers = request.session.get('keystone_providers', None) recent_project = request.COOKIES.get('recent_project') if not base_token or not k2k_auth_url: msg = _('K2K Federation not setup for this session') raise exceptions.KeystoneAuthException(msg) redirect_to = request.GET.get(redirect_field_name, '') if not is_safe_url(url=redirect_to, host=request.get_host()): redirect_to = settings.LOGIN_REDIRECT_URL unscoped_auth_ref = None keystone_idp_id = getattr( settings, 'KEYSTONE_PROVIDER_IDP_ID', 'localkeystone') if keystone_provider == keystone_idp_id: current_plugin = plugin.TokenPlugin() unscoped_auth = current_plugin.get_plugin(auth_url=k2k_auth_url, token=base_token) else: # Switch to service provider using K2K federation plugins = [plugin.TokenPlugin()] current_plugin = plugin.K2KAuthPlugin() unscoped_auth = current_plugin.get_plugin( auth_url=k2k_auth_url, service_provider=keystone_provider, plugins=plugins, token=base_token, recent_project=recent_project) try: # Switch to identity provider using token auth unscoped_auth_ref = current_plugin.get_access_info(unscoped_auth) except exceptions.KeystoneAuthException as exc: msg = 'Switching to Keystone Provider %s has failed. %s' \ % (keystone_provider, (six.text_type(exc))) messages.error(request, msg) if unscoped_auth_ref: try: request.user = auth.authenticate( request=request, auth_url=unscoped_auth.auth_url, token=unscoped_auth_ref.auth_token) except exceptions.KeystoneAuthException as exc: msg = 'Keystone provider switch failed: %s' % six.text_type(exc) res = django_http.HttpResponseRedirect(settings.LOGIN_URL) res.set_cookie('logout_reason', msg, max_age=10) return res auth.login(request, request.user) auth_user.set_session_from_user(request, request.user) request.session['keystone_provider_id'] = keystone_provider request.session['keystone_providers'] = keystone_providers request.session['k2k_base_unscoped_token'] = base_token request.session['k2k_auth_url'] = k2k_auth_url message = ( _('Switch to Keystone Provider "%(keystone_provider)s" ' 'successful.') % {'keystone_provider': keystone_provider}) messages.success(request, message) response = shortcuts.redirect(redirect_to) return response
python
def switch_keystone_provider(request, keystone_provider=None, redirect_field_name=auth.REDIRECT_FIELD_NAME): base_token = request.session.get('k2k_base_unscoped_token', None) k2k_auth_url = request.session.get('k2k_auth_url', None) keystone_providers = request.session.get('keystone_providers', None) recent_project = request.COOKIES.get('recent_project') if not base_token or not k2k_auth_url: msg = _('K2K Federation not setup for this session') raise exceptions.KeystoneAuthException(msg) redirect_to = request.GET.get(redirect_field_name, '') if not is_safe_url(url=redirect_to, host=request.get_host()): redirect_to = settings.LOGIN_REDIRECT_URL unscoped_auth_ref = None keystone_idp_id = getattr( settings, 'KEYSTONE_PROVIDER_IDP_ID', 'localkeystone') if keystone_provider == keystone_idp_id: current_plugin = plugin.TokenPlugin() unscoped_auth = current_plugin.get_plugin(auth_url=k2k_auth_url, token=base_token) else: # Switch to service provider using K2K federation plugins = [plugin.TokenPlugin()] current_plugin = plugin.K2KAuthPlugin() unscoped_auth = current_plugin.get_plugin( auth_url=k2k_auth_url, service_provider=keystone_provider, plugins=plugins, token=base_token, recent_project=recent_project) try: # Switch to identity provider using token auth unscoped_auth_ref = current_plugin.get_access_info(unscoped_auth) except exceptions.KeystoneAuthException as exc: msg = 'Switching to Keystone Provider %s has failed. %s' \ % (keystone_provider, (six.text_type(exc))) messages.error(request, msg) if unscoped_auth_ref: try: request.user = auth.authenticate( request=request, auth_url=unscoped_auth.auth_url, token=unscoped_auth_ref.auth_token) except exceptions.KeystoneAuthException as exc: msg = 'Keystone provider switch failed: %s' % six.text_type(exc) res = django_http.HttpResponseRedirect(settings.LOGIN_URL) res.set_cookie('logout_reason', msg, max_age=10) return res auth.login(request, request.user) auth_user.set_session_from_user(request, request.user) request.session['keystone_provider_id'] = keystone_provider request.session['keystone_providers'] = keystone_providers request.session['k2k_base_unscoped_token'] = base_token request.session['k2k_auth_url'] = k2k_auth_url message = ( _('Switch to Keystone Provider "%(keystone_provider)s" ' 'successful.') % {'keystone_provider': keystone_provider}) messages.success(request, message) response = shortcuts.redirect(redirect_to) return response
[ "def", "switch_keystone_provider", "(", "request", ",", "keystone_provider", "=", "None", ",", "redirect_field_name", "=", "auth", ".", "REDIRECT_FIELD_NAME", ")", ":", "base_token", "=", "request", ".", "session", ".", "get", "(", "'k2k_base_unscoped_token'", ",", ...
Switches the user's keystone provider using K2K Federation If keystone_provider is given then we switch the user to the keystone provider using K2K federation. Otherwise if keystone_provider is None then we switch the user back to the Identity Provider Keystone which a non federated token auth will be used.
[ "Switches", "the", "user", "s", "keystone", "provider", "using", "K2K", "Federation" ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_auth/views.py#L284-L353
234,842
openstack/horizon
horizon/tables/actions.py
LinkAction.get_link_url
def get_link_url(self, datum=None): """Returns the final URL based on the value of ``url``. If ``url`` is callable it will call the function. If not, it will then try to call ``reverse`` on ``url``. Failing that, it will simply return the value of ``url`` as-is. When called for a row action, the current row data object will be passed as the first parameter. """ if not self.url: raise NotImplementedError('A LinkAction class must have a ' 'url attribute or define its own ' 'get_link_url method.') if callable(self.url): return self.url(datum, **self.kwargs) try: if datum: obj_id = self.table.get_object_id(datum) return urls.reverse(self.url, args=(obj_id,)) else: return urls.reverse(self.url) except urls.NoReverseMatch as ex: LOG.info('No reverse found for "%(url)s": %(exception)s', {'url': self.url, 'exception': ex}) return self.url
python
def get_link_url(self, datum=None): if not self.url: raise NotImplementedError('A LinkAction class must have a ' 'url attribute or define its own ' 'get_link_url method.') if callable(self.url): return self.url(datum, **self.kwargs) try: if datum: obj_id = self.table.get_object_id(datum) return urls.reverse(self.url, args=(obj_id,)) else: return urls.reverse(self.url) except urls.NoReverseMatch as ex: LOG.info('No reverse found for "%(url)s": %(exception)s', {'url': self.url, 'exception': ex}) return self.url
[ "def", "get_link_url", "(", "self", ",", "datum", "=", "None", ")", ":", "if", "not", "self", ".", "url", ":", "raise", "NotImplementedError", "(", "'A LinkAction class must have a '", "'url attribute or define its own '", "'get_link_url method.'", ")", "if", "callabl...
Returns the final URL based on the value of ``url``. If ``url`` is callable it will call the function. If not, it will then try to call ``reverse`` on ``url``. Failing that, it will simply return the value of ``url`` as-is. When called for a row action, the current row data object will be passed as the first parameter.
[ "Returns", "the", "final", "URL", "based", "on", "the", "value", "of", "url", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/tables/actions.py#L388-L413
234,843
openstack/horizon
horizon/tables/actions.py
FilterAction.get_param_name
def get_param_name(self): """Returns the full query parameter name for this action. Defaults to ``{{ table.name }}__{{ action.name }}__{{ action.param_name }}``. """ return "__".join([self.table.name, self.name, self.param_name])
python
def get_param_name(self): return "__".join([self.table.name, self.name, self.param_name])
[ "def", "get_param_name", "(", "self", ")", ":", "return", "\"__\"", ".", "join", "(", "[", "self", ".", "table", ".", "name", ",", "self", ".", "name", ",", "self", ".", "param_name", "]", ")" ]
Returns the full query parameter name for this action. Defaults to ``{{ table.name }}__{{ action.name }}__{{ action.param_name }}``.
[ "Returns", "the", "full", "query", "parameter", "name", "for", "this", "action", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/tables/actions.py#L492-L498
234,844
openstack/horizon
horizon/tables/actions.py
FilterAction.is_api_filter
def is_api_filter(self, filter_field): """Determine if agiven filter field should be used as an API filter.""" if self.filter_type == 'server': for choice in self.filter_choices: if (choice[0] == filter_field and len(choice) > 2 and choice[2]): return True return False
python
def is_api_filter(self, filter_field): if self.filter_type == 'server': for choice in self.filter_choices: if (choice[0] == filter_field and len(choice) > 2 and choice[2]): return True return False
[ "def", "is_api_filter", "(", "self", ",", "filter_field", ")", ":", "if", "self", ".", "filter_type", "==", "'server'", ":", "for", "choice", "in", "self", ".", "filter_choices", ":", "if", "(", "choice", "[", "0", "]", "==", "filter_field", "and", "len"...
Determine if agiven filter field should be used as an API filter.
[ "Determine", "if", "agiven", "filter", "field", "should", "be", "used", "as", "an", "API", "filter", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/tables/actions.py#L534-L541
234,845
openstack/horizon
horizon/tables/actions.py
FilterAction.get_select_options
def get_select_options(self): """Provide the value, string, and help_text for the template to render. help_text is returned if applicable. """ if self.filter_choices: return [choice[:4] for choice in self.filter_choices # Display it If the fifth element is True or does not exist if len(choice) < 5 or choice[4]]
python
def get_select_options(self): if self.filter_choices: return [choice[:4] for choice in self.filter_choices # Display it If the fifth element is True or does not exist if len(choice) < 5 or choice[4]]
[ "def", "get_select_options", "(", "self", ")", ":", "if", "self", ".", "filter_choices", ":", "return", "[", "choice", "[", ":", "4", "]", "for", "choice", "in", "self", ".", "filter_choices", "# Display it If the fifth element is True or does not exist", "if", "l...
Provide the value, string, and help_text for the template to render. help_text is returned if applicable.
[ "Provide", "the", "value", "string", "and", "help_text", "for", "the", "template", "to", "render", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/tables/actions.py#L543-L551
234,846
openstack/horizon
horizon/tables/actions.py
BatchAction._get_action_name
def _get_action_name(self, items=None, past=False): """Retreive action name based on the number of items and `past` flag. :param items: A list or tuple of items (or container with a __len__ method) to count the number of concerned items for which this method is called. When this method is called for a single item (by the BatchAction itself), this parameter can be omitted and the number of items will be considered as "one". If we want to evaluate to "zero" this parameter must not be omitted (and should be an empty container). :param past: Boolean flag indicating if the action took place in the past. By default a present action is considered. """ action_type = "past" if past else "present" if items is None: # Called without items parameter (by a single instance.) count = 1 else: count = len(items) action_attr = getattr(self, "action_%s" % action_type)(count) if isinstance(action_attr, (six.string_types, Promise)): action = action_attr else: toggle_selection = getattr(self, "current_%s_action" % action_type) action = action_attr[toggle_selection] return action
python
def _get_action_name(self, items=None, past=False): action_type = "past" if past else "present" if items is None: # Called without items parameter (by a single instance.) count = 1 else: count = len(items) action_attr = getattr(self, "action_%s" % action_type)(count) if isinstance(action_attr, (six.string_types, Promise)): action = action_attr else: toggle_selection = getattr(self, "current_%s_action" % action_type) action = action_attr[toggle_selection] return action
[ "def", "_get_action_name", "(", "self", ",", "items", "=", "None", ",", "past", "=", "False", ")", ":", "action_type", "=", "\"past\"", "if", "past", "else", "\"present\"", "if", "items", "is", "None", ":", "# Called without items parameter (by a single instance.)...
Retreive action name based on the number of items and `past` flag. :param items: A list or tuple of items (or container with a __len__ method) to count the number of concerned items for which this method is called. When this method is called for a single item (by the BatchAction itself), this parameter can be omitted and the number of items will be considered as "one". If we want to evaluate to "zero" this parameter must not be omitted (and should be an empty container). :param past: Boolean flag indicating if the action took place in the past. By default a present action is considered.
[ "Retreive", "action", "name", "based", "on", "the", "number", "of", "items", "and", "past", "flag", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/tables/actions.py#L697-L730
234,847
openstack/horizon
horizon/tables/actions.py
BatchAction.update
def update(self, request, datum): """Switches the action verbose name, if needed.""" if getattr(self, 'action_present', False): self.verbose_name = self._get_action_name() self.verbose_name_plural = self._get_action_name('plural')
python
def update(self, request, datum): if getattr(self, 'action_present', False): self.verbose_name = self._get_action_name() self.verbose_name_plural = self._get_action_name('plural')
[ "def", "update", "(", "self", ",", "request", ",", "datum", ")", ":", "if", "getattr", "(", "self", ",", "'action_present'", ",", "False", ")", ":", "self", ".", "verbose_name", "=", "self", ".", "_get_action_name", "(", ")", "self", ".", "verbose_name_p...
Switches the action verbose name, if needed.
[ "Switches", "the", "action", "verbose", "name", "if", "needed", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/tables/actions.py#L740-L744
234,848
openstack/horizon
horizon/tables/actions.py
BatchAction.get_default_attrs
def get_default_attrs(self): """Returns a list of the default HTML attributes for the action.""" attrs = super(BatchAction, self).get_default_attrs() attrs.update({'data-batch-action': 'true'}) return attrs
python
def get_default_attrs(self): attrs = super(BatchAction, self).get_default_attrs() attrs.update({'data-batch-action': 'true'}) return attrs
[ "def", "get_default_attrs", "(", "self", ")", ":", "attrs", "=", "super", "(", "BatchAction", ",", "self", ")", ".", "get_default_attrs", "(", ")", "attrs", ".", "update", "(", "{", "'data-batch-action'", ":", "'true'", "}", ")", "return", "attrs" ]
Returns a list of the default HTML attributes for the action.
[ "Returns", "a", "list", "of", "the", "default", "HTML", "attributes", "for", "the", "action", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/tables/actions.py#L752-L756
234,849
openstack/horizon
horizon/tabs/views.py
TabView.get_tabs
def get_tabs(self, request, **kwargs): """Returns the initialized tab group for this view.""" if self._tab_group is None: self._tab_group = self.tab_group_class(request, **kwargs) return self._tab_group
python
def get_tabs(self, request, **kwargs): if self._tab_group is None: self._tab_group = self.tab_group_class(request, **kwargs) return self._tab_group
[ "def", "get_tabs", "(", "self", ",", "request", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "_tab_group", "is", "None", ":", "self", ".", "_tab_group", "=", "self", ".", "tab_group_class", "(", "request", ",", "*", "*", "kwargs", ")", "retu...
Returns the initialized tab group for this view.
[ "Returns", "the", "initialized", "tab", "group", "for", "this", "view", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/tabs/views.py#L40-L44
234,850
openstack/horizon
horizon/tabs/views.py
TabView.get_context_data
def get_context_data(self, **kwargs): """Adds the ``tab_group`` variable to the context data.""" context = super(TabView, self).get_context_data(**kwargs) try: tab_group = self.get_tabs(self.request, **kwargs) context["tab_group"] = tab_group # Make sure our data is pre-loaded to capture errors. context["tab_group"].load_tab_data() except Exception: exceptions.handle(self.request) return context
python
def get_context_data(self, **kwargs): context = super(TabView, self).get_context_data(**kwargs) try: tab_group = self.get_tabs(self.request, **kwargs) context["tab_group"] = tab_group # Make sure our data is pre-loaded to capture errors. context["tab_group"].load_tab_data() except Exception: exceptions.handle(self.request) return context
[ "def", "get_context_data", "(", "self", ",", "*", "*", "kwargs", ")", ":", "context", "=", "super", "(", "TabView", ",", "self", ")", ".", "get_context_data", "(", "*", "*", "kwargs", ")", "try", ":", "tab_group", "=", "self", ".", "get_tabs", "(", "...
Adds the ``tab_group`` variable to the context data.
[ "Adds", "the", "tab_group", "variable", "to", "the", "context", "data", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/tabs/views.py#L46-L56
234,851
openstack/horizon
horizon/tabs/views.py
TabView.handle_tabbed_response
def handle_tabbed_response(self, tab_group, context): """Sends back an AJAX-appropriate response for the tab group if needed. Otherwise renders the response as normal. """ if self.request.is_ajax(): if tab_group.selected: return http.HttpResponse(tab_group.selected.render()) else: return http.HttpResponse(tab_group.render()) return self.render_to_response(context)
python
def handle_tabbed_response(self, tab_group, context): if self.request.is_ajax(): if tab_group.selected: return http.HttpResponse(tab_group.selected.render()) else: return http.HttpResponse(tab_group.render()) return self.render_to_response(context)
[ "def", "handle_tabbed_response", "(", "self", ",", "tab_group", ",", "context", ")", ":", "if", "self", ".", "request", ".", "is_ajax", "(", ")", ":", "if", "tab_group", ".", "selected", ":", "return", "http", ".", "HttpResponse", "(", "tab_group", ".", ...
Sends back an AJAX-appropriate response for the tab group if needed. Otherwise renders the response as normal.
[ "Sends", "back", "an", "AJAX", "-", "appropriate", "response", "for", "the", "tab", "group", "if", "needed", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/tabs/views.py#L58-L68
234,852
openstack/horizon
horizon/tabs/views.py
TabbedTableView.load_tabs
def load_tabs(self): """Loads the tab group. It compiles the table instances for each table attached to any :class:`horizon.tabs.TableTab` instances on the tab group. This step is necessary before processing any tab or table actions. """ tab_group = self.get_tabs(self.request, **self.kwargs) tabs = tab_group.get_tabs() for tab in [t for t in tabs if issubclass(t.__class__, TableTab)]: self.table_classes.extend(tab.table_classes) for table in tab._tables.values(): self._table_dict[table._meta.name] = {'table': table, 'tab': tab}
python
def load_tabs(self): tab_group = self.get_tabs(self.request, **self.kwargs) tabs = tab_group.get_tabs() for tab in [t for t in tabs if issubclass(t.__class__, TableTab)]: self.table_classes.extend(tab.table_classes) for table in tab._tables.values(): self._table_dict[table._meta.name] = {'table': table, 'tab': tab}
[ "def", "load_tabs", "(", "self", ")", ":", "tab_group", "=", "self", ".", "get_tabs", "(", "self", ".", "request", ",", "*", "*", "self", ".", "kwargs", ")", "tabs", "=", "tab_group", ".", "get_tabs", "(", ")", "for", "tab", "in", "[", "t", "for", ...
Loads the tab group. It compiles the table instances for each table attached to any :class:`horizon.tabs.TableTab` instances on the tab group. This step is necessary before processing any tab or table actions.
[ "Loads", "the", "tab", "group", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/tabs/views.py#L81-L94
234,853
openstack/horizon
horizon/tabs/views.py
TabbedTableView.handle_table
def handle_table(self, table_dict): """Loads the table data based on a given table_dict and handles them. For the given dict containing a ``DataTable`` and a ``TableTab`` instance, it loads the table data for that tab and calls the table's :meth:`~horizon.tables.DataTable.maybe_handle` method. The return value will be the result of ``maybe_handle``. """ table = table_dict['table'] tab = table_dict['tab'] tab.load_table_data() table_name = table._meta.name tab._tables[table_name]._meta.has_prev_data = self.has_prev_data(table) tab._tables[table_name]._meta.has_more_data = self.has_more_data(table) handled = tab._tables[table_name].maybe_handle() return handled
python
def handle_table(self, table_dict): table = table_dict['table'] tab = table_dict['tab'] tab.load_table_data() table_name = table._meta.name tab._tables[table_name]._meta.has_prev_data = self.has_prev_data(table) tab._tables[table_name]._meta.has_more_data = self.has_more_data(table) handled = tab._tables[table_name].maybe_handle() return handled
[ "def", "handle_table", "(", "self", ",", "table_dict", ")", ":", "table", "=", "table_dict", "[", "'table'", "]", "tab", "=", "table_dict", "[", "'tab'", "]", "tab", ".", "load_table_data", "(", ")", "table_name", "=", "table", ".", "_meta", ".", "name",...
Loads the table data based on a given table_dict and handles them. For the given dict containing a ``DataTable`` and a ``TableTab`` instance, it loads the table data for that tab and calls the table's :meth:`~horizon.tables.DataTable.maybe_handle` method. The return value will be the result of ``maybe_handle``.
[ "Loads", "the", "table", "data", "based", "on", "a", "given", "table_dict", "and", "handles", "them", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/tabs/views.py#L102-L117
234,854
openstack/horizon
openstack_dashboard/context_processors.py
openstack
def openstack(request): """Context processor necessary for OpenStack Dashboard functionality. The following variables are added to the request context: ``authorized_tenants`` A list of tenant objects which the current user has access to. ``regions`` A dictionary containing information about region support, the current region, and available regions. """ context = {} # Auth/Keystone context context.setdefault('authorized_tenants', []) if request.user.is_authenticated: context['authorized_tenants'] = [ tenant for tenant in request.user.authorized_tenants if tenant.enabled] # Region context/support available_regions = getattr(settings, 'AVAILABLE_REGIONS', []) regions = {'support': len(available_regions) > 1, 'current': {'endpoint': request.session.get('region_endpoint'), 'name': request.session.get('region_name')}, 'available': [{'endpoint': region[0], 'name':region[1]} for region in available_regions]} # K2K Federation Service Providers context/support available_providers = request.session.get('keystone_providers', []) if available_providers: provider_id = request.session.get('keystone_provider_id', None) provider_name = None for provider in available_providers: if provider['id'] == provider_id: provider_name = provider.get('name') keystone_providers = { 'support': len(available_providers) > 1, 'current': { 'name': provider_name, 'id': provider_id }, 'available': [ {'name': keystone_provider['name'], 'id': keystone_provider['id']} for keystone_provider in available_providers] } else: keystone_providers = {'support': False} context['keystone_providers'] = keystone_providers context['regions'] = regions # Adding webroot access context['WEBROOT'] = getattr(settings, "WEBROOT", "/") user_menu_links = getattr(settings, "USER_MENU_LINKS", []) if not getattr(settings, "SHOW_KEYSTONE_V2_RC", False): user_menu_links = [ link for link in user_menu_links if link['url'] != 'horizon:project:api_access:openrcv2'] context['USER_MENU_LINKS'] = user_menu_links # Adding profiler support flag profiler_settings = getattr(settings, 'OPENSTACK_PROFILER', {}) profiler_enabled = profiler_settings.get('enabled', False) context['profiler_enabled'] = profiler_enabled if profiler_enabled and 'profile_page' in request.COOKIES: index_view_id = request.META.get(profiler.ROOT_HEADER, '') hmac_keys = profiler_settings.get('keys', []) context['x_trace_info'] = profiler.update_trace_headers( hmac_keys, parent_id=index_view_id) context['JS_CATALOG'] = get_js_catalog(conf) return context
python
def openstack(request): context = {} # Auth/Keystone context context.setdefault('authorized_tenants', []) if request.user.is_authenticated: context['authorized_tenants'] = [ tenant for tenant in request.user.authorized_tenants if tenant.enabled] # Region context/support available_regions = getattr(settings, 'AVAILABLE_REGIONS', []) regions = {'support': len(available_regions) > 1, 'current': {'endpoint': request.session.get('region_endpoint'), 'name': request.session.get('region_name')}, 'available': [{'endpoint': region[0], 'name':region[1]} for region in available_regions]} # K2K Federation Service Providers context/support available_providers = request.session.get('keystone_providers', []) if available_providers: provider_id = request.session.get('keystone_provider_id', None) provider_name = None for provider in available_providers: if provider['id'] == provider_id: provider_name = provider.get('name') keystone_providers = { 'support': len(available_providers) > 1, 'current': { 'name': provider_name, 'id': provider_id }, 'available': [ {'name': keystone_provider['name'], 'id': keystone_provider['id']} for keystone_provider in available_providers] } else: keystone_providers = {'support': False} context['keystone_providers'] = keystone_providers context['regions'] = regions # Adding webroot access context['WEBROOT'] = getattr(settings, "WEBROOT", "/") user_menu_links = getattr(settings, "USER_MENU_LINKS", []) if not getattr(settings, "SHOW_KEYSTONE_V2_RC", False): user_menu_links = [ link for link in user_menu_links if link['url'] != 'horizon:project:api_access:openrcv2'] context['USER_MENU_LINKS'] = user_menu_links # Adding profiler support flag profiler_settings = getattr(settings, 'OPENSTACK_PROFILER', {}) profiler_enabled = profiler_settings.get('enabled', False) context['profiler_enabled'] = profiler_enabled if profiler_enabled and 'profile_page' in request.COOKIES: index_view_id = request.META.get(profiler.ROOT_HEADER, '') hmac_keys = profiler_settings.get('keys', []) context['x_trace_info'] = profiler.update_trace_headers( hmac_keys, parent_id=index_view_id) context['JS_CATALOG'] = get_js_catalog(conf) return context
[ "def", "openstack", "(", "request", ")", ":", "context", "=", "{", "}", "# Auth/Keystone context", "context", ".", "setdefault", "(", "'authorized_tenants'", ",", "[", "]", ")", "if", "request", ".", "user", ".", "is_authenticated", ":", "context", "[", "'au...
Context processor necessary for OpenStack Dashboard functionality. The following variables are added to the request context: ``authorized_tenants`` A list of tenant objects which the current user has access to. ``regions`` A dictionary containing information about region support, the current region, and available regions.
[ "Context", "processor", "necessary", "for", "OpenStack", "Dashboard", "functionality", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/context_processors.py#L30-L110
234,855
openstack/horizon
openstack_auth/utils.py
is_token_valid
def is_token_valid(token, margin=None): """Timezone-aware checking of the auth token's expiration timestamp. Returns ``True`` if the token has not yet expired, otherwise ``False``. :param token: The openstack_auth.user.Token instance to check :param margin: A time margin in seconds to subtract from the real token's validity. An example usage is that the token can be valid once the middleware passed, and invalid (timed-out) during a view rendering and this generates authorization errors during the view rendering. A default margin can be set by the TOKEN_TIMEOUT_MARGIN in the django settings. """ expiration = token.expires # In case we get an unparseable expiration timestamp, return False # so you can't have a "forever" token just by breaking the expires param. if expiration is None: return False if margin is None: margin = getattr(settings, 'TOKEN_TIMEOUT_MARGIN', 0) expiration = expiration - datetime.timedelta(seconds=margin) if settings.USE_TZ and timezone.is_naive(expiration): # Presumes that the Keystone is using UTC. expiration = timezone.make_aware(expiration, timezone.utc) return expiration > timezone.now()
python
def is_token_valid(token, margin=None): expiration = token.expires # In case we get an unparseable expiration timestamp, return False # so you can't have a "forever" token just by breaking the expires param. if expiration is None: return False if margin is None: margin = getattr(settings, 'TOKEN_TIMEOUT_MARGIN', 0) expiration = expiration - datetime.timedelta(seconds=margin) if settings.USE_TZ and timezone.is_naive(expiration): # Presumes that the Keystone is using UTC. expiration = timezone.make_aware(expiration, timezone.utc) return expiration > timezone.now()
[ "def", "is_token_valid", "(", "token", ",", "margin", "=", "None", ")", ":", "expiration", "=", "token", ".", "expires", "# In case we get an unparseable expiration timestamp, return False", "# so you can't have a \"forever\" token just by breaking the expires param.", "if", "exp...
Timezone-aware checking of the auth token's expiration timestamp. Returns ``True`` if the token has not yet expired, otherwise ``False``. :param token: The openstack_auth.user.Token instance to check :param margin: A time margin in seconds to subtract from the real token's validity. An example usage is that the token can be valid once the middleware passed, and invalid (timed-out) during a view rendering and this generates authorization errors during the view rendering. A default margin can be set by the TOKEN_TIMEOUT_MARGIN in the django settings.
[ "Timezone", "-", "aware", "checking", "of", "the", "auth", "token", "s", "expiration", "timestamp", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_auth/utils.py#L75-L101
234,856
openstack/horizon
openstack_auth/utils.py
is_safe_url
def is_safe_url(url, host=None): """Return ``True`` if the url is a safe redirection. The safe redirection means that it doesn't point to a different host. Always returns ``False`` on an empty url. """ if not url: return False netloc = urlparse.urlparse(url)[1] return not netloc or netloc == host
python
def is_safe_url(url, host=None): if not url: return False netloc = urlparse.urlparse(url)[1] return not netloc or netloc == host
[ "def", "is_safe_url", "(", "url", ",", "host", "=", "None", ")", ":", "if", "not", "url", ":", "return", "False", "netloc", "=", "urlparse", ".", "urlparse", "(", "url", ")", "[", "1", "]", "return", "not", "netloc", "or", "netloc", "==", "host" ]
Return ``True`` if the url is a safe redirection. The safe redirection means that it doesn't point to a different host. Always returns ``False`` on an empty url.
[ "Return", "True", "if", "the", "url", "is", "a", "safe", "redirection", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_auth/utils.py#L107-L116
234,857
openstack/horizon
openstack_auth/utils.py
build_absolute_uri
def build_absolute_uri(request, relative_url): """Ensure absolute_uri are relative to WEBROOT.""" webroot = getattr(settings, 'WEBROOT', '') if webroot.endswith("/") and relative_url.startswith("/"): webroot = webroot[:-1] return request.build_absolute_uri(webroot + relative_url)
python
def build_absolute_uri(request, relative_url): webroot = getattr(settings, 'WEBROOT', '') if webroot.endswith("/") and relative_url.startswith("/"): webroot = webroot[:-1] return request.build_absolute_uri(webroot + relative_url)
[ "def", "build_absolute_uri", "(", "request", ",", "relative_url", ")", ":", "webroot", "=", "getattr", "(", "settings", ",", "'WEBROOT'", ",", "''", ")", "if", "webroot", ".", "endswith", "(", "\"/\"", ")", "and", "relative_url", ".", "startswith", "(", "\...
Ensure absolute_uri are relative to WEBROOT.
[ "Ensure", "absolute_uri", "are", "relative", "to", "WEBROOT", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_auth/utils.py#L173-L179
234,858
openstack/horizon
openstack_auth/utils.py
get_websso_url
def get_websso_url(request, auth_url, websso_auth): """Return the keystone endpoint for initiating WebSSO. Generate the keystone WebSSO endpoint that will redirect the user to the login page of the federated identity provider. Based on the authentication type selected by the user in the login form, it will construct the keystone WebSSO endpoint. :param request: Django http request object. :type request: django.http.HttpRequest :param auth_url: Keystone endpoint configured in the horizon setting. If WEBSSO_KEYSTONE_URL is defined, its value will be used. Otherwise, the value is derived from: - OPENSTACK_KEYSTONE_URL - AVAILABLE_REGIONS :type auth_url: string :param websso_auth: Authentication type selected by the user from the login form. The value is derived from the horizon setting WEBSSO_CHOICES. :type websso_auth: string Example of horizon WebSSO setting:: WEBSSO_CHOICES = ( ("credentials", "Keystone Credentials"), ("oidc", "OpenID Connect"), ("saml2", "Security Assertion Markup Language"), ("acme_oidc", "ACME - OpenID Connect"), ("acme_saml2", "ACME - SAML2") ) WEBSSO_IDP_MAPPING = { "acme_oidc": ("acme", "oidc"), "acme_saml2": ("acme", "saml2") } } The value of websso_auth will be looked up in the WEBSSO_IDP_MAPPING dictionary, if a match is found it will return a IdP specific WebSSO endpoint using the values found in the mapping. The value in WEBSSO_IDP_MAPPING is expected to be a tuple formatted as (<idp_id>, <protocol_id>). Using the values found, a IdP/protocol specific URL will be constructed:: /auth/OS-FEDERATION/identity_providers/<idp_id> /protocols/<protocol_id>/websso If no value is found from the WEBSSO_IDP_MAPPING dictionary, it will treat the value as the global WebSSO protocol <protocol_id> and construct the WebSSO URL by:: /auth/OS-FEDERATION/websso/<protocol_id> :returns: Keystone WebSSO endpoint. :rtype: string """ origin = build_absolute_uri(request, '/auth/websso/') idp_mapping = getattr(settings, 'WEBSSO_IDP_MAPPING', {}) idp_id, protocol_id = idp_mapping.get(websso_auth, (None, websso_auth)) if idp_id: # Use the IDP specific WebSSO endpoint url = ('%s/auth/OS-FEDERATION/identity_providers/%s' '/protocols/%s/websso?origin=%s' % (auth_url, idp_id, protocol_id, origin)) else: # If no IDP mapping found for the identifier, # perform WebSSO by protocol. url = ('%s/auth/OS-FEDERATION/websso/%s?origin=%s' % (auth_url, protocol_id, origin)) return url
python
def get_websso_url(request, auth_url, websso_auth): origin = build_absolute_uri(request, '/auth/websso/') idp_mapping = getattr(settings, 'WEBSSO_IDP_MAPPING', {}) idp_id, protocol_id = idp_mapping.get(websso_auth, (None, websso_auth)) if idp_id: # Use the IDP specific WebSSO endpoint url = ('%s/auth/OS-FEDERATION/identity_providers/%s' '/protocols/%s/websso?origin=%s' % (auth_url, idp_id, protocol_id, origin)) else: # If no IDP mapping found for the identifier, # perform WebSSO by protocol. url = ('%s/auth/OS-FEDERATION/websso/%s?origin=%s' % (auth_url, protocol_id, origin)) return url
[ "def", "get_websso_url", "(", "request", ",", "auth_url", ",", "websso_auth", ")", ":", "origin", "=", "build_absolute_uri", "(", "request", ",", "'/auth/websso/'", ")", "idp_mapping", "=", "getattr", "(", "settings", ",", "'WEBSSO_IDP_MAPPING'", ",", "{", "}", ...
Return the keystone endpoint for initiating WebSSO. Generate the keystone WebSSO endpoint that will redirect the user to the login page of the federated identity provider. Based on the authentication type selected by the user in the login form, it will construct the keystone WebSSO endpoint. :param request: Django http request object. :type request: django.http.HttpRequest :param auth_url: Keystone endpoint configured in the horizon setting. If WEBSSO_KEYSTONE_URL is defined, its value will be used. Otherwise, the value is derived from: - OPENSTACK_KEYSTONE_URL - AVAILABLE_REGIONS :type auth_url: string :param websso_auth: Authentication type selected by the user from the login form. The value is derived from the horizon setting WEBSSO_CHOICES. :type websso_auth: string Example of horizon WebSSO setting:: WEBSSO_CHOICES = ( ("credentials", "Keystone Credentials"), ("oidc", "OpenID Connect"), ("saml2", "Security Assertion Markup Language"), ("acme_oidc", "ACME - OpenID Connect"), ("acme_saml2", "ACME - SAML2") ) WEBSSO_IDP_MAPPING = { "acme_oidc": ("acme", "oidc"), "acme_saml2": ("acme", "saml2") } } The value of websso_auth will be looked up in the WEBSSO_IDP_MAPPING dictionary, if a match is found it will return a IdP specific WebSSO endpoint using the values found in the mapping. The value in WEBSSO_IDP_MAPPING is expected to be a tuple formatted as (<idp_id>, <protocol_id>). Using the values found, a IdP/protocol specific URL will be constructed:: /auth/OS-FEDERATION/identity_providers/<idp_id> /protocols/<protocol_id>/websso If no value is found from the WEBSSO_IDP_MAPPING dictionary, it will treat the value as the global WebSSO protocol <protocol_id> and construct the WebSSO URL by:: /auth/OS-FEDERATION/websso/<protocol_id> :returns: Keystone WebSSO endpoint. :rtype: string
[ "Return", "the", "keystone", "endpoint", "for", "initiating", "WebSSO", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_auth/utils.py#L182-L257
234,859
openstack/horizon
openstack_auth/utils.py
has_in_url_path
def has_in_url_path(url, subs): """Test if any of `subs` strings is present in the `url` path.""" scheme, netloc, path, query, fragment = urlparse.urlsplit(url) return any([sub in path for sub in subs])
python
def has_in_url_path(url, subs): scheme, netloc, path, query, fragment = urlparse.urlsplit(url) return any([sub in path for sub in subs])
[ "def", "has_in_url_path", "(", "url", ",", "subs", ")", ":", "scheme", ",", "netloc", ",", "path", ",", "query", ",", "fragment", "=", "urlparse", ".", "urlsplit", "(", "url", ")", "return", "any", "(", "[", "sub", "in", "path", "for", "sub", "in", ...
Test if any of `subs` strings is present in the `url` path.
[ "Test", "if", "any", "of", "subs", "strings", "is", "present", "in", "the", "url", "path", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_auth/utils.py#L260-L263
234,860
openstack/horizon
openstack_auth/utils.py
url_path_replace
def url_path_replace(url, old, new, count=None): """Return a copy of url with replaced path. Return a copy of url with all occurrences of old replaced by new in the url path. If the optional argument count is given, only the first count occurrences are replaced. """ args = [] scheme, netloc, path, query, fragment = urlparse.urlsplit(url) if count is not None: args.append(count) return urlparse.urlunsplit(( scheme, netloc, path.replace(old, new, *args), query, fragment))
python
def url_path_replace(url, old, new, count=None): args = [] scheme, netloc, path, query, fragment = urlparse.urlsplit(url) if count is not None: args.append(count) return urlparse.urlunsplit(( scheme, netloc, path.replace(old, new, *args), query, fragment))
[ "def", "url_path_replace", "(", "url", ",", "old", ",", "new", ",", "count", "=", "None", ")", ":", "args", "=", "[", "]", "scheme", ",", "netloc", ",", "path", ",", "query", ",", "fragment", "=", "urlparse", ".", "urlsplit", "(", "url", ")", "if",...
Return a copy of url with replaced path. Return a copy of url with all occurrences of old replaced by new in the url path. If the optional argument count is given, only the first count occurrences are replaced.
[ "Return", "a", "copy", "of", "url", "with", "replaced", "path", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_auth/utils.py#L266-L278
234,861
openstack/horizon
openstack_auth/utils.py
_augment_url_with_version
def _augment_url_with_version(auth_url): """Optionally augment auth_url path with version suffix. Check if path component already contains version suffix and if it does not, append version suffix to the end of path, not erasing the previous path contents, since keystone web endpoint (like /identity) could be there. Keystone version needs to be added to endpoint because as of Kilo, the identity URLs returned by Keystone might no longer contain API versions, leaving the version choice up to the user. """ if has_in_url_path(auth_url, ["/v2.0", "/v3"]): return auth_url if get_keystone_version() >= 3: return url_path_append(auth_url, "/v3") else: return url_path_append(auth_url, "/v2.0")
python
def _augment_url_with_version(auth_url): if has_in_url_path(auth_url, ["/v2.0", "/v3"]): return auth_url if get_keystone_version() >= 3: return url_path_append(auth_url, "/v3") else: return url_path_append(auth_url, "/v2.0")
[ "def", "_augment_url_with_version", "(", "auth_url", ")", ":", "if", "has_in_url_path", "(", "auth_url", ",", "[", "\"/v2.0\"", ",", "\"/v3\"", "]", ")", ":", "return", "auth_url", "if", "get_keystone_version", "(", ")", ">=", "3", ":", "return", "url_path_app...
Optionally augment auth_url path with version suffix. Check if path component already contains version suffix and if it does not, append version suffix to the end of path, not erasing the previous path contents, since keystone web endpoint (like /identity) could be there. Keystone version needs to be added to endpoint because as of Kilo, the identity URLs returned by Keystone might no longer contain API versions, leaving the version choice up to the user.
[ "Optionally", "augment", "auth_url", "path", "with", "version", "suffix", "." ]
5601ea9477323e599d9b766fcac1f8be742935b2
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_auth/utils.py#L287-L303
234,862
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): 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
234,863
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): # 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
234,864
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): 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
234,865
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): 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
234,866
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): _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
234,867
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): 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
234,868
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): 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
234,869
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): 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
234,870
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): 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
234,871
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): 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
234,872
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): 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
234,873
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): 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
234,874
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): 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
234,875
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): 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
234,876
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): # 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
234,877
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): # 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
234,878
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): 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
234,879
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): 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
234,880
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. 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
234,881
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): 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
234,882
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): 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
234,883
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): 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
234,884
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): 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
234,885
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): 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
234,886
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): 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
234,887
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): 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
234,888
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): 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
234,889
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): 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
234,890
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): 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
234,891
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): 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
234,892
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): 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
234,893
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): 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
234,894
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): 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
234,895
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): 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
234,896
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): 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
234,897
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): # 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
234,898
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): 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
234,899
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): 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