INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Check if the current user owns the object
def is_owned_by_current_user(self): """ Check if the current user owns the object """ from bambou.nurest_root_object import NURESTRootObject root_object = NURESTRootObject.get_default_root_object() return self._owner == root_object.id
Return parent that matches a rest name
def parent_for_matching_rest_name(self, rest_names): """ Return parent that matches a rest name """ parent = self while parent: if parent.rest_name in rest_names: return parent parent = parent.parent_object return None
Get genealogic types
def genealogic_types(self): """ Get genealogic types Returns: Returns a list of all parent types """ types = [] parent = self while parent: types.append(parent.rest_name) parent = parent.parent_object return types
Get all genealogic ids
def genealogic_ids(self): """ Get all genealogic ids Returns: A list of all parent ids """ ids = [] parent = self while parent: ids.append(parent.id) parent = parent.parent_object return ids
Return creation date with a given format. Default is %b %Y %d %H: %I: %S
def get_formated_creation_date(self, format='%b %Y %d %H:%I:%S'): """ Return creation date with a given format. Default is '%b %Y %d %H:%I:%S' """ if not self._creation_date: return None date = datetime.datetime.utcfromtimestamp(self._creation_date) return date.strftime(for...
Add a child
def add_child(self, child): """ Add a child """ rest_name = child.rest_name children = self.fetcher_for_rest_name(rest_name) if children is None: raise InternalConsitencyError('Could not find fetcher with name %s while adding %s in parent %s' % (rest_name, child, self)) ...
Remove a child
def remove_child(self, child): """ Remove a child """ rest_name = child.rest_name children = self.fetcher_for_rest_name(rest_name) target_child = None for local_child in children: if local_child.id == child.id: target_child = local_child ...
Update child
def update_child(self, child): """ Update child """ rest_name = child.rest_name children = self.fetcher_for_rest_name(rest_name) index = None for local_child in children: if local_child.id == child.id: index = children.index(local_child) ...
Converts the current object into a Dictionary using all exposed ReST attributes.
def to_dict(self): """ Converts the current object into a Dictionary using all exposed ReST attributes. Returns: dict: the dictionary containing all the exposed ReST attributes and their values. Example:: >>> print entity.to_dict() {"name...
Sets all the exposed ReST attribues from the given dictionary
def from_dict(self, dictionary): """ Sets all the exposed ReST attribues from the given dictionary Args: dictionary (dict): dictionnary containing the raw object attributes and their values. Example: >>> info = {"name": "my group", "private": False} ...
Delete object and call given callback in case of call.
def delete(self, response_choice=1, async=False, callback=None): """ Delete object and call given callback in case of call. Args: response_choice (int): Automatically send a response choice when confirmation is needed async (bool): Boolean to make an asynchronous cal...
Update object and call given callback in case of async call
def save(self, response_choice=None, async=False, callback=None): """ Update object and call given callback in case of async call Args: async (bool): Boolean to make an asynchronous call. Default is False callback (function): Callback method that will be triggered in...
Sends a request calls the local callback then the remote callback in case of async call
def send_request(self, request, async=False, local_callback=None, remote_callback=None, user_info=None): """ Sends a request, calls the local callback, then the remote callback in case of async call Args: request: The request to send local_callback: local method that...
Low level child management. Send given HTTP method with given nurest_object to given ressource of current object
def _manage_child_object(self, nurest_object, method=HTTP_METHOD_GET, async=False, callback=None, handler=None, response_choice=None, commit=False): """ Low level child management. Send given HTTP method with given nurest_object to given ressource of current object Args: nurest_obje...
Receive a response from the connection
def _did_receive_response(self, connection): """ Receive a response from the connection """ if connection.has_timeouted: bambou_logger.info("NURESTConnection has timeout.") return has_callbacks = connection.has_callbacks() should_post = not has_callbacks ...
Callback called after fetching the object
def _did_retrieve(self, connection): """ Callback called after fetching the object """ response = connection.response try: self.from_dict(response.data[0]) except: pass return self._did_perform_standard_operation(connection)
Performs standard opertions
def _did_perform_standard_operation(self, connection): """ Performs standard opertions """ if connection.async: callback = connection.callbacks['remote'] if connection.user_info and 'nurest_object' in connection.user_info: callback(connection.user_info['nurest_o...
Add given nurest_object to the current object
def create_child(self, nurest_object, response_choice=None, async=False, callback=None, commit=True): """ Add given nurest_object to the current object For example, to add a child into a parent, you can call parent.create_child(nurest_object=child) Args: nur...
Instantiate an nurest_object from a template object
def instantiate_child(self, nurest_object, from_template, response_choice=None, async=False, callback=None, commit=True): """ Instantiate an nurest_object from a template object Args: nurest_object: the NURESTObject object to add from_template: the NURESTObject templ...
Callback called after adding a new child nurest_object
def _did_create_child(self, connection): """ Callback called after adding a new child nurest_object """ response = connection.response try: connection.user_info['nurest_object'].from_dict(response.data[0]) except Exception: pass return self._did_perform_...
Reference a list of objects into the current resource
def assign(self, objects, nurest_object_type, async=False, callback=None, commit=True): """ Reference a list of objects into the current resource Args: objects (list): list of NURESTObject to link nurest_object_type (type): Type of the object to link ...
Compare objects REST attributes
def rest_equals(self, rest_object): """ Compare objects REST attributes """ if not self.equals(rest_object): return False return self.to_dict() == rest_object.to_dict()
Compare with another object
def equals(self, rest_object): """ Compare with another object """ if self._is_dirty: return False if rest_object is None: return False if not isinstance(rest_object, NURESTObject): raise TypeError('The object is not a NURESTObject %s' % rest_object...
Correct IP address is expected as first element of HTTP_X_FORWARDED_FOR or REMOTE_ADDR
def get_ip_address(request): """ Correct IP address is expected as first element of HTTP_X_FORWARDED_FOR or REMOTE_ADDR """ if 'HTTP_X_FORWARDED_FOR' in request.META: return request.META['HTTP_X_FORWARDED_FOR'].split(',')[0].strip() else: return request.META['REMOTE_ADDR']
It is expected that valid row for each month contains at least one price estimate for customer service setting service service project link project and resource. Otherwise all price estimates in the row should be deleted.
def get_estimates_without_scope_in_month(self, customer): """ It is expected that valid row for each month contains at least one price estimate for customer, service setting, service, service project link, project and resource. Otherwise all price estimates in the row should be d...
Setter for is_identifier
def is_identifier(self, is_identifier): """ Setter for is_identifier """ if is_identifier: self.is_editable = False self._is_identifier = is_identifier
Setter for is_identifier
def is_password(self, is_password): """ Setter for is_identifier """ if is_password: self.is_forgetable = True self._is_password = is_password
Setter for is_identifier
def choices(self, choices): """ Setter for is_identifier """ if choices is not None and len(choices) > 0: self.has_choices = True self._choices = choices
Get a default value of the attribute_type
def get_default_value(self): """ Get a default value of the attribute_type """ if self.choices: return self.choices[0] value = self.attribute_type() if self.attribute_type is time: value = int(value) elif self.attribute_type is str: value =...
Get the minimum value
def get_min_value(self): """ Get the minimum value """ value = self.get_default_value() if self.attribute_type is str: min_value = value[:self.min_length - 1] elif self.attribute_type is int: min_value = self.min_length - 1 else: raise Type...
Get the maximum value
def get_max_value(self): """ Get the maximum value """ value = self.get_default_value() if self.attribute_type is str: max_value = value.ljust(self.max_length + 1, 'a') elif self.attribute_type is int: max_value = self.max_length + 1 else: ...
Return a basic root view.
def get_api_root_view(self, api_urls=None): """ Return a basic root view. """ api_root_dict = OrderedDict() list_name = self.routes[0].name for prefix, viewset, basename in self.registry: api_root_dict[prefix] = list_name.format(basename=basename) cla...
Attempt to automatically determine base name using get_url_name.
def get_default_base_name(self, viewset): """ Attempt to automatically determine base name using `get_url_name`. """ queryset = getattr(viewset, 'queryset', None) if queryset is not None: get_url_name = getattr(queryset.model, 'get_url_name', None) if get...
Modify nc_user_count quota usage on structure role grant or revoke
def change_customer_nc_users_quota(sender, structure, user, role, signal, **kwargs): """ Modify nc_user_count quota usage on structure role grant or revoke """ assert signal in (signals.structure_role_granted, signals.structure_role_revoked), \ 'Handler "change_customer_nc_users_quota" has to be used on...
Delete not shared service settings without services
def delete_service_settings_on_service_delete(sender, instance, **kwargs): """ Delete not shared service settings without services """ service = instance try: service_settings = service.settings except ServiceSettings.DoesNotExist: # If this handler works together with delete_service_set...
If VM that contains service settings were deleted - all settings resources could be safely deleted from NC.
def delete_service_settings_on_scope_delete(sender, instance, **kwargs): """ If VM that contains service settings were deleted - all settings resources could be safely deleted from NC. """ for service_settings in ServiceSettings.objects.filter(scope=instance): service_settings.unlink_descend...
Set API URL endpoint
def url(self, url): """ Set API URL endpoint Args: url: the url of the API endpoint """ if url and url.endswith('/'): url = url[:-1] self._url = url
Return authenication string to place in Authorization Header
def get_authentication_header(self, user=None, api_key=None, password=None, certificate=None): """ Return authenication string to place in Authorization Header If API Token is set, it'll be used. Otherwise, the clear text password will be sent. Users of NURESTLoginController are respons...
Reset controller
def reset(self): """ Reset controller It removes all information about previous session """ self._is_impersonating = False self._impersonation = None self.user = None self.password = None self.api_key = None self.enterprise = None se...
Impersonate a user in a enterprise
def impersonate(self, user, enterprise): """ Impersonate a user in a enterprise Args: user: the name of the user to impersonate enterprise: the name of the enterprise where to use impersonation """ if not user or not enterprise: raise Val...
Verify if the controller corresponds to the current one.
def equals(self, controller): """ Verify if the controller corresponds to the current one. """ if controller is None: return False return self.user == controller.user and self.enterprise == controller.enterprise and self.url == controller.url
WSGI adapter. It creates a simple WSGI application that can be used with any WSGI server. The arguments are:
def create_application(server, root_url): """ WSGI adapter. It creates a simple WSGI application, that can be used with any WSGI server. The arguments are: #. ``server`` is a pyws server object, #. ``root_url`` is an URL to which the server will be bound. An application created by the function...
构建dialect
def compiler_dialect(paramstyle='named'): """ 构建dialect """ dialect = SQLiteDialect_pysqlite( json_serializer=json.dumps, json_deserializer=json_deserializer, paramstyle=paramstyle ) dialect.default_paramstyle = paramstyle dialect.statement_compiler = ACompiler_sqlite...
A coroutine for Engine creation.
def create_engine( database, minsize=1, maxsize=10, loop=None, dialect=_dialect, paramstyle=None, **kwargs): """ A coroutine for Engine creation. Returns Engine instance with embedded connection pool. The pool has *minsize* opened connections to ...
Revert back connection to pool.
def release(self, conn): """Revert back connection to pool.""" if conn.in_transaction: raise InvalidRequestError( "Cannot release a connection with " "not finished transaction" ) raw = conn.connection res = yield from self._pool.rel...
Return how much consumables are used by resource with current configuration.
def get_configuration(cls, resource): """ Return how much consumables are used by resource with current configuration. Output example: { <ConsumableItem instance>: <usage>, <ConsumableItem instance>: <usage>, ... } """ ...
Close this ResultProxy. Closes the underlying DBAPI cursor corresponding to the execution. Note that any data cached within this ResultProxy is still available. For some types of results this may include buffered rows. If this ResultProxy was generated from an implicit execution the underlying Connection will also be c...
def close(self): """Close this ResultProxy. Closes the underlying DBAPI cursor corresponding to the execution. Note that any data cached within this ResultProxy is still available. For some types of results, this may include buffered rows. If this ResultProxy was generated from a...
Obtain the version number
def get_version(): """Obtain the version number""" import imp import os mod = imp.load_source( 'version', os.path.join('skdata', '__init__.py') ) return mod.__version__
Accept invitation for current user.
def accept(self, request, uuid=None): """ Accept invitation for current user. To replace user's email with email from invitation - add parameter 'replace_email' to request POST body. """ invitation = self.get_object() if invitation.state != models.Invitation.Sta...
Run different actions on price estimate scope deletion.
def scope_deletion(sender, instance, **kwargs): """ Run different actions on price estimate scope deletion. If scope is a customer - delete all customer estimates and their children. If scope is a deleted resource - redefine consumption details, recalculate ...
Recalculate consumption details and save resource details
def _resource_deletion(resource): """ Recalculate consumption details and save resource details """ if resource.__class__ not in CostTrackingRegister.registered_resources: return new_configuration = {} price_estimate = models.PriceEstimate.update_resource_estimate(resource, new_configuration) ...
Update resource consumption details and price estimate if its configuration has changed. Create estimates for previous months if resource was created not in current month.
def resource_update(sender, instance, created=False, **kwargs): """ Update resource consumption details and price estimate if its configuration has changed. Create estimates for previous months if resource was created not in current month. """ resource = instance try: new_configuration =...
Update resource consumption details and price estimate if its configuration has changed
def resource_quota_update(sender, instance, **kwargs): """ Update resource consumption details and price estimate if its configuration has changed """ quota = instance resource = quota.scope try: new_configuration = CostTrackingRegister.get_configuration(resource) except ResourceNotRegistere...
Create consumption details and price estimates for past months.
def _create_historical_estimates(resource, configuration): """ Create consumption details and price estimates for past months. Usually we need to update historical values on resource import. """ today = timezone.now() month_start = core_utils.month_start(today) while month_start > resource....
Decide if the Ipython command line is running code.
def IPYTHON_MAIN(): """Decide if the Ipython command line is running code.""" import pkg_resources runner_frame = inspect.getouterframes(inspect.currentframe())[-2] return ( getattr(runner_frame, "function", None) == pkg_resources.load_entry_point("ipython", "console_scripts", "ipython"...
Register a model class according to its remote name
def register_model(cls, model): """ Register a model class according to its remote name Args: model: the model to register """ rest_name = model.rest_name resource_name = model.resource_name if rest_name not in cls._model_rest_name_regis...
Get the first model corresponding to a rest_name
def get_first_model_with_rest_name(cls, rest_name): """ Get the first model corresponding to a rest_name Args: rest_name: the rest name """ models = cls.get_models_with_rest_name(rest_name) if len(models) > 0: return models[0] return No...
Get the first model corresponding to a resource_name
def get_first_model_with_resource_name(cls, resource_name): """ Get the first model corresponding to a resource_name Args: resource_name: the resource name """ models = cls.get_models_with_resource_name(resource_name) if len(models) > 0: return ...
执行任务
def run(self): """ 执行任务 """ while not self._stoped: self._tx_event.wait() self._tx_event.clear() try: func = self._tx_queue.get_nowait() if isinstance(func, str): self._stoped = True ...
: param dset_id:: return:
def build_layout(self, dset_id: str): """ :param dset_id: :return: """ all_fields = list(self.get_data(dset_id=dset_id).keys()) try: field_reference = self.skd[dset_id].attrs('target') except: field_reference = all_fields[0] field...
: param dset_id:: return:
def display(self, dset_id: str): """ :param dset_id: :return: """ # update result self.skd[dset_id].compute() # build layout self.build_layout(dset_id=dset_id) # display widgets display(self._('dashboard')) # display data table and...
Try to finder the spec and if it cannot be found use the underscore starring syntax to identify potential matches.
def find_spec(self, fullname, target=None): """Try to finder the spec and if it cannot be found, use the underscore starring syntax to identify potential matches. """ spec = super().find_spec(fullname, target=target) if spec is None: original = fullname ...
Get resource complete url
def get_resource_url(self): """ Get resource complete url """ name = self.__class__.resource_name url = self.__class__.rest_base_url() return "%s/%s" % (url, name)
Updates the user and perform the callback method
def save(self, async=False, callback=None, encrypted=True): """ Updates the user and perform the callback method """ if self._new_password and encrypted: self.password = Sha1.encrypt(self._new_password) controller = NURESTSession.get_current_session().login_controller contr...
Launched when save has been successfully executed
def _did_save(self, connection): """ Launched when save has been successfully executed """ self._new_password = None controller = NURESTSession.get_current_session().login_controller controller.password = None controller.api_key = self.api_key if connection.async: ...
Fetch all information about the current object
def fetch(self, async=False, callback=None): """ Fetch all information about the current object Args: async (bool): Boolean to make an asynchronous call. Default is False callback (function): Callback method that will be triggered in case of asynchronous call ...
This function retrieves the ISO 639 and inverted names datasets as tsv files and returns them as lists.
def _fabtabular(): """ This function retrieves the ISO 639 and inverted names datasets as tsv files and returns them as lists. """ import csv import sys from pkg_resources import resource_filename data = resource_filename(__package__, 'iso-639-3.tab') inverted = resource_filename(__pack...
Function for generating retired languages. Returns a dict ( code ( datetime [ language... ] description )).
def retired(self): """ Function for generating retired languages. Returns a dict('code', (datetime, [language, ...], 'description')). """ def gen(): import csv import re from datetime import datetime from pkg_resources import resource_file...
Simple getter function for languages. Takes 1 keyword/ value and returns 1 language object.
def get(self, **kwargs): """ Simple getter function for languages. Takes 1 keyword/value and returns 1 language object. """ if not len(kwargs) == 1: raise AttributeError('Only one keyword expected') key, value = kwargs.popitem() return getattr(self, key)[value...
To get a list of customers run GET against */ api/ customers/ * as authenticated user. Note that a user can only see connected customers:
def list(self, request, *args, **kwargs): """ To get a list of customers, run GET against */api/customers/* as authenticated user. Note that a user can only see connected customers: - customers that the user owns - customers that have a project where user has a role Sta...
Optional field query parameter ( can be list ) allows to limit what fields are returned. For example given request/ api/ customers/ <uuid >/ ?field = uuid&field = name you get response like this:
def retrieve(self, request, *args, **kwargs): """ Optional `field` query parameter (can be list) allows to limit what fields are returned. For example, given request /api/customers/<uuid>/?field=uuid&field=name you get response like this: .. code-block:: javascript { ...
A new customer can only be created:
def create(self, request, *args, **kwargs): """ A new customer can only be created: - by users with staff privilege (is_staff=True); - by organization owners if OWNER_CAN_MANAGE_CUSTOMER is set to True; Example of a valid request: .. code-block:: http PO...
Deletion of a customer is done through sending a ** DELETE ** request to the customer instance URI. Please note that if a customer has connected projects deletion request will fail with 409 response code.
def destroy(self, request, *args, **kwargs): """ Deletion of a customer is done through sending a **DELETE** request to the customer instance URI. Please note, that if a customer has connected projects, deletion request will fail with 409 response code. Valid request example (token is u...
To get a list of projects run ** GET ** against */ api/ projects/ * as authenticated user. Here you can also check actual value for project quotas and project usage
def list(self, request, *args, **kwargs): """ To get a list of projects, run **GET** against */api/projects/* as authenticated user. Here you can also check actual value for project quotas and project usage Note that a user can only see connected projects: - projects that the u...
Optional field query parameter ( can be list ) allows to limit what fields are returned. For example given request/ api/ projects/ <uuid >/ ?field = uuid&field = name you get response like this:
def retrieve(self, request, *args, **kwargs): """ Optional `field` query parameter (can be list) allows to limit what fields are returned. For example, given request /api/projects/<uuid>/?field=uuid&field=name you get response like this: .. code-block:: javascript { ...
A new project can be created by users with staff privilege ( is_staff = True ) or customer owners. Project resource quota is optional. Example of a valid request:
def create(self, request, *args, **kwargs): """ A new project can be created by users with staff privilege (is_staff=True) or customer owners. Project resource quota is optional. Example of a valid request: .. code-block:: http POST /api/projects/ HTTP/1.1 Conte...
Deletion of a project is done through sending a ** DELETE ** request to the project instance URI. Please note that if a project has connected instances deletion request will fail with 409 response code.
def destroy(self, request, *args, **kwargs): """ Deletion of a project is done through sending a **DELETE** request to the project instance URI. Please note, that if a project has connected instances, deletion request will fail with 409 response code. Valid request example (token is use...
A list of users connected to the project
def users(self, request, uuid=None): """ A list of users connected to the project """ project = self.get_object() queryset = project.get_users() # we need to handle filtration manually because we want to filter only project users, not projects. filter_backend = filters.UserConcat...
User list is available to all authenticated users. To get a list issue authenticated ** GET ** request against */ api/ users/ *.
def list(self, request, *args, **kwargs): """ User list is available to all authenticated users. To get a list, issue authenticated **GET** request against */api/users/*. User list supports several filters. All filters are set in HTTP query section. Field filters are listed belo...
User fields can be updated by account owner or user with staff privilege ( is_staff = True ). Following user fields can be updated:
def retrieve(self, request, *args, **kwargs): """ User fields can be updated by account owner or user with staff privilege (is_staff=True). Following user fields can be updated: - organization (deprecated, use `organization plugin <http://waldur_core-organization.readthedocs.o...
To change a user password submit a ** POST ** request to the user s RPC URL specifying new password by staff user or account owner.
def password(self, request, uuid=None): """ To change a user password, submit a **POST** request to the user's RPC URL, specifying new password by staff user or account owner. Password is expected to be at least 7 symbols long and contain at least one number and at least one low...
Project permissions expresses connection of user to a project. User may have either project manager or system administrator permission in the project. Use */ api/ project - permissions/ * endpoint to maintain project permissions.
def list(self, request, *args, **kwargs): """ Project permissions expresses connection of user to a project. User may have either project manager or system administrator permission in the project. Use */api/project-permissions/* endpoint to maintain project permissions. Note tha...
To remove a user from a project delete corresponding connection ( ** url ** field ). Successful deletion will return status code 204.
def destroy(self, request, *args, **kwargs): """ To remove a user from a project, delete corresponding connection (**url** field). Successful deletion will return status code 204. .. code-block:: http DELETE /api/project-permissions/42/ HTTP/1.1 Authorization: T...
Each customer is associated with a group of users that represent customer owners. The link is maintained through ** api/ customer - permissions/ ** endpoint.
def list(self, request, *args, **kwargs): """ Each customer is associated with a group of users that represent customer owners. The link is maintained through **api/customer-permissions/** endpoint. To list all visible links, run a **GET** query against a list. Response will con...
To remove a user from a customer owner group delete corresponding connection ( ** url ** field ). Successful deletion will return status code 204.
def retrieve(self, request, *args, **kwargs): """ To remove a user from a customer owner group, delete corresponding connection (**url** field). Successful deletion will return status code 204. .. code-block:: http DELETE /api/customer-permissions/71/ HTTP/1.1 A...
Available request parameters:
def list(self, request, *args, **kwargs): """ Available request parameters: - ?type=type_of_statistics_objects (required. Have to be from the list: 'customer', 'project') - ?from=timestamp (default: now - 30 days, for example: 1415910025) - ?to=timestamp (default: now, for examp...
To get a list of SSH keys run ** GET ** against */ api/ keys/ * as authenticated user.
def list(self, request, *args, **kwargs): """ To get a list of SSH keys, run **GET** against */api/keys/* as authenticated user. A new SSH key can be created by any active users. Example of a valid request: .. code-block:: http POST /api/keys/ HTTP/1.1 Content-...
To get a list of service settings run ** GET ** against */ api/ service - settings/ * as an authenticated user. Only settings owned by this user or shared settings will be listed.
def list(self, request, *args, **kwargs): """ To get a list of service settings, run **GET** against */api/service-settings/* as an authenticated user. Only settings owned by this user or shared settings will be listed. Supported filters are: - ?name=<text> - partial matching u...
Only staff can update shared settings otherwise user has to be an owner of the settings.
def can_user_update_settings(request, view, obj=None): """ Only staff can update shared settings, otherwise user has to be an owner of the settings.""" if obj is None: return # TODO [TM:3/21/17] clean it up after WAL-634. Clean up service settings update tests as well. if ob...
To update service settings issue a ** PUT ** or ** PATCH ** to */ api/ service - settings/ <uuid >/ * as a customer owner. You are allowed to change name and credentials only.
def update(self, request, *args, **kwargs): """ To update service settings, issue a **PUT** or **PATCH** to */api/service-settings/<uuid>/* as a customer owner. You are allowed to change name and credentials only. Example of a request: .. code-block:: http PATCH /a...
This endpoint returns allocation of resources for current service setting. Answer is service - specific dictionary. Example output for OpenStack:
def stats(self, request, uuid=None): """ This endpoint returns allocation of resources for current service setting. Answer is service-specific dictionary. Example output for OpenStack: * vcpu - maximum number of vCPUs (from hypervisors) * vcpu_quota - maximum number of vCPUs(fro...
To get a list of supported resources actions run ** OPTIONS ** against */ api/ <resource_url >/ * as an authenticated user.
def list(self, request, *args, **kwargs): """ To get a list of supported resources' actions, run **OPTIONS** against */api/<resource_url>/* as an authenticated user. It is possible to filter and order by resource-specific fields, but this filters will be applied only to resource...
Count resources by type. Example output:
def count(self, request): """ Count resources by type. Example output: .. code-block:: javascript { "Amazon.Instance": 0, "GitLab.Project": 3, "Azure.VirtualMachine": 0, "DigitalOcean.Droplet": 0, "Open...
Filter services by type ^^^^^^^^^^^^^^^^^^^^^^^
def list(self, request, *args, **kwargs): """ Filter services by type ^^^^^^^^^^^^^^^^^^^^^^^ It is possible to filter services by their types. Example: /api/services/?service_type=DigitalOcean&service_type=OpenStack """ return super(ServicesViewSet, self).lis...
To list all services without regard to its type run ** GET ** against */ api/ services/ * as an authenticated user.
def list(self, request, *args, **kwargs): """ To list all services without regard to its type, run **GET** against */api/services/* as an authenticated user. To list services of specific type issue **GET** to specific endpoint from a list above as a customer owner. Individual endpoint u...
Allow to execute action only if service settings are not shared or user is staff
def _require_staff_for_shared_settings(request, view, obj=None): """ Allow to execute action only if service settings are not shared or user is staff """ if obj is None: return if obj.settings.shared and not request.user.is_staff: raise PermissionDenied(_('Only staff use...
To get a list of resources available for import run ** GET ** against */ <service_endpoint >/ link/ * as an authenticated user. Optionally project_uuid parameter can be supplied for services requiring it like OpenStack.
def link(self, request, uuid=None): """ To get a list of resources available for import, run **GET** against */<service_endpoint>/link/* as an authenticated user. Optionally project_uuid parameter can be supplied for services requiring it like OpenStack. To import (link with Wal...
Unlink all related resources service project link and service itself.
def unlink(self, request, uuid=None): """ Unlink all related resources, service project link and service itself. """ service = self.get_object() service.unlink_descendants() self.perform_destroy(service) return Response(status=status.HTTP_204_NO_CONTENT)
To get a list of connections between a project and an service run ** GET ** against service_project_link_url as authenticated user. Note that a user can only see connections of a project where a user has a role.
def list(self, request, *args, **kwargs): """ To get a list of connections between a project and an service, run **GET** against service_project_link_url as authenticated user. Note that a user can only see connections of a project where a user has a role. If service has `available_for_...
To remove a link issue ** DELETE ** to URL of the corresponding connection as stuff user or customer owner.
def retrieve(self, request, *args, **kwargs): """ To remove a link, issue **DELETE** to URL of the corresponding connection as stuff user or customer owner. """ return super(BaseServiceProjectLinkViewSet, self).retrieve(request, *args, **kwargs)