sentence1
stringlengths 52
3.87M
| sentence2
stringlengths 1
47.2k
| label
stringclasses 1
value |
|---|---|---|
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").__name__
)
|
Decide if the Ipython command line is running code.
|
entailment
|
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_registry:
cls._model_rest_name_registry[rest_name] = [model]
cls._model_resource_name_registry[resource_name] = [model]
elif model not in cls._model_rest_name_registry[rest_name]:
cls._model_rest_name_registry[rest_name].append(model)
cls._model_resource_name_registry[resource_name].append(model)
|
Register a model class according to its remote name
Args:
model: the model to register
|
entailment
|
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 None
|
Get the first model corresponding to a rest_name
Args:
rest_name: the rest name
|
entailment
|
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 models[0]
return None
|
Get the first model corresponding to a resource_name
Args:
resource_name: the resource name
|
entailment
|
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
self._rx_queue.put('closed')
self.notice()
break
except Empty:
# pragma: no cover
continue
try:
result = func()
self._rx_queue.put(result)
except Exception as e:
self._rx_queue.put(e)
self.notice()
else:
# pragma: no cover
pass
|
执行任务
|
entailment
|
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]
fields_comparison = [all_fields[1]]
# chart type widget
self.register_widget(
chart_type=widgets.RadioButtons(
options=['individual', 'grouped'],
value='individual',
description='Chart Type:'
)
)
# bins widget
self.register_widget(
bins=IntSlider(
description='Bins:',
min=2, max=10, value=2,
continuous_update=False
)
)
# fields comparison widget
self.register_widget(
xs=widgets.SelectMultiple(
description='Xs:',
options=[f for f in all_fields if not f == field_reference],
value=fields_comparison
)
)
# field reference widget
self.register_widget(
y=widgets.Dropdown(
description='Y:',
options=all_fields,
value=field_reference
)
)
# used to internal flow control
y_changed = [False]
self.register_widget(
box_filter_panel=widgets.VBox([
self._('y'), self._('xs'), self._('bins')
])
)
# layout widgets
self.register_widget(
table=widgets.HTML(),
chart=widgets.HTML()
)
self.register_widget(vbox_chart=widgets.VBox([
self._('chart_type'), self._('chart')
]))
self.register_widget(
tab=widgets.Tab(
children=[
self._('box_filter_panel'),
self._('table'),
self._('vbox_chart')
]
)
)
self.register_widget(dashboard=widgets.HBox([self._('tab')]))
# observe hooks
def w_y_change(change: dict):
"""
When y field was changed xs field should be updated and data table
and chart should be displayed/updated.
:param change:
:return:
"""
# remove reference field from the comparison field list
_xs = [
f for f in all_fields
if not f == change['new']
]
y_changed[0] = True # flow control variable
_xs_value = list(self._('xs').value)
if change['new'] in self._('xs').value:
_xs_value.pop(_xs_value.index(change['new']))
if not _xs_value:
_xs_value = [_xs[0]]
self._('xs').options = _xs
self._('xs').value = _xs_value
self._display_result(y=change['new'], dset_id=dset_id)
y_changed[0] = False # flow control variable
# widgets registration
# change tab settings
self._('tab').set_title(0, 'Filter')
self._('tab').set_title(1, 'Data')
self._('tab').set_title(2, 'Chart')
# data panel
self._('table').value = '...'
# chart panel
self._('chart').value = '...'
# create observe callbacks
self._('bins').observe(
lambda change: (
self._display_result(bins=change['new'], dset_id=dset_id)
), 'value'
)
self._('y').observe(w_y_change, 'value')
# execute display result if 'y' was not changing.
self._('xs').observe(
lambda change: (
self._display_result(xs=change['new'], dset_id=dset_id)
if not y_changed[0] else None
), 'value'
)
self._('chart_type').observe(
lambda change: (
self._display_result(chart_type=change['new'], dset_id=dset_id)
), 'value'
)
|
:param dset_id:
:return:
|
entailment
|
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 chart
self._display_result(dset_id=dset_id)
|
:param dset_id:
:return:
|
entailment
|
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
if "." in fullname:
original, fullname = fullname.rsplit(".", 1)
else:
original, fullname = "", original
if "_" in fullname:
files = fuzzy_file_search(self.path, fullname)
if files:
file = Path(sorted(files)[0])
spec = super().find_spec(
(original + "." + file.stem.split(".", 1)[0]).lstrip("."), target=target
)
fullname = (original + "." + fullname).lstrip(".")
if spec and fullname != spec.name:
spec = FuzzySpec(
spec.name,
spec.loader,
origin=spec.origin,
loader_state=spec.loader_state,
alias=fullname,
is_package=bool(spec.submodule_search_locations),
)
return spec
|
Try to finder the spec and if it cannot be found, use the underscore starring syntax
to identify potential matches.
|
entailment
|
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)
|
Get resource complete url
|
entailment
|
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
controller.password = self._new_password
controller.api_key = None
data = json.dumps(self.to_dict())
request = NURESTRequest(method=HTTP_METHOD_PUT, url=self.get_resource_url(), data=data)
if async:
return self.send_request(request=request, async=async, local_callback=self._did_save, remote_callback=callback)
else:
connection = self.send_request(request=request)
return self._did_save(connection)
|
Updates the user and perform the callback method
|
entailment
|
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:
callback = connection.callbacks['remote']
if connection.user_info:
callback(connection.user_info, connection)
else:
callback(self, connection)
else:
return (self, connection)
|
Launched when save has been successfully executed
|
entailment
|
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
Returns:
tuple: (current_fetcher, callee_parent, fetched_bjects, connection)
Example:
>>> entity = NUEntity(id="xxx-xxx-xxx-xxx")
>>> entity.fetch() # will get the entity with id "xxx-xxx-xxx-xxx"
>>> print entity.name
"My Entity"
"""
request = NURESTRequest(method=HTTP_METHOD_GET, url=self.get_resource_url())
if async:
return self.send_request(request=request, async=async, local_callback=self._did_fetch, remote_callback=callback)
else:
connection = self.send_request(request=request)
return self._did_retrieve(connection)
|
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
Returns:
tuple: (current_fetcher, callee_parent, fetched_bjects, connection)
Example:
>>> entity = NUEntity(id="xxx-xxx-xxx-xxx")
>>> entity.fetch() # will get the entity with id "xxx-xxx-xxx-xxx"
>>> print entity.name
"My Entity"
|
entailment
|
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(__package__, 'iso-639-3_Name_Index.tab')
macro = resource_filename(__package__, 'iso-639-3-macrolanguages.tab')
part5 = resource_filename(__package__, 'iso639-5.tsv')
part2 = resource_filename(__package__, 'iso639-2.tsv')
part1 = resource_filename(__package__, 'iso639-1.tsv')
# if sys.version_info[0] == 2:
# from urllib2 import urlopen
# from contextlib import closing
# data_fo = closing(urlopen('http://www-01.sil.org/iso639-3/iso-639-3.tab'))
# inverted_fo = closing(urlopen('http://www-01.sil.org/iso639-3/iso-639-3_Name_Index.tab'))
# else:
# from urllib.request import urlopen
# import io
# data_fo = io.StringIO(urlopen('http://www-01.sil.org/iso639-3/iso-639-3.tab').read().decode())
# inverted_fo = io.StringIO(urlopen('http://www-01.sil.org/iso639-3/iso-639-3_Name_Index.tab').read().decode())
if sys.version_info[0] == 3:
from functools import partial
global open
open = partial(open, encoding='utf-8')
data_fo = open(data)
inverted_fo = open(inverted)
macro_fo = open(macro)
part5_fo = open(part5)
part2_fo = open(part2)
part1_fo = open(part1)
with data_fo as u:
with inverted_fo as i:
with macro_fo as m:
with part5_fo as p5:
with part2_fo as p2:
with part1_fo as p1:
return (list(csv.reader(u, delimiter='\t'))[1:],
list(csv.reader(i, delimiter='\t'))[1:],
list(csv.reader(m, delimiter='\t'))[1:],
list(csv.reader(p5, delimiter='\t'))[1:],
list(csv.reader(p2, delimiter='\t'))[1:],
list(csv.reader(p1, delimiter='\t'))[1:])
|
This function retrieves the ISO 639 and inverted names datasets as tsv files and returns them as lists.
|
entailment
|
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_filename
with open(resource_filename(__package__, 'iso-639-3_Retirements.tab')) as rf:
rtd = list(csv.reader(rf, delimiter='\t'))[1:]
rc = [r[0] for r in rtd]
for i, _, _, m, s, d in rtd:
d = datetime.strptime(d, '%Y-%m-%d')
if not m:
m = re.findall('\[([a-z]{3})\]', s)
if m:
m = [m] if isinstance(m, str) else m
yield i, (d, [self.get(part3=x) for x in m if x not in rc], s)
else:
yield i, (d, [], s)
yield 'sh', self.get(part3='hbs') # Add 'sh' as deprecated
return dict(gen())
|
Function for generating retired languages. Returns a dict('code', (datetime, [language, ...], 'description')).
|
entailment
|
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]
|
Simple getter function for languages. Takes 1 keyword/value and returns 1 language object.
|
entailment
|
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
Staff also can filter customers by user UUID, for example /api/customers/?user_uuid=<UUID>
Staff also can filter customers by exists accounting_start_date, for example:
The first category:
/api/customers/?accounting_is_running=True
has accounting_start_date empty (i.e. accounting starts at once)
has accounting_start_date in the past (i.e. has already started).
Those that are not in the first:
/api/customers/?accounting_is_running=False # exists accounting_start_date
"""
return super(CustomerViewSet, self).list(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
Staff also can filter customers by user UUID, for example /api/customers/?user_uuid=<UUID>
Staff also can filter customers by exists accounting_start_date, for example:
The first category:
/api/customers/?accounting_is_running=True
has accounting_start_date empty (i.e. accounting starts at once)
has accounting_start_date in the past (i.e. has already started).
Those that are not in the first:
/api/customers/?accounting_is_running=False # exists accounting_start_date
|
entailment
|
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
{
"uuid": "90bcfe38b0124c9bbdadd617b5d739f5",
"name": "Ministry of Bells"
}
"""
return super(CustomerViewSet, self).retrieve(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
{
"uuid": "90bcfe38b0124c9bbdadd617b5d739f5",
"name": "Ministry of Bells"
}
|
entailment
|
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
POST /api/customers/ HTTP/1.1
Content-Type: application/json
Accept: application/json
Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4
Host: example.com
{
"name": "Customer A",
"native_name": "Customer A",
"abbreviation": "CA",
"contact_details": "Luhamaa 28, 10128 Tallinn",
}
"""
return super(CustomerViewSet, self).create(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
POST /api/customers/ HTTP/1.1
Content-Type: application/json
Accept: application/json
Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4
Host: example.com
{
"name": "Customer A",
"native_name": "Customer A",
"abbreviation": "CA",
"contact_details": "Luhamaa 28, 10128 Tallinn",
}
|
entailment
|
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 user specific):
.. code-block:: http
DELETE /api/customers/6c9b01c251c24174a6691a1f894fae31/ HTTP/1.1
Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4
Host: example.com
"""
return super(CustomerViewSet, self).destroy(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 user specific):
.. code-block:: http
DELETE /api/customers/6c9b01c251c24174a6691a1f894fae31/ HTTP/1.1
Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4
Host: example.com
|
entailment
|
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 user owns as a customer
- projects where user has any role
Supported logic filters:
- ?can_manage - return a list of projects where current user is manager or a customer owner;
- ?can_admin - return a list of projects where current user is admin;
"""
return super(ProjectViewSet, self).list(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 user owns as a customer
- projects where user has any role
Supported logic filters:
- ?can_manage - return a list of projects where current user is manager or a customer owner;
- ?can_admin - return a list of projects where current user is admin;
|
entailment
|
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
{
"uuid": "90bcfe38b0124c9bbdadd617b5d739f5",
"name": "Default"
}
"""
return super(ProjectViewSet, self).retrieve(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
{
"uuid": "90bcfe38b0124c9bbdadd617b5d739f5",
"name": "Default"
}
|
entailment
|
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
Content-Type: application/json
Accept: application/json
Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4
Host: example.com
{
"name": "Project A",
"customer": "http://example.com/api/customers/6c9b01c251c24174a6691a1f894fae31/",
}
"""
return super(ProjectViewSet, self).create(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
Content-Type: application/json
Accept: application/json
Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4
Host: example.com
{
"name": "Project A",
"customer": "http://example.com/api/customers/6c9b01c251c24174a6691a1f894fae31/",
}
|
entailment
|
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 user specific):
.. code-block:: http
DELETE /api/projects/6c9b01c251c24174a6691a1f894fae31/ HTTP/1.1
Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4
Host: example.com
"""
return super(ProjectViewSet, self).destroy(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 user specific):
.. code-block:: http
DELETE /api/projects/6c9b01c251c24174a6691a1f894fae31/ HTTP/1.1
Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4
Host: example.com
|
entailment
|
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.UserConcatenatedNameOrderingBackend()
queryset = filter_backend.filter_queryset(request, queryset, self)
queryset = self.paginate_queryset(queryset)
serializer = self.get_serializer(queryset, many=True)
return self.get_paginated_response(serializer.data)
|
A list of users connected to the project
|
entailment
|
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 below. All of the filters apart from ?organization are
using case insensitive partial matching.
Several custom filters are supported:
- ?current - filters out user making a request. Useful for getting information about a currently logged in user.
- ?civil_number=XXX - filters out users with a specified civil number
- ?is_active=True|False - show only active (non-active) users
The user can be created either through automated process on login with SAML token, or through a REST call by a user
with staff privilege.
Example of a creation request is below.
.. code-block:: http
POST /api/users/ HTTP/1.1
Content-Type: application/json
Accept: application/json
Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4
Host: example.com
{
"username": "sample-user",
"full_name": "full name",
"native_name": "taisnimi",
"job_title": "senior cleaning manager",
"email": "example@example.com",
"civil_number": "12121212",
"phone_number": "",
"description": "",
"organization": "",
}
NB! Username field is case-insensitive. So "John" and "john" will be treated as the same user.
"""
return super(UserViewSet, self).list(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 below. All of the filters apart from ?organization are
using case insensitive partial matching.
Several custom filters are supported:
- ?current - filters out user making a request. Useful for getting information about a currently logged in user.
- ?civil_number=XXX - filters out users with a specified civil number
- ?is_active=True|False - show only active (non-active) users
The user can be created either through automated process on login with SAML token, or through a REST call by a user
with staff privilege.
Example of a creation request is below.
.. code-block:: http
POST /api/users/ HTTP/1.1
Content-Type: application/json
Accept: application/json
Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4
Host: example.com
{
"username": "sample-user",
"full_name": "full name",
"native_name": "taisnimi",
"job_title": "senior cleaning manager",
"email": "example@example.com",
"civil_number": "12121212",
"phone_number": "",
"description": "",
"organization": "",
}
NB! Username field is case-insensitive. So "John" and "john" will be treated as the same user.
|
entailment
|
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.org/en/stable/>`_ instead)
- full_name
- native_name
- job_title
- phone_number
- email
Can be done by **PUT**ing a new data to the user URI, i.e. */api/users/<UUID>/* by staff user or account owner.
Valid request example (token is user specific):
.. code-block:: http
PUT /api/users/e0c058d06864441fb4f1c40dee5dd4fd/ HTTP/1.1
Content-Type: application/json
Accept: application/json
Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4
Host: example.com
{
"email": "example@example.com",
"organization": "Bells organization",
}
"""
return super(UserViewSet, self).retrieve(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.org/en/stable/>`_ instead)
- full_name
- native_name
- job_title
- phone_number
- email
Can be done by **PUT**ing a new data to the user URI, i.e. */api/users/<UUID>/* by staff user or account owner.
Valid request example (token is user specific):
.. code-block:: http
PUT /api/users/e0c058d06864441fb4f1c40dee5dd4fd/ HTTP/1.1
Content-Type: application/json
Accept: application/json
Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4
Host: example.com
{
"email": "example@example.com",
"organization": "Bells organization",
}
|
entailment
|
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 lower or upper case.
Example of a valid request:
.. code-block:: http
POST /api/users/e0c058d06864441fb4f1c40dee5dd4fd/password/ HTTP/1.1
Content-Type: application/json
Accept: application/json
Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4
Host: example.com
{
"password": "nQvqHzeP123",
}
"""
user = self.get_object()
serializer = serializers.PasswordSerializer(data=request.data)
serializer.is_valid(raise_exception=True)
new_password = serializer.validated_data['password']
user.set_password(new_password)
user.save()
return Response({'detail': _('Password has been successfully updated.')},
status=status.HTTP_200_OK)
|
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 lower or upper case.
Example of a valid request:
.. code-block:: http
POST /api/users/e0c058d06864441fb4f1c40dee5dd4fd/password/ HTTP/1.1
Content-Type: application/json
Accept: application/json
Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4
Host: example.com
{
"password": "nQvqHzeP123",
}
|
entailment
|
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 that project permissions can be viewed and modified only by customer owners and staff users.
To list all visible permissions, run a **GET** query against a list.
Response will contain a list of project users and their brief data.
To add a new user to the project, **POST** a new relationship to */api/project-permissions/* endpoint specifying
project, user and the role of the user ('admin' or 'manager'):
.. code-block:: http
POST /api/project-permissions/ HTTP/1.1
Accept: application/json
Authorization: Token 95a688962bf68678fd4c8cec4d138ddd9493c93b
Host: example.com
{
"project": "http://example.com/api/projects/6c9b01c251c24174a6691a1f894fae31/",
"role": "manager",
"user": "http://example.com/api/users/82cec6c8e0484e0ab1429412fe4194b7/"
}
"""
return super(ProjectPermissionViewSet, self).list(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 that project permissions can be viewed and modified only by customer owners and staff users.
To list all visible permissions, run a **GET** query against a list.
Response will contain a list of project users and their brief data.
To add a new user to the project, **POST** a new relationship to */api/project-permissions/* endpoint specifying
project, user and the role of the user ('admin' or 'manager'):
.. code-block:: http
POST /api/project-permissions/ HTTP/1.1
Accept: application/json
Authorization: Token 95a688962bf68678fd4c8cec4d138ddd9493c93b
Host: example.com
{
"project": "http://example.com/api/projects/6c9b01c251c24174a6691a1f894fae31/",
"role": "manager",
"user": "http://example.com/api/users/82cec6c8e0484e0ab1429412fe4194b7/"
}
|
entailment
|
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: Token 95a688962bf68678fd4c8cec4d138ddd9493c93b
Host: example.com
"""
return super(ProjectPermissionViewSet, self).destroy(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: Token 95a688962bf68678fd4c8cec4d138ddd9493c93b
Host: example.com
|
entailment
|
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 contain a list of customer owners and their brief data.
To add a new user to the customer, **POST** a new relationship to **customer-permissions** endpoint:
.. code-block:: http
POST /api/customer-permissions/ HTTP/1.1
Accept: application/json
Authorization: Token 95a688962bf68678fd4c8cec4d138ddd9493c93b
Host: example.com
{
"customer": "http://example.com/api/customers/6c9b01c251c24174a6691a1f894fae31/",
"role": "owner",
"user": "http://example.com/api/users/82cec6c8e0484e0ab1429412fe4194b7/"
}
"""
return super(CustomerPermissionViewSet, self).list(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 contain a list of customer owners and their brief data.
To add a new user to the customer, **POST** a new relationship to **customer-permissions** endpoint:
.. code-block:: http
POST /api/customer-permissions/ HTTP/1.1
Accept: application/json
Authorization: Token 95a688962bf68678fd4c8cec4d138ddd9493c93b
Host: example.com
{
"customer": "http://example.com/api/customers/6c9b01c251c24174a6691a1f894fae31/",
"role": "owner",
"user": "http://example.com/api/users/82cec6c8e0484e0ab1429412fe4194b7/"
}
|
entailment
|
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
Authorization: Token 95a688962bf68678fd4c8cec4d138ddd9493c93b
Host: example.com
"""
return super(CustomerPermissionViewSet, self).retrieve(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
Authorization: Token 95a688962bf68678fd4c8cec4d138ddd9493c93b
Host: example.com
|
entailment
|
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 example: 1415912625)
- ?datapoints=how many data points have to be in answer (default: 6)
Answer will be list of datapoints(dictionaries).
Each datapoint will contain fields: 'to', 'from', 'value'.
'Value' - count of objects, that were created between 'from' and 'to' dates.
Example:
.. code-block:: javascript
[
{"to": 471970877, "from": 1, "value": 5},
{"to": 943941753, "from": 471970877, "value": 0},
{"to": 1415912629, "from": 943941753, "value": 3}
]
"""
return super(CreationTimeStatsView, self).list(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 example: 1415912625)
- ?datapoints=how many data points have to be in answer (default: 6)
Answer will be list of datapoints(dictionaries).
Each datapoint will contain fields: 'to', 'from', 'value'.
'Value' - count of objects, that were created between 'from' and 'to' dates.
Example:
.. code-block:: javascript
[
{"to": 471970877, "from": 1, "value": 5},
{"to": 943941753, "from": 471970877, "value": 0},
{"to": 1415912629, "from": 943941753, "value": 3}
]
|
entailment
|
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-Type: application/json
Accept: application/json
Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4
Host: example.com
{
"name": "ssh_public_key1",
"public_key": "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDDURXDP5YhOQUYoDuTxJ84DuzqMJYJqJ8+SZT28
TtLm5yBDRLKAERqtlbH2gkrQ3US58gd2r8H9jAmQOydfvgwauxuJUE4eDpaMWupqquMYsYLB5f+vVGhdZbbzfc6DTQ2rY
dknWoMoArlG7MvRMA/xQ0ye1muTv+mYMipnd7Z+WH0uVArYI9QBpqC/gpZRRIouQ4VIQIVWGoT6M4Kat5ZBXEa9yP+9du
D2C05GX3gumoSAVyAcDHn/xgej9pYRXGha4l+LKkFdGwAoXdV1z79EG1+9ns7wXuqMJFHM2KDpxAizV0GkZcojISvDwuh
vEAFdOJcqjyyH4FOGYa8usP1 jhon@example.com",
}
"""
return super(SshKeyViewSet, self).list(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-Type: application/json
Accept: application/json
Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4
Host: example.com
{
"name": "ssh_public_key1",
"public_key": "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDDURXDP5YhOQUYoDuTxJ84DuzqMJYJqJ8+SZT28
TtLm5yBDRLKAERqtlbH2gkrQ3US58gd2r8H9jAmQOydfvgwauxuJUE4eDpaMWupqquMYsYLB5f+vVGhdZbbzfc6DTQ2rY
dknWoMoArlG7MvRMA/xQ0ye1muTv+mYMipnd7Z+WH0uVArYI9QBpqC/gpZRRIouQ4VIQIVWGoT6M4Kat5ZBXEa9yP+9du
D2C05GX3gumoSAVyAcDHn/xgej9pYRXGha4l+LKkFdGwAoXdV1z79EG1+9ns7wXuqMJFHM2KDpxAizV0GkZcojISvDwuh
vEAFdOJcqjyyH4FOGYa8usP1 jhon@example.com",
}
|
entailment
|
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 used for searching
- ?type=<type> - choices: OpenStack, DigitalOcean, Amazon, JIRA, GitLab, Oracle
- ?state=<state> - choices: New, Creation Scheduled, Creating, Sync Scheduled, Syncing, In Sync, Erred
- ?shared=<bool> - allows to filter shared service settings
"""
return super(ServiceSettingsViewSet, self).list(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 used for searching
- ?type=<type> - choices: OpenStack, DigitalOcean, Amazon, JIRA, GitLab, Oracle
- ?state=<state> - choices: New, Creation Scheduled, Creating, Sync Scheduled, Syncing, In Sync, Erred
- ?shared=<bool> - allows to filter shared service settings
|
entailment
|
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 obj.customer and not obj.shared:
return permissions.is_owner(request, view, obj)
else:
return permissions.is_staff(request, view, obj)
|
Only staff can update shared settings, otherwise user has to be an owner of the settings.
|
entailment
|
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 /api/service-settings/9079705c17d64e6aa0af2e619b0e0702/ HTTP/1.1
Content-Type: application/json
Accept: application/json
Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4
Host: example.com
{
"username": "admin",
"password": "new_secret"
}
"""
return super(ServiceSettingsViewSet, self).update(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 /api/service-settings/9079705c17d64e6aa0af2e619b0e0702/ HTTP/1.1
Content-Type: application/json
Accept: application/json
Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4
Host: example.com
{
"username": "admin",
"password": "new_secret"
}
|
entailment
|
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(from quotas)
* vcpu_usage - current number of used vCPUs
* ram - total size of memory for allocation (from hypervisors)
* ram_quota - maximum number of memory (from quotas)
* ram_usage - currently used memory size on all physical hosts
* storage - total available disk space on all physical hosts (from hypervisors)
* storage_quota - maximum number of storage (from quotas)
* storage_usage - currently used storage on all physical hosts
{
'vcpu': 10,
'vcpu_quota': 7,
'vcpu_usage': 5,
'ram': 1000,
'ram_quota': 700,
'ram_usage': 500,
'storage': 10000,
'storage_quota': 7000,
'storage_usage': 5000
}
"""
service_settings = self.get_object()
backend = service_settings.get_backend()
try:
stats = backend.get_stats()
except ServiceBackendNotImplemented:
stats = {}
return Response(stats, status=status.HTTP_200_OK)
|
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(from quotas)
* vcpu_usage - current number of used vCPUs
* ram - total size of memory for allocation (from hypervisors)
* ram_quota - maximum number of memory (from quotas)
* ram_usage - currently used memory size on all physical hosts
* storage - total available disk space on all physical hosts (from hypervisors)
* storage_quota - maximum number of storage (from quotas)
* storage_usage - currently used storage on all physical hosts
{
'vcpu': 10,
'vcpu_quota': 7,
'vcpu_usage': 5,
'ram': 1000,
'ram_quota': 700,
'ram_usage': 500,
'storage': 10000,
'storage_quota': 7000,
'storage_usage': 5000
}
|
entailment
|
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
resources that support such filtering. For example it is possible to sort resource by ?o=ram, but SugarCRM crms
will ignore this ordering, because they do not support such option.
Filter resources by type or category
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
There are two query argument to select resources by their type.
- Specify explicitly list of resource types, for example:
/api/<resource_endpoint>/?resource_type=DigitalOcean.Droplet&resource_type=OpenStack.Instance
- Specify category, one of vms, apps, private_clouds or storages for example:
/api/<resource_endpoint>/?category=vms
Filtering by monitoring fields
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Resources may have SLA attached to it. Example rendering of SLA:
.. code-block:: javascript
"sla": {
"value": 95.0
"agreed_value": 99.0,
"period": "2016-03"
}
You may filter or order resources by SLA. Default period is current year and month.
- Example query for filtering list of resources by actual SLA:
/api/<resource_endpoint>/?actual_sla=90&period=2016-02
- Warning! If resource does not have SLA attached to it, it is not included in ordered response.
Example query for ordering list of resources by actual SLA:
/api/<resource_endpoint>/?o=actual_sla&period=2016-02
Service list is displaying current SLAs for each of the items. By default,
SLA period is set to the current month. To change the period pass it as a query argument:
- ?period=YYYY-MM - return a list with SLAs for a given month
- ?period=YYYY - return a list with SLAs for a given year
In all cases all currently running resources are returned, if SLA for the given period is
not known or not present, it will be shown as **null** in the response.
Resources may have monitoring items attached to it. Example rendering of monitoring items:
.. code-block:: javascript
"monitoring_items": {
"application_state": 1
}
You may filter or order resources by monitoring item.
- Example query for filtering list of resources by installation state:
/api/<resource_endpoint>/?monitoring__installation_state=1
- Warning! If resource does not have monitoring item attached to it, it is not included in ordered response.
Example query for ordering list of resources by installation state:
/api/<resource_endpoint>/?o=monitoring__installation_state
Filtering by tags
^^^^^^^^^^^^^^^^^
Resource may have tags attached to it. Example of tags rendering:
.. code-block:: javascript
"tags": [
"license-os:centos7",
"os-family:linux",
"license-application:postgresql",
"support:premium"
]
Tags filtering:
- ?tag=IaaS - filter by full tag name, using method OR. Can be list.
- ?rtag=os-family:linux - filter by full tag name, using AND method. Can be list.
- ?tag__license-os=centos7 - filter by tags with particular prefix.
Tags ordering:
- ?o=tag__license-os - order by tag with particular prefix. Instances without given tag will not be returned.
"""
return super(ResourceSummaryViewSet, self).list(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
resources that support such filtering. For example it is possible to sort resource by ?o=ram, but SugarCRM crms
will ignore this ordering, because they do not support such option.
Filter resources by type or category
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
There are two query argument to select resources by their type.
- Specify explicitly list of resource types, for example:
/api/<resource_endpoint>/?resource_type=DigitalOcean.Droplet&resource_type=OpenStack.Instance
- Specify category, one of vms, apps, private_clouds or storages for example:
/api/<resource_endpoint>/?category=vms
Filtering by monitoring fields
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Resources may have SLA attached to it. Example rendering of SLA:
.. code-block:: javascript
"sla": {
"value": 95.0
"agreed_value": 99.0,
"period": "2016-03"
}
You may filter or order resources by SLA. Default period is current year and month.
- Example query for filtering list of resources by actual SLA:
/api/<resource_endpoint>/?actual_sla=90&period=2016-02
- Warning! If resource does not have SLA attached to it, it is not included in ordered response.
Example query for ordering list of resources by actual SLA:
/api/<resource_endpoint>/?o=actual_sla&period=2016-02
Service list is displaying current SLAs for each of the items. By default,
SLA period is set to the current month. To change the period pass it as a query argument:
- ?period=YYYY-MM - return a list with SLAs for a given month
- ?period=YYYY - return a list with SLAs for a given year
In all cases all currently running resources are returned, if SLA for the given period is
not known or not present, it will be shown as **null** in the response.
Resources may have monitoring items attached to it. Example rendering of monitoring items:
.. code-block:: javascript
"monitoring_items": {
"application_state": 1
}
You may filter or order resources by monitoring item.
- Example query for filtering list of resources by installation state:
/api/<resource_endpoint>/?monitoring__installation_state=1
- Warning! If resource does not have monitoring item attached to it, it is not included in ordered response.
Example query for ordering list of resources by installation state:
/api/<resource_endpoint>/?o=monitoring__installation_state
Filtering by tags
^^^^^^^^^^^^^^^^^
Resource may have tags attached to it. Example of tags rendering:
.. code-block:: javascript
"tags": [
"license-os:centos7",
"os-family:linux",
"license-application:postgresql",
"support:premium"
]
Tags filtering:
- ?tag=IaaS - filter by full tag name, using method OR. Can be list.
- ?rtag=os-family:linux - filter by full tag name, using AND method. Can be list.
- ?tag__license-os=centos7 - filter by tags with particular prefix.
Tags ordering:
- ?o=tag__license-os - order by tag with particular prefix. Instances without given tag will not be returned.
|
entailment
|
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,
"OpenStack.Instance": 0,
"GitLab.Group": 8
}
"""
queryset = self.filter_queryset(self.get_queryset())
return Response({SupportedServices.get_name_for_model(qs.model): qs.count()
for qs in queryset.querysets})
|
Count resources by type. Example output:
.. code-block:: javascript
{
"Amazon.Instance": 0,
"GitLab.Project": 3,
"Azure.VirtualMachine": 0,
"DigitalOcean.Droplet": 0,
"OpenStack.Instance": 0,
"GitLab.Group": 8
}
|
entailment
|
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).list(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
|
entailment
|
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 used for every service type.
To create a service, issue a **POST** to specific endpoint from a list above as a customer owner.
Individual endpoint used for every service type.
You can create service based on shared service settings. Example:
.. code-block:: http
POST /api/digitalocean/ HTTP/1.1
Content-Type: application/json
Accept: application/json
Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4
Host: example.com
{
"name": "Common DigitalOcean",
"customer": "http://example.com/api/customers/1040561ca9e046d2b74268600c7e1105/",
"settings": "http://example.com/api/service-settings/93ba615d6111466ebe3f792669059cb4/"
}
Or provide your own credentials. Example:
.. code-block:: http
POST /api/oracle/ HTTP/1.1
Content-Type: application/json
Accept: application/json
Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4
Host: example.com
{
"name": "My Oracle",
"customer": "http://example.com/api/customers/1040561ca9e046d2b74268600c7e1105/",
"backend_url": "https://oracle.example.com:7802/em",
"username": "admin",
"password": "secret"
}
"""
return super(BaseServiceViewSet, self).list(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 used for every service type.
To create a service, issue a **POST** to specific endpoint from a list above as a customer owner.
Individual endpoint used for every service type.
You can create service based on shared service settings. Example:
.. code-block:: http
POST /api/digitalocean/ HTTP/1.1
Content-Type: application/json
Accept: application/json
Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4
Host: example.com
{
"name": "Common DigitalOcean",
"customer": "http://example.com/api/customers/1040561ca9e046d2b74268600c7e1105/",
"settings": "http://example.com/api/service-settings/93ba615d6111466ebe3f792669059cb4/"
}
Or provide your own credentials. Example:
.. code-block:: http
POST /api/oracle/ HTTP/1.1
Content-Type: application/json
Accept: application/json
Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4
Host: example.com
{
"name": "My Oracle",
"customer": "http://example.com/api/customers/1040561ca9e046d2b74268600c7e1105/",
"backend_url": "https://oracle.example.com:7802/em",
"username": "admin",
"password": "secret"
}
|
entailment
|
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 users are allowed to import resources from shared services.'))
|
Allow to execute action only if service settings are not shared or user is staff
|
entailment
|
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 Waldur) resource issue **POST** against the same endpoint with resource id.
.. code-block:: http
POST /api/openstack/08039f01c9794efc912f1689f4530cf0/link/ HTTP/1.1
Content-Type: application/json
Accept: application/json
Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4
Host: example.com
{
"backend_id": "bd5ec24d-9164-440b-a9f2-1b3c807c5df3",
"project": "http://example.com/api/projects/e5f973af2eb14d2d8c38d62bcbaccb33/"
}
"""
service = self.get_object()
if self.request.method == 'GET':
try:
backend = self.get_backend(service)
try:
resources = backend.get_resources_for_import(**self.get_import_context())
except ServiceBackendNotImplemented:
resources = []
page = self.paginate_queryset(resources)
if page is not None:
return self.get_paginated_response(page)
return Response(resources)
except (ServiceBackendError, ValidationError) as e:
raise APIException(e)
else:
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
try:
resource = serializer.save()
except ServiceBackendError as e:
raise APIException(e)
resource_imported.send(
sender=resource.__class__,
instance=resource,
)
return Response(serializer.data, status=status.HTTP_200_OK)
|
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 Waldur) resource issue **POST** against the same endpoint with resource id.
.. code-block:: http
POST /api/openstack/08039f01c9794efc912f1689f4530cf0/link/ HTTP/1.1
Content-Type: application/json
Accept: application/json
Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4
Host: example.com
{
"backend_id": "bd5ec24d-9164-440b-a9f2-1b3c807c5df3",
"project": "http://example.com/api/projects/e5f973af2eb14d2d8c38d62bcbaccb33/"
}
|
entailment
|
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)
|
Unlink all related resources, service project link and service itself.
|
entailment
|
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_all` flag, project-service connections are created automatically.
Otherwise, in order to be able to provision resources, service must first be linked to a project.
To do that, **POST** a connection between project and a service to service_project_link_url
as stuff user or customer owner.
"""
return super(BaseServiceProjectLinkViewSet, self).list(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_all` flag, project-service connections are created automatically.
Otherwise, in order to be able to provision resources, service must first be linked to a project.
To do that, **POST** a connection between project and a service to service_project_link_url
as stuff user or customer owner.
|
entailment
|
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)
|
To remove a link, issue **DELETE** to URL of the corresponding connection as stuff user or customer owner.
|
entailment
|
def get_aggregator_quotas(self, quota):
""" Fetch ancestors quotas that have the same name and are registered as aggregator quotas. """
ancestors = quota.scope.get_quota_ancestors()
aggregator_quotas = []
for ancestor in ancestors:
for ancestor_quota_field in ancestor.get_quotas_fields(field_class=AggregatorQuotaField):
if ancestor_quota_field.get_child_quota_name() == quota.name:
aggregator_quotas.append(ancestor.quotas.get(name=ancestor_quota_field))
return aggregator_quotas
|
Fetch ancestors quotas that have the same name and are registered as aggregator quotas.
|
entailment
|
def subscribe(self, handler):
"""Adds a new event handler."""
assert callable(handler), "Invalid handler %s" % handler
self.handlers.append(handler)
|
Adds a new event handler.
|
entailment
|
def safe_trigger(self, *args):
"""*Safely* triggers the event by invoking all its
handlers, even if few of them raise an exception.
If a set of exceptions is raised during handler
invocation sequence, this method rethrows the first one.
:param args: the arguments to invoke event handlers with.
"""
error = None
# iterate over a copy of the original list because some event handlers
# may mutate the list
for handler in list(self.handlers):
try:
handler(*args)
except BaseException as e:
if error is None:
prepare_for_reraise(e)
error = e
if error is not None:
reraise(error)
|
*Safely* triggers the event by invoking all its
handlers, even if few of them raise an exception.
If a set of exceptions is raised during handler
invocation sequence, this method rethrows the first one.
:param args: the arguments to invoke event handlers with.
|
entailment
|
def on(self, event, handler):
"""Attaches the handler to the specified event.
@param event: event to attach the handler to. Any object can be passed
as event, but string is preferable. If qcore.EnumBase
instance is passed, its name is used as event key.
@param handler: event handler.
@return: self, so calls like this can be chained together.
"""
event_hook = self.get_or_create(event)
event_hook.subscribe(handler)
return self
|
Attaches the handler to the specified event.
@param event: event to attach the handler to. Any object can be passed
as event, but string is preferable. If qcore.EnumBase
instance is passed, its name is used as event key.
@param handler: event handler.
@return: self, so calls like this can be chained together.
|
entailment
|
def off(self, event, handler):
"""Detaches the handler from the specified event.
@param event: event to detach the handler to. Any object can be passed
as event, but string is preferable. If qcore.EnumBase
instance is passed, its name is used as event key.
@param handler: event handler.
@return: self, so calls like this can be chained together.
"""
event_hook = self.get_or_create(event)
event_hook.unsubscribe(handler)
return self
|
Detaches the handler from the specified event.
@param event: event to detach the handler to. Any object can be passed
as event, but string is preferable. If qcore.EnumBase
instance is passed, its name is used as event key.
@param handler: event handler.
@return: self, so calls like this can be chained together.
|
entailment
|
def trigger(self, event, *args):
"""Triggers the specified event by invoking EventHook.trigger under the hood.
@param event: event to trigger. Any object can be passed
as event, but string is preferable. If qcore.EnumBase
instance is passed, its name is used as event key.
@param args: event arguments.
@return: self, so calls like this can be chained together.
"""
event_hook = self.get_or_create(event)
event_hook.trigger(*args)
return self
|
Triggers the specified event by invoking EventHook.trigger under the hood.
@param event: event to trigger. Any object can be passed
as event, but string is preferable. If qcore.EnumBase
instance is passed, its name is used as event key.
@param args: event arguments.
@return: self, so calls like this can be chained together.
|
entailment
|
def safe_trigger(self, event, *args):
"""Safely triggers the specified event by invoking
EventHook.safe_trigger under the hood.
@param event: event to trigger. Any object can be passed
as event, but string is preferable. If qcore.EnumBase
instance is passed, its name is used as event key.
@param args: event arguments.
@return: self, so calls like this can be chained together.
"""
event_hook = self.get_or_create(event)
event_hook.safe_trigger(*args)
return self
|
Safely triggers the specified event by invoking
EventHook.safe_trigger under the hood.
@param event: event to trigger. Any object can be passed
as event, but string is preferable. If qcore.EnumBase
instance is passed, its name is used as event key.
@param args: event arguments.
@return: self, so calls like this can be chained together.
|
entailment
|
def get_or_create(self, event):
"""Gets or creates a new event hook for the specified event (key).
This method treats qcore.EnumBase-typed event keys specially:
enum_member.name is used as key instead of enum instance
in case such a key is passed.
Note that on/off/trigger/safe_trigger methods rely on this method,
so you can pass enum members there as well.
"""
if isinstance(event, EnumBase):
event = event.short_name
return self.__dict__.setdefault(event, EventHook())
|
Gets or creates a new event hook for the specified event (key).
This method treats qcore.EnumBase-typed event keys specially:
enum_member.name is used as key instead of enum instance
in case such a key is passed.
Note that on/off/trigger/safe_trigger methods rely on this method,
so you can pass enum members there as well.
|
entailment
|
def cancel_expired_invitations(invitations=None):
"""
Invitation lifetime must be specified in Waldur Core settings with parameter
"INVITATION_LIFETIME". If invitation creation time is less than expiration time, the invitation will set as expired.
"""
expiration_date = timezone.now() - settings.WALDUR_CORE['INVITATION_LIFETIME']
if not invitations:
invitations = models.Invitation.objects.filter(state=models.Invitation.State.PENDING)
invitations = invitations.filter(created__lte=expiration_date)
invitations.update(state=models.Invitation.State.EXPIRED)
|
Invitation lifetime must be specified in Waldur Core settings with parameter
"INVITATION_LIFETIME". If invitation creation time is less than expiration time, the invitation will set as expired.
|
entailment
|
def get_pseudo_abi_for_input(s, timeout=None, proxies=None):
"""
Lookup sighash from 4bytes.directory, create a pseudo api and try to decode it with the parsed abi.
May return multiple results as sighashes may collide.
:param s: bytes input
:return: pseudo abi for method
"""
sighash = Utils.bytes_to_str(s[:4])
for pseudo_abi in FourByteDirectory.get_pseudo_abi_for_sighash(sighash, timeout=timeout, proxies=proxies):
types = [ti["type"] for ti in pseudo_abi['inputs']]
try:
# test decoding
_ = decode_abi(types, s[4:])
yield pseudo_abi
except eth_abi.exceptions.DecodingError as e:
continue
|
Lookup sighash from 4bytes.directory, create a pseudo api and try to decode it with the parsed abi.
May return multiple results as sighashes may collide.
:param s: bytes input
:return: pseudo abi for method
|
entailment
|
def _prepare_abi(self, jsonabi):
"""
Prepare the contract json abi for sighash lookups and fast access
:param jsonabi: contracts abi in json format
:return:
"""
self.signatures = {}
for element_description in jsonabi:
abi_e = AbiMethod(element_description)
if abi_e["type"] == "constructor":
self.signatures[b"__constructor__"] = abi_e
elif abi_e["type"] == "fallback":
abi_e.setdefault("inputs", [])
self.signatures[b"__fallback__"] = abi_e
elif abi_e["type"] == "function":
# function and signature present
# todo: we could generate the sighash ourselves? requires keccak256
if abi_e.get("signature"):
self.signatures[Utils.str_to_bytes(abi_e["signature"])] = abi_e
elif abi_e["type"] == "event":
self.signatures[b"__event__"] = abi_e
else:
raise Exception("Invalid abi type: %s - %s - %s" % (abi_e.get("type"),
element_description, abi_e))
|
Prepare the contract json abi for sighash lookups and fast access
:param jsonabi: contracts abi in json format
:return:
|
entailment
|
def describe_constructor(self, s):
"""
Describe the input bytesequence (constructor arguments) s based on the loaded contract
abi definition
:param s: bytes constructor arguments
:return: AbiMethod instance
"""
method = self.signatures.get(b"__constructor__")
if not method:
# constructor not available
m = AbiMethod({"type": "constructor", "name": "", "inputs": [], "outputs": []})
return m
types_def = method["inputs"]
types = [t["type"] for t in types_def]
names = [t["name"] for t in types_def]
if not len(s):
values = len(types) * ["<nA>"]
else:
values = decode_abi(types, s)
# (type, name, data)
method.inputs = [{"type": t, "name": n, "data": v} for t, n, v in list(
zip(types, names, values))]
return method
|
Describe the input bytesequence (constructor arguments) s based on the loaded contract
abi definition
:param s: bytes constructor arguments
:return: AbiMethod instance
|
entailment
|
def describe_input(self, s):
"""
Describe the input bytesequence s based on the loaded contract abi definition
:param s: bytes input
:return: AbiMethod instance
"""
signatures = self.signatures.items()
for sighash, method in signatures:
if sighash is None or sighash.startswith(b"__"):
continue # skip constructor
if s.startswith(sighash):
s = s[len(sighash):]
types_def = self.signatures.get(sighash)["inputs"]
types = [t["type"] for t in types_def]
names = [t["name"] for t in types_def]
if not len(s):
values = len(types) * ["<nA>"]
else:
values = decode_abi(types, s)
# (type, name, data)
method.inputs = [{"type": t, "name": n, "data": v} for t, n, v in list(
zip(types, names, values))]
return method
else:
method = AbiMethod({"type": "fallback",
"name": "__fallback__",
"inputs": [], "outputs": []})
types_def = self.signatures.get(b"__fallback__", {"inputs": []})["inputs"]
types = [t["type"] for t in types_def]
names = [t["name"] for t in types_def]
values = decode_abi(types, s)
# (type, name, data)
method.inputs = [{"type": t, "name": n, "data": v} for t, n, v in list(
zip(types, names, values))]
return method
|
Describe the input bytesequence s based on the loaded contract abi definition
:param s: bytes input
:return: AbiMethod instance
|
entailment
|
def from_input_lookup(s):
"""
Return a new AbiMethod object from an input stream
:param s: binary input
:return: new AbiMethod object matching the provided input stream
"""
for pseudo_abi in FourByteDirectory.get_pseudo_abi_for_input(s):
method = AbiMethod(pseudo_abi)
types_def = pseudo_abi["inputs"]
types = [t["type"] for t in types_def]
names = [t["name"] for t in types_def]
values = decode_abi(types, s[4:])
# (type, name, data)
method.inputs = [{"type": t, "name": n, "data": v} for t, n, v in list(
zip(types, names, values))]
return method
|
Return a new AbiMethod object from an input stream
:param s: binary input
:return: new AbiMethod object matching the provided input stream
|
entailment
|
def assert_is(expected, actual, message=None, extra=None):
"""Raises an AssertionError if expected is not actual."""
assert expected is actual, _assert_fail_message(
message, expected, actual, "is not", extra
)
|
Raises an AssertionError if expected is not actual.
|
entailment
|
def assert_is_not(expected, actual, message=None, extra=None):
"""Raises an AssertionError if expected is actual."""
assert expected is not actual, _assert_fail_message(
message, expected, actual, "is", extra
)
|
Raises an AssertionError if expected is actual.
|
entailment
|
def assert_is_instance(value, types, message=None, extra=None):
"""Raises an AssertionError if value is not an instance of type(s)."""
assert isinstance(value, types), _assert_fail_message(
message, value, types, "is not an instance of", extra
)
|
Raises an AssertionError if value is not an instance of type(s).
|
entailment
|
def assert_eq(expected, actual, message=None, tolerance=None, extra=None):
"""Raises an AssertionError if expected != actual.
If tolerance is specified, raises an AssertionError if either
- expected or actual isn't a number, or
- the difference between expected and actual is larger than the tolerance.
"""
if tolerance is None:
assert expected == actual, _assert_fail_message(
message, expected, actual, "!=", extra
)
else:
assert isinstance(tolerance, _number_types), (
"tolerance parameter to assert_eq must be a number: %r" % tolerance
)
assert isinstance(expected, _number_types) and isinstance(
actual, _number_types
), (
"parameters must be numbers when tolerance is specified: %r, %r"
% (expected, actual)
)
diff = abs(expected - actual)
assert diff <= tolerance, _assert_fail_message(
message, expected, actual, "is more than %r away from" % tolerance, extra
)
|
Raises an AssertionError if expected != actual.
If tolerance is specified, raises an AssertionError if either
- expected or actual isn't a number, or
- the difference between expected and actual is larger than the tolerance.
|
entailment
|
def assert_dict_eq(expected, actual, number_tolerance=None, dict_path=[]):
"""Asserts that two dictionaries are equal, producing a custom message if they are not."""
assert_is_instance(expected, dict)
assert_is_instance(actual, dict)
expected_keys = set(expected.keys())
actual_keys = set(actual.keys())
assert expected_keys <= actual_keys, "Actual dict at %s is missing keys: %r" % (
_dict_path_string(dict_path),
expected_keys - actual_keys,
)
assert actual_keys <= expected_keys, "Actual dict at %s has extra keys: %r" % (
_dict_path_string(dict_path),
actual_keys - expected_keys,
)
for k in expected_keys:
key_path = dict_path + [k]
assert_is_instance(
actual[k],
type(expected[k]),
extra="Types don't match for %s" % _dict_path_string(key_path),
)
assert_is_instance(
expected[k],
type(actual[k]),
extra="Types don't match for %s" % _dict_path_string(key_path),
)
if isinstance(actual[k], dict):
assert_dict_eq(
expected[k],
actual[k],
number_tolerance=number_tolerance,
dict_path=key_path,
)
elif isinstance(actual[k], _number_types):
assert_eq(
expected[k],
actual[k],
extra="Value doesn't match for %s" % _dict_path_string(key_path),
tolerance=number_tolerance,
)
else:
assert_eq(
expected[k],
actual[k],
extra="Value doesn't match for %s" % _dict_path_string(key_path),
)
|
Asserts that two dictionaries are equal, producing a custom message if they are not.
|
entailment
|
def assert_gt(left, right, message=None, extra=None):
"""Raises an AssertionError if left_hand <= right_hand."""
assert left > right, _assert_fail_message(message, left, right, "<=", extra)
|
Raises an AssertionError if left_hand <= right_hand.
|
entailment
|
def assert_ge(left, right, message=None, extra=None):
"""Raises an AssertionError if left_hand < right_hand."""
assert left >= right, _assert_fail_message(message, left, right, "<", extra)
|
Raises an AssertionError if left_hand < right_hand.
|
entailment
|
def assert_lt(left, right, message=None, extra=None):
"""Raises an AssertionError if left_hand >= right_hand."""
assert left < right, _assert_fail_message(message, left, right, ">=", extra)
|
Raises an AssertionError if left_hand >= right_hand.
|
entailment
|
def assert_le(left, right, message=None, extra=None):
"""Raises an AssertionError if left_hand > right_hand."""
assert left <= right, _assert_fail_message(message, left, right, ">", extra)
|
Raises an AssertionError if left_hand > right_hand.
|
entailment
|
def assert_in(obj, seq, message=None, extra=None):
"""Raises an AssertionError if obj is not in seq."""
assert obj in seq, _assert_fail_message(message, obj, seq, "is not in", extra)
|
Raises an AssertionError if obj is not in seq.
|
entailment
|
def assert_not_in(obj, seq, message=None, extra=None):
"""Raises an AssertionError if obj is in iter."""
# for very long strings, provide a truncated error
if isinstance(seq, six.string_types) and obj in seq and len(seq) > 200:
index = seq.find(obj)
start_index = index - 50
if start_index > 0:
truncated = "(truncated) ..."
else:
truncated = ""
start_index = 0
end_index = index + len(obj) + 50
truncated += seq[start_index:end_index]
if end_index < len(seq):
truncated += "... (truncated)"
assert False, _assert_fail_message(message, obj, truncated, "is in", extra)
assert obj not in seq, _assert_fail_message(message, obj, seq, "is in", extra)
|
Raises an AssertionError if obj is in iter.
|
entailment
|
def assert_in_with_tolerance(obj, seq, tolerance, message=None, extra=None):
"""Raises an AssertionError if obj is not in seq using assert_eq cmp."""
for i in seq:
try:
assert_eq(obj, i, tolerance=tolerance, message=message, extra=extra)
return
except AssertionError:
pass
assert False, _assert_fail_message(message, obj, seq, "is not in", extra)
|
Raises an AssertionError if obj is not in seq using assert_eq cmp.
|
entailment
|
def assert_is_substring(substring, subject, message=None, extra=None):
"""Raises an AssertionError if substring is not a substring of subject."""
assert (
(subject is not None)
and (substring is not None)
and (subject.find(substring) != -1)
), _assert_fail_message(message, substring, subject, "is not in", extra)
|
Raises an AssertionError if substring is not a substring of subject.
|
entailment
|
def assert_is_not_substring(substring, subject, message=None, extra=None):
"""Raises an AssertionError if substring is a substring of subject."""
assert (
(subject is not None)
and (substring is not None)
and (subject.find(substring) == -1)
), _assert_fail_message(message, substring, subject, "is in", extra)
|
Raises an AssertionError if substring is a substring of subject.
|
entailment
|
def assert_unordered_list_eq(expected, actual, message=None):
"""Raises an AssertionError if the objects contained
in expected are not equal to the objects contained
in actual without regard to their order.
This takes quadratic time in the umber of elements in actual; don't use it for very long lists.
"""
missing_in_actual = []
missing_in_expected = list(actual)
for x in expected:
try:
missing_in_expected.remove(x)
except ValueError:
missing_in_actual.append(x)
if missing_in_actual or missing_in_expected:
if not message:
message = (
"%r not equal to %r; missing items: %r in expected, %r in actual."
% (expected, actual, missing_in_expected, missing_in_actual)
)
assert False, message
|
Raises an AssertionError if the objects contained
in expected are not equal to the objects contained
in actual without regard to their order.
This takes quadratic time in the umber of elements in actual; don't use it for very long lists.
|
entailment
|
def _execute_if_not_empty(func):
""" Execute function only if one of input parameters is not empty """
def wrapper(*args, **kwargs):
if any(args[1:]) or any(kwargs.items()):
return func(*args, **kwargs)
return wrapper
|
Execute function only if one of input parameters is not empty
|
entailment
|
def prepare_search_body(self, should_terms=None, must_terms=None, must_not_terms=None, search_text='', start=None, end=None):
"""
Prepare body for elasticsearch query
Search parameters
^^^^^^^^^^^^^^^^^
These parameters are dictionaries and have format: <term>: [<value 1>, <value 2> ...]
should_terms: it resembles logical OR
must_terms: it resembles logical AND
must_not_terms: it resembles logical NOT
search_text : string
Text for FTS(full text search)
start, end : datetime
Filter for event creation time
"""
self.body = self.SearchBody()
self.body.set_should_terms(should_terms)
self.body.set_must_terms(must_terms)
self.body.set_must_not_terms(must_not_terms)
self.body.set_search_text(search_text)
self.body.set_timestamp_filter(start, end)
self.body.prepare()
|
Prepare body for elasticsearch query
Search parameters
^^^^^^^^^^^^^^^^^
These parameters are dictionaries and have format: <term>: [<value 1>, <value 2> ...]
should_terms: it resembles logical OR
must_terms: it resembles logical AND
must_not_terms: it resembles logical NOT
search_text : string
Text for FTS(full text search)
start, end : datetime
Filter for event creation time
|
entailment
|
def execute(cls, instance, async=True, countdown=2, is_heavy_task=False, **kwargs):
""" Execute high level-operation """
cls.pre_apply(instance, async=async, **kwargs)
result = cls.apply_signature(instance, async=async, countdown=countdown,
is_heavy_task=is_heavy_task, **kwargs)
cls.post_apply(instance, async=async, **kwargs)
return result
|
Execute high level-operation
|
entailment
|
def apply_signature(cls, instance, async=True, countdown=None, is_heavy_task=False, **kwargs):
""" Serialize input data and apply signature """
serialized_instance = utils.serialize_instance(instance)
signature = cls.get_task_signature(instance, serialized_instance, **kwargs)
link = cls.get_success_signature(instance, serialized_instance, **kwargs)
link_error = cls.get_failure_signature(instance, serialized_instance, **kwargs)
if async:
return signature.apply_async(link=link, link_error=link_error, countdown=countdown,
queue=is_heavy_task and 'heavy' or None)
else:
result = signature.apply()
callback = link if not result.failed() else link_error
if callback is not None:
cls._apply_callback(callback, result)
return result.get()
|
Serialize input data and apply signature
|
entailment
|
def _apply_callback(cls, callback, result):
""" Synchronously execute callback """
if not callback.immutable:
callback.args = (result.id, ) + callback.args
callback.apply()
|
Synchronously execute callback
|
entailment
|
def get_entity_description(entity):
"""
Returns description in format:
* entity human readable name
* docstring
"""
try:
entity_name = entity.__name__.strip('_')
except AttributeError:
# entity is a class instance
entity_name = entity.__class__.__name__
label = '* %s' % formatting.camelcase_to_spaces(entity_name)
if entity.__doc__ is not None:
entity_docstring = formatting.dedent(smart_text(entity.__doc__)).replace('\n', '\n\t')
return '%s\n * %s' % (label, entity_docstring)
return label
|
Returns description in format:
* entity human readable name
* docstring
|
entailment
|
def get_validators_description(view):
"""
Returns validators description in format:
### Validators:
* validator1 name
* validator1 docstring
* validator2 name
* validator2 docstring
"""
action = getattr(view, 'action', None)
if action is None:
return ''
description = ''
validators = getattr(view, action + '_validators', [])
for validator in validators:
validator_description = get_entity_description(validator)
description += '\n' + validator_description if description else validator_description
return '### Validators:\n' + description if description else ''
|
Returns validators description in format:
### Validators:
* validator1 name
* validator1 docstring
* validator2 name
* validator2 docstring
|
entailment
|
def get_actions_permission_description(view, method):
"""
Returns actions permissions description in format:
* permission1 name
* permission1 docstring
* permission2 name
* permission2 docstring
"""
action = getattr(view, 'action', None)
if action is None:
return ''
if hasattr(view, action + '_permissions'):
permission_types = (action,)
elif method in SAFE_METHODS:
permission_types = ('safe_methods', '%s_extra' % action)
else:
permission_types = ('unsafe_methods', '%s_extra' % action)
description = ''
for permission_type in permission_types:
action_perms = getattr(view, permission_type + '_permissions', [])
for permission in action_perms:
action_perm_description = get_entity_description(permission)
description += '\n' + action_perm_description if description else action_perm_description
return description
|
Returns actions permissions description in format:
* permission1 name
* permission1 docstring
* permission2 name
* permission2 docstring
|
entailment
|
def get_permissions_description(view, method):
"""
Returns permissions description in format:
### Permissions:
* permission1 name
* permission1 docstring
* permission2 name
* permission2 docstring
"""
if not hasattr(view, 'permission_classes'):
return ''
description = ''
for permission_class in view.permission_classes:
if permission_class == core_permissions.ActionsPermission:
actions_perm_description = get_actions_permission_description(view, method)
if actions_perm_description:
description += '\n' + actions_perm_description if description else actions_perm_description
continue
perm_description = get_entity_description(permission_class)
description += '\n' + perm_description if description else perm_description
return '### Permissions:\n' + description if description else ''
|
Returns permissions description in format:
### Permissions:
* permission1 name
* permission1 docstring
* permission2 name
* permission2 docstring
|
entailment
|
def get_validation_description(view, method):
"""
Returns validation description in format:
### Validation:
validate method docstring
* field1 name
* field1 validation docstring
* field2 name
* field2 validation docstring
"""
if method not in ('PUT', 'PATCH', 'POST') or not hasattr(view, 'get_serializer'):
return ''
serializer = view.get_serializer()
description = ''
if hasattr(serializer, 'validate') and serializer.validate.__doc__ is not None:
description += formatting.dedent(smart_text(serializer.validate.__doc__))
for field in serializer.fields.values():
if not hasattr(serializer, 'validate_' + field.field_name):
continue
field_validation = getattr(serializer, 'validate_' + field.field_name)
if field_validation.__doc__ is not None:
docstring = formatting.dedent(smart_text(field_validation.__doc__)).replace('\n', '\n\t')
field_description = '* %s\n * %s' % (field.field_name, docstring)
description += '\n' + field_description if description else field_description
return '### Validation:\n' + description if description else ''
|
Returns validation description in format:
### Validation:
validate method docstring
* field1 name
* field1 validation docstring
* field2 name
* field2 validation docstring
|
entailment
|
def get_field_type(field):
"""
Returns field type/possible values.
"""
if isinstance(field, core_filters.MappedMultipleChoiceFilter):
return ' | '.join(['"%s"' % f for f in sorted(field.mapped_to_model)])
if isinstance(field, OrderingFilter) or isinstance(field, ChoiceFilter):
return ' | '.join(['"%s"' % f[0] for f in field.extra['choices']])
if isinstance(field, ChoiceField):
return ' | '.join(['"%s"' % f for f in sorted(field.choices)])
if isinstance(field, HyperlinkedRelatedField):
if field.view_name.endswith('detail'):
return 'link to %s' % reverse(field.view_name,
kwargs={'%s' % field.lookup_field: "'%s'" % field.lookup_field})
return reverse(field.view_name)
if isinstance(field, structure_filters.ServiceTypeFilter):
return ' | '.join(['"%s"' % f for f in SupportedServices.get_filter_mapping().keys()])
if isinstance(field, ResourceTypeFilter):
return ' | '.join(['"%s"' % f for f in SupportedServices.get_resource_models().keys()])
if isinstance(field, core_serializers.GenericRelatedField):
links = []
for model in field.related_models:
detail_view_name = core_utils.get_detail_view_name(model)
for f in field.lookup_fields:
try:
link = reverse(detail_view_name, kwargs={'%s' % f: "'%s'" % f})
except NoReverseMatch:
pass
else:
links.append(link)
break
path = ', '.join(links)
if path:
return 'link to any: %s' % path
if isinstance(field, core_filters.ContentTypeFilter):
return "string in form 'app_label'.'model_name'"
if isinstance(field, ModelMultipleChoiceFilter):
return get_field_type(field.field)
if isinstance(field, ListSerializer):
return 'list of [%s]' % get_field_type(field.child)
if isinstance(field, ManyRelatedField):
return 'list of [%s]' % get_field_type(field.child_relation)
if isinstance(field, ModelField):
return get_field_type(field.model_field)
name = field.__class__.__name__
for w in ('Filter', 'Field', 'Serializer'):
name = name.replace(w, '')
return FIELDS.get(name, name)
|
Returns field type/possible values.
|
entailment
|
def is_disabled_action(view):
"""
Checks whether Link action is disabled.
"""
if not isinstance(view, core_views.ActionsViewSet):
return False
action = getattr(view, 'action', None)
return action in view.disabled_actions if action is not None else False
|
Checks whether Link action is disabled.
|
entailment
|
def get_allowed_methods(self, callback):
"""
Return a list of the valid HTTP methods for this endpoint.
"""
if hasattr(callback, 'actions'):
return [method.upper() for method in callback.actions.keys() if method != 'head']
return [
method for method in
callback.cls().allowed_methods if method not in ('OPTIONS', 'HEAD')
]
|
Return a list of the valid HTTP methods for this endpoint.
|
entailment
|
def create_view(self, callback, method, request=None):
"""
Given a callback, return an actual view instance.
"""
view = super(WaldurSchemaGenerator, self).create_view(callback, method, request)
if is_disabled_action(view):
view.exclude_from_schema = True
return view
|
Given a callback, return an actual view instance.
|
entailment
|
def get_description(self, path, method, view):
"""
Determine a link description.
This will be based on the method docstring if one exists,
or else the class docstring.
"""
description = super(WaldurSchemaGenerator, self).get_description(path, method, view)
permissions_description = get_permissions_description(view, method)
if permissions_description:
description += '\n\n' + permissions_description if description else permissions_description
if isinstance(view, core_views.ActionsViewSet):
validators_description = get_validators_description(view)
if validators_description:
description += '\n\n' + validators_description if description else validators_description
validation_description = get_validation_description(view, method)
if validation_description:
description += '\n\n' + validation_description if description else validation_description
return description
|
Determine a link description.
This will be based on the method docstring if one exists,
or else the class docstring.
|
entailment
|
def get_serializer_fields(self, path, method, view):
"""
Return a list of `coreapi.Field` instances corresponding to any
request body input, as determined by the serializer class.
"""
if method not in ('PUT', 'PATCH', 'POST'):
return []
if not hasattr(view, 'get_serializer'):
return []
serializer = view.get_serializer()
if not isinstance(serializer, Serializer):
return []
fields = []
for field in serializer.fields.values():
if field.read_only or isinstance(field, HiddenField):
continue
required = field.required and method != 'PATCH'
description = force_text(field.help_text) if field.help_text else ''
field_type = get_field_type(field)
description += '; ' + field_type if description else field_type
field = coreapi.Field(
name=field.field_name,
location='form',
required=required,
description=description,
schema=schemas.field_to_schema(field),
)
fields.append(field)
return fields
|
Return a list of `coreapi.Field` instances corresponding to any
request body input, as determined by the serializer class.
|
entailment
|
def delete_error_message(sender, instance, name, source, target, **kwargs):
""" Delete error message if instance state changed from erred """
if source != StateMixin.States.ERRED:
return
instance.error_message = ''
instance.save(update_fields=['error_message'])
|
Delete error message if instance state changed from erred
|
entailment
|
def find_version(*file_paths):
"""
read __init__.py
"""
file_path = os.path.join(*file_paths)
with open(file_path, 'r') as version_file:
line = version_file.readline()
while line:
if line.startswith('__version__'):
version_match = re.search(
r"^__version__ = ['\"]([^'\"]*)['\"]",
line,
re.M
)
if version_match:
return version_match.group(1)
line = version_file.readline()
raise RuntimeError('Unable to find version string.')
|
read __init__.py
|
entailment
|
def trace(enter=False, exit=True):
"""
This decorator prints entry and exit message when
the decorated method is called, as well as call
arguments, result and thrown exception (if any).
:param enter: indicates whether entry message should be printed.
:param exit: indicates whether exit message should be printed.
:return: decorated function.
"""
def decorate(fn):
@inspection.wraps(fn)
def new_fn(*args, **kwargs):
name = fn.__module__ + "." + fn.__name__
if enter:
print(
"%s(args = %s, kwargs = %s) <-" % (name, repr(args), repr(kwargs))
)
try:
result = fn(*args, **kwargs)
if exit:
print(
"%s(args = %s, kwargs = %s) -> %s"
% (name, repr(args), repr(kwargs), repr(result))
)
return result
except Exception as e:
if exit:
print(
"%s(args = %s, kwargs = %s) -> thrown %s"
% (name, repr(args), repr(kwargs), str(e))
)
raise
return new_fn
return decorate
|
This decorator prints entry and exit message when
the decorated method is called, as well as call
arguments, result and thrown exception (if any).
:param enter: indicates whether entry message should be printed.
:param exit: indicates whether exit message should be printed.
:return: decorated function.
|
entailment
|
def _make_value(self, value):
"""Instantiates an enum with an arbitrary value."""
member = self.__new__(self, value)
member.__init__(value)
return member
|
Instantiates an enum with an arbitrary value.
|
entailment
|
def create(cls, name, members):
"""Creates a new enum type based on this one (cls) and adds newly
passed members to the newly created subclass of cls.
This method helps to create enums having the same member values as
values of other enum(s).
:param name: name of the newly created type
:param members: 1) a dict or 2) a list of (name, value) tuples
and/or EnumBase instances describing new members
:return: newly created enum type.
"""
NewEnum = type(name, (cls,), {})
if isinstance(members, dict):
members = members.items()
for member in members:
if isinstance(member, tuple):
name, value = member
setattr(NewEnum, name, value)
elif isinstance(member, EnumBase):
setattr(NewEnum, member.short_name, member.value)
else:
assert False, (
"members must be either a dict, "
+ "a list of (name, value) tuples, "
+ "or a list of EnumBase instances."
)
NewEnum.process()
# needed for pickling to work (hopefully); taken from the namedtuple implementation in the
# standard library
try:
NewEnum.__module__ = sys._getframe(1).f_globals.get("__name__", "__main__")
except (AttributeError, ValueError):
pass
return NewEnum
|
Creates a new enum type based on this one (cls) and adds newly
passed members to the newly created subclass of cls.
This method helps to create enums having the same member values as
values of other enum(s).
:param name: name of the newly created type
:param members: 1) a dict or 2) a list of (name, value) tuples
and/or EnumBase instances describing new members
:return: newly created enum type.
|
entailment
|
def parse(cls, value, default=_no_default):
"""Parses an enum member name or value into an enum member.
Accepts the following types:
- Members of this enum class. These are returned directly.
- Integers. If there is an enum member with the integer as a value, that member is returned.
- Strings. If there is an enum member with the string as its name, that member is returned.
For integers and strings that don't correspond to an enum member, default is returned; if
no default is given the function raises KeyError instead.
Examples:
>>> class Color(Enum):
... red = 1
... blue = 2
>>> Color.parse(Color.red)
Color.red
>>> Color.parse(1)
Color.red
>>> Color.parse('blue')
Color.blue
"""
if isinstance(value, cls):
return value
elif isinstance(value, six.integer_types) and not isinstance(value, EnumBase):
e = cls._value_to_member.get(value, _no_default)
else:
e = cls._name_to_member.get(value, _no_default)
if e is _no_default or not e.is_valid():
if default is _no_default:
raise _create_invalid_value_error(cls, value)
return default
return e
|
Parses an enum member name or value into an enum member.
Accepts the following types:
- Members of this enum class. These are returned directly.
- Integers. If there is an enum member with the integer as a value, that member is returned.
- Strings. If there is an enum member with the string as its name, that member is returned.
For integers and strings that don't correspond to an enum member, default is returned; if
no default is given the function raises KeyError instead.
Examples:
>>> class Color(Enum):
... red = 1
... blue = 2
>>> Color.parse(Color.red)
Color.red
>>> Color.parse(1)
Color.red
>>> Color.parse('blue')
Color.blue
|
entailment
|
def parse(cls, value, default=_no_default):
"""Parses a flag integer or string into a Flags instance.
Accepts the following types:
- Members of this enum class. These are returned directly.
- Integers. These are converted directly into a Flags instance with the given name.
- Strings. The function accepts a comma-delimited list of flag names, corresponding to
members of the enum. These are all ORed together.
Examples:
>>> class Car(Flags):
... is_big = 1
... has_wheels = 2
>>> Car.parse(1)
Car.is_big
>>> Car.parse(3)
Car.parse('has_wheels,is_big')
>>> Car.parse('is_big,has_wheels')
Car.parse('has_wheels,is_big')
"""
if isinstance(value, cls):
return value
elif isinstance(value, int):
e = cls._make_value(value)
else:
if not value:
e = cls._make_value(0)
else:
r = 0
for k in value.split(","):
v = cls._name_to_member.get(k, _no_default)
if v is _no_default:
if default is _no_default:
raise _create_invalid_value_error(cls, value)
else:
return default
r |= v.value
e = cls._make_value(r)
if not e.is_valid():
if default is _no_default:
raise _create_invalid_value_error(cls, value)
return default
return e
|
Parses a flag integer or string into a Flags instance.
Accepts the following types:
- Members of this enum class. These are returned directly.
- Integers. These are converted directly into a Flags instance with the given name.
- Strings. The function accepts a comma-delimited list of flag names, corresponding to
members of the enum. These are all ORed together.
Examples:
>>> class Car(Flags):
... is_big = 1
... has_wheels = 2
>>> Car.parse(1)
Car.is_big
>>> Car.parse(3)
Car.parse('has_wheels,is_big')
>>> Car.parse('is_big,has_wheels')
Car.parse('has_wheels,is_big')
|
entailment
|
def list(self, request, *args, **kwargs):
"""
To get a list of price estimates, run **GET** against */api/price-estimates/* as authenticated user.
You can filter price estimates by scope type, scope URL, customer UUID.
`scope_type` is generic type of object for which price estimate is calculated.
Currently there are following types: customer, project, service, serviceprojectlink, resource.
`date` parameter accepts list of dates. `start` and `end` parameters together specify date range.
Each valid date should in format YYYY.MM
You can specify GET parameter ?depth to show price estimate children. For example with ?depth=2 customer
price estimate will shows its children - project and service and grandchildren - serviceprojectlink.
"""
return super(PriceEstimateViewSet, self).list(request, *args, **kwargs)
|
To get a list of price estimates, run **GET** against */api/price-estimates/* as authenticated user.
You can filter price estimates by scope type, scope URL, customer UUID.
`scope_type` is generic type of object for which price estimate is calculated.
Currently there are following types: customer, project, service, serviceprojectlink, resource.
`date` parameter accepts list of dates. `start` and `end` parameters together specify date range.
Each valid date should in format YYYY.MM
You can specify GET parameter ?depth to show price estimate children. For example with ?depth=2 customer
price estimate will shows its children - project and service and grandchildren - serviceprojectlink.
|
entailment
|
def list(self, request, *args, **kwargs):
"""
To get a list of price list items, run **GET** against */api/price-list-items/* as an authenticated user.
"""
return super(PriceListItemViewSet, self).list(request, *args, **kwargs)
|
To get a list of price list items, run **GET** against */api/price-list-items/* as an authenticated user.
|
entailment
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.