text stringlengths 81 112k |
|---|
Get field that are tracked in object history versions.
def get_version_fields(self):
""" Get field that are tracked in object history versions. """
options = reversion._get_options(self)
return options.fields or [f.name for f in self._meta.fields if f not in options.exclude] |
Define should new version be created for object or no.
Reasons to provide custom check instead of default `ignore_revision_duplicates`:
- no need to compare all revisions - it is OK if right object version exists in any revision;
- need to compare object attributes (not serialized... |
Get all unique instance ancestors
def get_ancestors(self):
""" Get all unique instance ancestors """
ancestors = list(self.get_parents())
ancestor_unique_attributes = set([(a.__class__, a.id) for a in ancestors])
ancestors_with_parents = [a for a in ancestors if isinstance(a, Descendant... |
Check if the connection has succeed
Returns:
Returns True if connection has succeed.
False otherwise.
def has_succeed(self):
""" Check if the connection has succeed
Returns:
Returns True if connection has succeed.
False o... |
Check if the response succeed or not.
In case of error, this method also print messages and set
an array of errors in the response object.
Returns:
Returns True if the response has succeed, False otherwise
def handle_response_for_connection(self, should_post=False)... |
Called when a response is received
def _did_receive_response(self, response):
""" Called when a response is received """
try:
data = response.json()
except:
data = None
self._response = NURESTResponse(status_code=response.status_code, headers=response.headers, d... |
Called when a resquest has timeout
def _did_timeout(self):
""" Called when a resquest has timeout """
bambou_logger.debug('Bambou %s on %s has timeout (timeout=%ss)..' % (self._request.method, self._request.url, self.timeout))
self._has_timeouted = True
if self.async:
self... |
Make a synchronous request
def _make_request(self, session=None):
""" Make a synchronous request """
if session is None:
session = NURESTSession.get_current_session()
self._has_timeouted = False
# Add specific headers
controller = session.login_controller
... |
Encapsulate requests call
def __make_request(self, requests_session, method, url, params, data, headers, certificate):
""" Encapsulate requests call
"""
verify = False
timeout = self.timeout
try: # TODO : Remove this ugly try/except after fixing Java issue: http://mvjira.mv.us... |
Make an HTTP request with a specific method
def start(self):
""" Make an HTTP request with a specific method """
# TODO : Use Timeout here and _ignore_request_idle
from .nurest_session import NURESTSession
session = NURESTSession.get_current_session()
if self.async:
... |
Reset the connection
def reset(self):
""" Reset the connection
"""
self._request = None
self._response = None
self._transaction_id = uuid.uuid4().hex |
Take configuration from previous month, it it exists.
Set last_update_time equals to the beginning of the month.
def create(self, price_estimate):
""" Take configuration from previous month, it it exists.
Set last_update_time equals to the beginning of the month.
"""
kwa... |
When static declaration is used, event type choices are fetched too early -
even before all apps are initialized. As a result, some event types are missing.
When dynamic declaration is used, all valid event types are available as choices.
def get_fields(self):
"""
When static declaratio... |
Use PriceEstimateSerializer to serialize estimate children
def build_nested_field(self, field_name, relation_info, nested_depth):
""" Use PriceEstimateSerializer to serialize estimate children """
if field_name != 'children':
return super(PriceEstimateSerializer, self).build_nested_field(fi... |
Prepares the exception for re-raising with reraise method.
This method attaches type and traceback info to the error object
so that reraise can properly reraise it using this info.
def prepare_for_reraise(error, exc_info=None):
"""Prepares the exception for re-raising with reraise method.
This method... |
Re-raises the error that was processed by prepare_for_reraise earlier.
def reraise(error):
"""Re-raises the error that was processed by prepare_for_reraise earlier."""
if hasattr(error, "_type_"):
six.reraise(type(error), error, error._traceback)
raise error |
Creates a registrator that, being called with a function as the only
argument, wraps a function with ``pyws.functions.NativeFunctionAdapter``
and registers it to the server. Arguments are exactly the same as for
``pyws.functions.NativeFunctionAdapter`` except that you can pass
an additional keyword argu... |
Represents a singular REST name
def rest_name(cls):
""" Represents a singular REST name
"""
if cls.__name__ == "NURESTRootObject" or cls.__name__ == "NURESTObject":
return "Not Implemented"
if cls.__rest_name__ is None:
raise NotImplementedError('%s has no defin... |
Represents the resource name
def resource_name(cls):
""" Represents the resource name
"""
if cls.__name__ == "NURESTRootObject" or cls.__name__ == "NURESTObject":
return "Not Implemented"
if cls.__resource_name__ is None:
raise NotImplementedError('%s has no def... |
Compute the arguments
Try to import attributes from data.
Otherwise compute kwargs arguments.
Args:
data: a dict()
kwargs: a list of arguments
def _compute_args(self, data=dict(), **kwargs):
""" Compute the arguments
Try to impo... |
Gets the list of all possible children ReST names.
Returns:
list: list containing all possible rest names as string
Example:
>>> entity = NUEntity()
>>> entity.children_rest_names
["foo", "bar"]
def children_rest_names(self):
... |
Get resource complete url
def get_resource_url(self):
""" Get resource complete url """
name = self.__class__.resource_name
url = self.__class__.rest_base_url()
if self.id is not None:
return "%s/%s/%s" % (url, name, self.id)
return "%s/%s" % (url, name) |
Validate the current object attributes.
Check all attributes and store errors
Returns:
Returns True if all attibutes of the object
respect contraints. Returns False otherwise and
store error in errors dict.
def validate(self):
""" Valida... |
Expose local_name as remote_name
An exposed attribute `local_name` will be sent within the HTTP request as
a `remote_name`
def expose_attribute(self, local_name, attribute_type, remote_name=None, display_name=None, is_required=False, is_readonly=False, max_length=None, min_length=None, is_iden... |
Check if the current user owns the object
def is_owned_by_current_user(self):
""" Check if the current user owns the object """
from bambou.nurest_root_object import NURESTRootObject
root_object = NURESTRootObject.get_default_root_object()
return self._owner == root_object.id |
Return parent that matches a rest name
def parent_for_matching_rest_name(self, rest_names):
""" Return parent that matches a rest name """
parent = self
while parent:
if parent.rest_name in rest_names:
return parent
parent = parent.parent_object
... |
Get genealogic types
Returns:
Returns a list of all parent types
def genealogic_types(self):
""" Get genealogic types
Returns:
Returns a list of all parent types
"""
types = []
parent = self
while parent:
ty... |
Get all genealogic ids
Returns:
A list of all parent ids
def genealogic_ids(self):
""" Get all genealogic ids
Returns:
A list of all parent ids
"""
ids = []
parent = self
while parent:
ids.append(parent.id... |
Return creation date with a given format. Default is '%b %Y %d %H:%I:%S'
def get_formated_creation_date(self, format='%b %Y %d %H:%I:%S'):
""" Return creation date with a given format. Default is '%b %Y %d %H:%I:%S' """
if not self._creation_date:
return None
date = datetime.datet... |
Add a child
def add_child(self, child):
""" Add a child """
rest_name = child.rest_name
children = self.fetcher_for_rest_name(rest_name)
if children is None:
raise InternalConsitencyError('Could not find fetcher with name %s while adding %s in parent %s' % (rest_name, chil... |
Remove a child
def remove_child(self, child):
""" Remove a child """
rest_name = child.rest_name
children = self.fetcher_for_rest_name(rest_name)
target_child = None
for local_child in children:
if local_child.id == child.id:
target_child = local_c... |
Update child
def update_child(self, child):
""" Update child """
rest_name = child.rest_name
children = self.fetcher_for_rest_name(rest_name)
index = None
for local_child in children:
if local_child.id == child.id:
index = children.index(local_chil... |
Converts the current object into a Dictionary using all exposed ReST attributes.
Returns:
dict: the dictionary containing all the exposed ReST attributes and their values.
Example::
>>> print entity.to_dict()
{"name": "my entity", "description": ... |
Sets all the exposed ReST attribues from the given dictionary
Args:
dictionary (dict): dictionnary containing the raw object attributes and their values.
Example:
>>> info = {"name": "my group", "private": False}
>>> group = NUGroup()
... |
Delete object and call given callback in case of call.
Args:
response_choice (int): Automatically send a response choice when confirmation is needed
async (bool): Boolean to make an asynchronous call. Default is False
callback (function): Callback method that... |
Update object and call given callback in case of async call
Args:
async (bool): Boolean to make an asynchronous call. Default is False
callback (function): Callback method that will be triggered in case of asynchronous call
Example:
>>> entity.na... |
Sends a request, calls the local callback, then the remote callback in case of async call
Args:
request: The request to send
local_callback: local method that will be triggered in case of async call
remote_callback: remote moethd that will be triggered in cas... |
Low level child management. Send given HTTP method with given nurest_object to given ressource of current object
Args:
nurest_object: the NURESTObject object to manage
method: the HTTP method to use (GET, POST, PUT, DELETE)
callback: the callback to call at t... |
Receive a response from the connection
def _did_receive_response(self, connection):
""" Receive a response from the connection """
if connection.has_timeouted:
bambou_logger.info("NURESTConnection has timeout.")
return
has_callbacks = connection.has_callbacks()
... |
Callback called after fetching the object
def _did_retrieve(self, connection):
""" Callback called after fetching the object """
response = connection.response
try:
self.from_dict(response.data[0])
except:
pass
return self._did_perform_standard_operati... |
Performs standard opertions
def _did_perform_standard_operation(self, connection):
""" Performs standard opertions """
if connection.async:
callback = connection.callbacks['remote']
if connection.user_info and 'nurest_object' in connection.user_info:
callback(c... |
Add given nurest_object to the current object
For example, to add a child into a parent, you can call
parent.create_child(nurest_object=child)
Args:
nurest_object (bambou.NURESTObject): the NURESTObject object to add
response_choice (int): Automatica... |
Instantiate an nurest_object from a template object
Args:
nurest_object: the NURESTObject object to add
from_template: the NURESTObject template object
callback: callback containing the object and the connection
Returns:
Returns t... |
Callback called after adding a new child nurest_object
def _did_create_child(self, connection):
""" Callback called after adding a new child nurest_object """
response = connection.response
try:
connection.user_info['nurest_object'].from_dict(response.data[0])
except Except... |
Reference a list of objects into the current resource
Args:
objects (list): list of NURESTObject to link
nurest_object_type (type): Type of the object to link
callback (function): Callback method that should be fired at the end
Returns:
... |
Compare objects REST attributes
def rest_equals(self, rest_object):
""" Compare objects REST attributes
"""
if not self.equals(rest_object):
return False
return self.to_dict() == rest_object.to_dict() |
Compare with another object
def equals(self, rest_object):
""" Compare with another object """
if self._is_dirty:
return False
if rest_object is None:
return False
if not isinstance(rest_object, NURESTObject):
raise TypeError('The object is not a N... |
Correct IP address is expected as first element of HTTP_X_FORWARDED_FOR or REMOTE_ADDR
def get_ip_address(request):
"""
Correct IP address is expected as first element of HTTP_X_FORWARDED_FOR or REMOTE_ADDR
"""
if 'HTTP_X_FORWARDED_FOR' in request.META:
return request.META['HTTP_X_FORWARDED_FOR... |
It is expected that valid row for each month contains at least one
price estimate for customer, service setting, service,
service project link, project and resource.
Otherwise all price estimates in the row should be deleted.
def get_estimates_without_scope_in_month(self, customer):
"""... |
Setter for is_identifier
def is_identifier(self, is_identifier):
""" Setter for is_identifier """
if is_identifier:
self.is_editable = False
self._is_identifier = is_identifier |
Setter for is_identifier
def is_password(self, is_password):
""" Setter for is_identifier """
if is_password:
self.is_forgetable = True
self._is_password = is_password |
Setter for is_identifier
def choices(self, choices):
""" Setter for is_identifier """
if choices is not None and len(choices) > 0:
self.has_choices = True
self._choices = choices |
Get a default value of the attribute_type
def get_default_value(self):
""" Get a default value of the attribute_type """
if self.choices:
return self.choices[0]
value = self.attribute_type()
if self.attribute_type is time:
value = int(value)
elif self... |
Get the minimum value
def get_min_value(self):
""" Get the minimum value """
value = self.get_default_value()
if self.attribute_type is str:
min_value = value[:self.min_length - 1]
elif self.attribute_type is int:
min_value = self.min_length - 1
else:... |
Get the maximum value
def get_max_value(self):
""" Get the maximum value """
value = self.get_default_value()
if self.attribute_type is str:
max_value = value.ljust(self.max_length + 1, 'a')
elif self.attribute_type is int:
max_value = self.max_length + 1
... |
Return a basic root view.
def get_api_root_view(self, api_urls=None):
"""
Return a basic root view.
"""
api_root_dict = OrderedDict()
list_name = self.routes[0].name
for prefix, viewset, basename in self.registry:
api_root_dict[prefix] = list_name.format(base... |
Attempt to automatically determine base name using `get_url_name`.
def get_default_base_name(self, viewset):
"""
Attempt to automatically determine base name using `get_url_name`.
"""
queryset = getattr(viewset, 'queryset', None)
if queryset is not None:
get_url_nam... |
Modify nc_user_count quota usage on structure role grant or revoke
def change_customer_nc_users_quota(sender, structure, user, role, signal, **kwargs):
""" Modify nc_user_count quota usage on structure role grant or revoke """
assert signal in (signals.structure_role_granted, signals.structure_role_revoked), \... |
Delete not shared service settings without services
def delete_service_settings_on_service_delete(sender, instance, **kwargs):
""" Delete not shared service settings without services """
service = instance
try:
service_settings = service.settings
except ServiceSettings.DoesNotExist:
# I... |
If VM that contains service settings were deleted - all settings
resources could be safely deleted from NC.
def delete_service_settings_on_scope_delete(sender, instance, **kwargs):
""" If VM that contains service settings were deleted - all settings
resources could be safely deleted from NC.
""... |
Set API URL endpoint
Args:
url: the url of the API endpoint
def url(self, url):
""" Set API URL endpoint
Args:
url: the url of the API endpoint
"""
if url and url.endswith('/'):
url = url[:-1]
self._url = url |
Return authenication string to place in Authorization Header
If API Token is set, it'll be used. Otherwise, the clear
text password will be sent. Users of NURESTLoginController are responsible to
clean the password property.
Returns:
Returns the XREST Au... |
Reset controller
It removes all information about previous session
def reset(self):
""" Reset controller
It removes all information about previous session
"""
self._is_impersonating = False
self._impersonation = None
self.user = None
self.pass... |
Impersonate a user in a enterprise
Args:
user: the name of the user to impersonate
enterprise: the name of the enterprise where to use impersonation
def impersonate(self, user, enterprise):
""" Impersonate a user in a enterprise
Args:
us... |
Verify if the controller corresponds
to the current one.
def equals(self, controller):
""" Verify if the controller corresponds
to the current one.
"""
if controller is None:
return False
return self.user == controller.user and self.enterprise == co... |
WSGI adapter. It creates a simple WSGI application, that can be used with
any WSGI server. The arguments are:
#. ``server`` is a pyws server object,
#. ``root_url`` is an URL to which the server will be bound.
An application created by the function transforms WSGI environment into a
pyws request o... |
构建dialect
def compiler_dialect(paramstyle='named'):
"""
构建dialect
"""
dialect = SQLiteDialect_pysqlite(
json_serializer=json.dumps,
json_deserializer=json_deserializer,
paramstyle=paramstyle
)
dialect.default_paramstyle = paramstyle
dialect.statement_compiler = AComp... |
A coroutine for Engine creation.
Returns Engine instance with embedded connection pool.
The pool has *minsize* opened connections to sqlite3.
def create_engine(
database,
minsize=1,
maxsize=10,
loop=None,
dialect=_dialect,
paramstyle=None,
**kwargs):
... |
Revert back connection to pool.
def release(self, conn):
"""Revert back connection to pool."""
if conn.in_transaction:
raise InvalidRequestError(
"Cannot release a connection with "
"not finished transaction"
)
raw = conn.connection
... |
Return how much consumables are used by resource with current configuration.
Output example:
{
<ConsumableItem instance>: <usage>,
<ConsumableItem instance>: <usage>,
...
}
def get_configuration(cls, resource):
""" Return how ... |
Close this ResultProxy.
Closes the underlying DBAPI cursor corresponding to the execution.
Note that any data cached within this ResultProxy is still available.
For some types of results, this may include buffered rows.
If this ResultProxy was generated from an implicit execution,
... |
Obtain the version number
def get_version():
"""Obtain the version number"""
import imp
import os
mod = imp.load_source(
'version', os.path.join('skdata', '__init__.py')
)
return mod.__version__ |
Accept invitation for current user.
To replace user's email with email from invitation - add parameter
'replace_email' to request POST body.
def accept(self, request, uuid=None):
""" Accept invitation for current user.
To replace user's email with email from invitation - a... |
Run different actions on price estimate scope deletion.
If scope is a customer - delete all customer estimates and their children.
If scope is a deleted resource - redefine consumption details, recalculate
ancestors estimates and update estimate details.
... |
Recalculate consumption details and save resource details
def _resource_deletion(resource):
""" Recalculate consumption details and save resource details """
if resource.__class__ not in CostTrackingRegister.registered_resources:
return
new_configuration = {}
price_estimate = models.PriceEstima... |
Update resource consumption details and price estimate if its configuration has changed.
Create estimates for previous months if resource was created not in current month.
def resource_update(sender, instance, created=False, **kwargs):
""" Update resource consumption details and price estimate if its confi... |
Update resource consumption details and price estimate if its configuration has changed
def resource_quota_update(sender, instance, **kwargs):
""" Update resource consumption details and price estimate if its configuration has changed """
quota = instance
resource = quota.scope
try:
new_configu... |
Create consumption details and price estimates for past months.
Usually we need to update historical values on resource import.
def _create_historical_estimates(resource, configuration):
""" Create consumption details and price estimates for past months.
Usually we need to update historical value... |
Decide if the Ipython command line is running code.
def IPYTHON_MAIN():
"""Decide if the Ipython command line is running code."""
import pkg_resources
runner_frame = inspect.getouterframes(inspect.currentframe())[-2]
return (
getattr(runner_frame, "function", None)
== pkg_resources.loa... |
Register a model class according to its remote name
Args:
model: the model to register
def register_model(cls, model):
"""
Register a model class according to its remote name
Args:
model: the model to register
"""
rest_name ... |
Get the first model corresponding to a rest_name
Args:
rest_name: the rest name
def get_first_model_with_rest_name(cls, rest_name):
""" Get the first model corresponding to a rest_name
Args:
rest_name: the rest name
"""
models = cls.get... |
Get the first model corresponding to a resource_name
Args:
resource_name: the resource name
def get_first_model_with_resource_name(cls, resource_name):
""" Get the first model corresponding to a resource_name
Args:
resource_name: the resource name
... |
执行任务
def run(self):
"""
执行任务
"""
while not self._stoped:
self._tx_event.wait()
self._tx_event.clear()
try:
func = self._tx_queue.get_nowait()
if isinstance(func, str):
self._stoped = True
... |
:param dset_id:
:return:
def build_layout(self, dset_id: str):
"""
:param dset_id:
:return:
"""
all_fields = list(self.get_data(dset_id=dset_id).keys())
try:
field_reference = self.skd[dset_id].attrs('target')
except:
field_refere... |
:param dset_id:
:return:
def display(self, dset_id: str):
"""
:param dset_id:
:return:
"""
# update result
self.skd[dset_id].compute()
# build layout
self.build_layout(dset_id=dset_id)
# display widgets
display(self._('dashboard')... |
Try to finder the spec and if it cannot be found, use the underscore starring syntax
to identify potential matches.
def find_spec(self, fullname, target=None):
"""Try to finder the spec and if it cannot be found, use the underscore starring syntax
to identify potential matches.
"""
... |
Get resource complete url
def get_resource_url(self):
""" Get resource complete url """
name = self.__class__.resource_name
url = self.__class__.rest_base_url()
return "%s/%s" % (url, name) |
Updates the user and perform the callback method
def save(self, async=False, callback=None, encrypted=True):
""" Updates the user and perform the callback method """
if self._new_password and encrypted:
self.password = Sha1.encrypt(self._new_password)
controller = NURESTSession.ge... |
Launched when save has been successfully executed
def _did_save(self, connection):
""" Launched when save has been successfully executed """
self._new_password = None
controller = NURESTSession.get_current_session().login_controller
controller.password = None
controller.api_ke... |
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, c... |
This function retrieves the ISO 639 and inverted names datasets as tsv files and returns them as lists.
def _fabtabular():
"""
This function retrieves the ISO 639 and inverted names datasets as tsv files and returns them as lists.
"""
import csv
import sys
from pkg_resources import resource_fil... |
Function for generating retired languages. Returns a dict('code', (datetime, [language, ...], 'description')).
def retired(self):
"""
Function for generating retired languages. Returns a dict('code', (datetime, [language, ...], 'description')).
"""
def gen():
import csv
... |
Simple getter function for languages. Takes 1 keyword/value and returns 1 language object.
def get(self, **kwargs):
"""
Simple getter function for languages. Takes 1 keyword/value and returns 1 language object.
"""
if not len(kwargs) == 1:
raise AttributeError('Only one keyw... |
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/cu... |
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",
... |
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: applicatio... |
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 ... |
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 r... |
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",
... |
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
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.