sentence1
stringlengths 52
3.87M
| sentence2
stringlengths 1
47.2k
| label
stringclasses 1
value |
|---|---|---|
def create(self, request, *args, **kwargs):
"""
Run **POST** request against */api/price-list-items/* to create new price list item.
Customer owner and staff can create price items.
Example of request:
.. code-block:: http
POST /api/price-list-items/ HTTP/1.1
Content-Type: application/json
Accept: application/json
Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4
Host: example.com
{
"units": "per month",
"value": 100,
"service": "http://example.com/api/oracle/d4060812ca5d4de390e0d7a5062d99f6/",
"default_price_list_item": "http://example.com/api/default-price-list-items/349d11e28f634f48866089e41c6f71f1/"
}
"""
return super(PriceListItemViewSet, self).create(request, *args, **kwargs)
|
Run **POST** request against */api/price-list-items/* to create new price list item.
Customer owner and staff can create price items.
Example of request:
.. code-block:: http
POST /api/price-list-items/ HTTP/1.1
Content-Type: application/json
Accept: application/json
Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4
Host: example.com
{
"units": "per month",
"value": 100,
"service": "http://example.com/api/oracle/d4060812ca5d4de390e0d7a5062d99f6/",
"default_price_list_item": "http://example.com/api/default-price-list-items/349d11e28f634f48866089e41c6f71f1/"
}
|
entailment
|
def update(self, request, *args, **kwargs):
"""
Run **PATCH** request against */api/price-list-items/<uuid>/* to update price list item.
Only item_type, key value and units can be updated.
Only customer owner and staff can update price items.
"""
return super(PriceListItemViewSet, self).update(request, *args, **kwargs)
|
Run **PATCH** request against */api/price-list-items/<uuid>/* to update price list item.
Only item_type, key value and units can be updated.
Only customer owner and staff can update price items.
|
entailment
|
def destroy(self, request, *args, **kwargs):
"""
Run **DELETE** request against */api/price-list-items/<uuid>/* to delete price list item.
Only customer owner and staff can delete price items.
"""
return super(PriceListItemViewSet, self).destroy(request, *args, **kwargs)
|
Run **DELETE** request against */api/price-list-items/<uuid>/* to delete price list item.
Only customer owner and staff can delete price items.
|
entailment
|
def list(self, request, *args, **kwargs):
"""
To get a list of default price list items, run **GET** against */api/default-price-list-items/*
as authenticated user.
Price lists can be filtered by:
- ?key=<string>
- ?item_type=<string> has to be from list of available item_types
(available options: 'flavor', 'storage', 'license-os', 'license-application', 'network', 'support')
- ?resource_type=<string> resource type, for example: 'OpenStack.Instance, 'Oracle.Database')
"""
return super(DefaultPriceListItemViewSet, self).list(request, *args, **kwargs)
|
To get a list of default price list items, run **GET** against */api/default-price-list-items/*
as authenticated user.
Price lists can be filtered by:
- ?key=<string>
- ?item_type=<string> has to be from list of available item_types
(available options: 'flavor', 'storage', 'license-os', 'license-application', 'network', 'support')
- ?resource_type=<string> resource type, for example: 'OpenStack.Instance, 'Oracle.Database')
|
entailment
|
def list(self, request, *args, **kwargs):
"""
To get a list of price list items, run **GET** against */api/merged-price-list-items/*
as authenticated user.
If service is not specified default price list items are displayed.
Otherwise service specific price list items are displayed.
In this case rendered object contains {"is_manually_input": true}
In order to specify service pass query parameters:
- service_type (Azure, OpenStack etc.)
- service_uuid
Example URL: http://example.com/api/merged-price-list-items/?service_type=Azure&service_uuid=cb658b491f3644a092dd223e894319be
"""
return super(MergedPriceListItemViewSet, self).list(request, *args, **kwargs)
|
To get a list of price list items, run **GET** against */api/merged-price-list-items/*
as authenticated user.
If service is not specified default price list items are displayed.
Otherwise service specific price list items are displayed.
In this case rendered object contains {"is_manually_input": true}
In order to specify service pass query parameters:
- service_type (Azure, OpenStack etc.)
- service_uuid
Example URL: http://example.com/api/merged-price-list-items/?service_type=Azure&service_uuid=cb658b491f3644a092dd223e894319be
|
entailment
|
def Remote(path=None, loader=Notebook, **globals):
"""A remote notebook finder. Place a `*` into a url
to generalize the finder. It returns a context manager
"""
class Remote(RemoteMixin, loader):
...
return Remote(path=path, **globals)
|
A remote notebook finder. Place a `*` into a url
to generalize the finder. It returns a context manager
|
entailment
|
def get_permission_checks(self, request, view):
"""
Get permission checks that will be executed for current action.
"""
if view.action is None:
return []
# if permissions are defined for view directly - use them.
if hasattr(view, view.action + '_permissions'):
return getattr(view, view.action + '_permissions')
# otherwise return view-level permissions + extra view permissions
extra_permissions = getattr(view, view.action + 'extra_permissions', [])
if request.method in SAFE_METHODS:
return getattr(view, 'safe_methods_permissions', []) + extra_permissions
else:
return getattr(view, 'unsafe_methods_permissions', []) + extra_permissions
|
Get permission checks that will be executed for current action.
|
entailment
|
def add_function(self, function):
"""
Registers the function to the server's default fixed function manager.
"""
#noinspection PyTypeChecker
if not len(self.settings.FUNCTION_MANAGERS):
raise ConfigurationError(
'Where have the default function manager gone?!')
self.settings.FUNCTION_MANAGERS[0].add_function(function)
|
Registers the function to the server's default fixed function manager.
|
entailment
|
def format_raw_field(key):
"""
When ElasticSearch analyzes string, it breaks it into parts.
In order make query for not-analyzed exact string values, we should use subfield instead.
The index template for Elasticsearch 5.0 has been changed.
The subfield for string multi-fields has changed from .raw to .keyword
Thus workaround for backward compatibility during migration is required.
See also: https://github.com/elastic/logstash/blob/v5.4.1/docs/static/breaking-changes.asciidoc
"""
subfield = django_settings.WALDUR_CORE.get('ELASTICSEARCH', {}).get('raw_subfield', 'keyword')
return '%s.%s' % (camel_case_to_underscore(key), subfield)
|
When ElasticSearch analyzes string, it breaks it into parts.
In order make query for not-analyzed exact string values, we should use subfield instead.
The index template for Elasticsearch 5.0 has been changed.
The subfield for string multi-fields has changed from .raw to .keyword
Thus workaround for backward compatibility during migration is required.
See also: https://github.com/elastic/logstash/blob/v5.4.1/docs/static/breaking-changes.asciidoc
|
entailment
|
def decorate(decorator_cls, *args, **kwargs):
"""Creates a decorator function that applies the decorator_cls that was passed in."""
global _wrappers
wrapper_cls = _wrappers.get(decorator_cls, None)
if wrapper_cls is None:
class PythonWrapper(decorator_cls):
pass
wrapper_cls = PythonWrapper
wrapper_cls.__name__ = decorator_cls.__name__ + "PythonWrapper"
_wrappers[decorator_cls] = wrapper_cls
def decorator(fn):
wrapped = wrapper_cls(fn, *args, **kwargs)
_update_wrapper(wrapped, fn)
return wrapped
return decorator
|
Creates a decorator function that applies the decorator_cls that was passed in.
|
entailment
|
def deprecated(replacement_description):
"""States that method is deprecated.
:param replacement_description: Describes what must be used instead.
:return: the original method with modified docstring.
"""
def decorate(fn_or_class):
if isinstance(fn_or_class, type):
pass # Can't change __doc__ of type objects
else:
try:
fn_or_class.__doc__ = "This API point is obsolete. %s\n\n%s" % (
replacement_description,
fn_or_class.__doc__,
)
except AttributeError:
pass # For Cython method descriptors, etc.
return fn_or_class
return decorate
|
States that method is deprecated.
:param replacement_description: Describes what must be used instead.
:return: the original method with modified docstring.
|
entailment
|
def convert_result(converter):
"""Decorator that can convert the result of a function call."""
def decorate(fn):
@inspection.wraps(fn)
def new_fn(*args, **kwargs):
return converter(fn(*args, **kwargs))
return new_fn
return decorate
|
Decorator that can convert the result of a function call.
|
entailment
|
def retry(exception_cls, max_tries=10, sleep=0.05):
"""Decorator for retrying a function if it throws an exception.
:param exception_cls: an exception type or a parenthesized tuple of exception types
:param max_tries: maximum number of times this function can be executed. Must be at least 1.
:param sleep: number of seconds to sleep between function retries
"""
assert max_tries > 0
def with_max_retries_call(delegate):
for i in xrange(0, max_tries):
try:
return delegate()
except exception_cls:
if i + 1 == max_tries:
raise
time.sleep(sleep)
def outer(fn):
is_generator = inspect.isgeneratorfunction(fn)
@functools.wraps(fn)
def retry_fun(*args, **kwargs):
return with_max_retries_call(lambda: fn(*args, **kwargs))
@functools.wraps(fn)
def retry_generator_fun(*args, **kwargs):
def get_first_item():
results = fn(*args, **kwargs)
for first_result in results:
return [first_result], results
return [], results
cache, generator = with_max_retries_call(get_first_item)
for item in cache:
yield item
for item in generator:
yield item
if not is_generator:
# so that qcore.inspection.get_original_fn can retrieve the original function
retry_fun.fn = fn
# Necessary for pickling of Cythonized functions to work. Cython's __reduce__
# method always returns the original name of the function.
retry_fun.__reduce__ = lambda: fn.__name__
return retry_fun
else:
retry_generator_fun.fn = fn
retry_generator_fun.__reduce__ = lambda: fn.__name__
return retry_generator_fun
return outer
|
Decorator for retrying a function if it throws an exception.
:param exception_cls: an exception type or a parenthesized tuple of exception types
:param max_tries: maximum number of times this function can be executed. Must be at least 1.
:param sleep: number of seconds to sleep between function retries
|
entailment
|
def decorator_of_context_manager(ctxt):
"""Converts a context manager into a decorator.
This decorator will run the decorated function in the context of the
manager.
:param ctxt: Context to run the function in.
:return: Wrapper around the original function.
"""
def decorator_fn(*outer_args, **outer_kwargs):
def decorator(fn):
@functools.wraps(fn)
def wrapper(*args, **kwargs):
with ctxt(*outer_args, **outer_kwargs):
return fn(*args, **kwargs)
return wrapper
return decorator
if getattr(ctxt, "__doc__", None) is None:
msg = "Decorator that runs the inner function in the context of %s"
decorator_fn.__doc__ = msg % ctxt
else:
decorator_fn.__doc__ = ctxt.__doc__
return decorator_fn
|
Converts a context manager into a decorator.
This decorator will run the decorated function in the context of the
manager.
:param ctxt: Context to run the function in.
:return: Wrapper around the original function.
|
entailment
|
def get_error(self, error):
"""
A helper function, gets standard information from the error.
"""
error_type = type(error)
if error.error_type == ET_CLIENT:
error_type_name = 'Client'
else:
error_type_name = 'Server'
return {
'type': error_type_name,
'name': error_type.__name__,
'prefix': getattr(error_type, '__module__', ''),
'message': unicode(error),
'params': error.args,
}
|
A helper function, gets standard information from the error.
|
entailment
|
def validate_quota_change(self, quota_deltas, raise_exception=False):
"""
Get error messages about object and his ancestor quotas that will be exceeded if quota_delta will be added.
raise_exception - if True QuotaExceededException will be raised if validation fails
quota_deltas - dictionary of quotas deltas, example:
{
'ram': 1024,
'storage': 2048,
...
}
Example of output:
['ram quota limit: 1024, requires: 2048(instance#1)', ...]
"""
errors = []
for name, delta in six.iteritems(quota_deltas):
quota = self.quotas.get(name=name)
if quota.is_exceeded(delta):
errors.append('%s quota limit: %s, requires %s (%s)\n' % (
quota.name, quota.limit, quota.usage + delta, quota.scope))
if not raise_exception:
return errors
else:
if errors:
raise exceptions.QuotaExceededException(_('One or more quotas were exceeded: %s') % ';'.join(errors))
|
Get error messages about object and his ancestor quotas that will be exceeded if quota_delta will be added.
raise_exception - if True QuotaExceededException will be raised if validation fails
quota_deltas - dictionary of quotas deltas, example:
{
'ram': 1024,
'storage': 2048,
...
}
Example of output:
['ram quota limit: 1024, requires: 2048(instance#1)', ...]
|
entailment
|
def get_sum_of_quotas_as_dict(cls, scopes, quota_names=None, fields=['usage', 'limit']):
"""
Return dictionary with sum of all scopes' quotas.
Dictionary format:
{
'quota_name1': 'sum of limits for quotas with such quota_name1',
'quota_name1_usage': 'sum of usages for quotas with such quota_name1',
...
}
All `scopes` have to be instances of the same model.
`fields` keyword argument defines sum of which fields of quotas will present in result.
"""
if not scopes:
return {}
if quota_names is None:
quota_names = cls.get_quotas_names()
scope_models = set([scope._meta.model for scope in scopes])
if len(scope_models) > 1:
raise exceptions.QuotaError(_('All scopes have to be instances of the same model.'))
filter_kwargs = {
'content_type': ct_models.ContentType.objects.get_for_model(scopes[0]),
'object_id__in': [scope.id for scope in scopes],
'name__in': quota_names
}
result = {}
if 'usage' in fields:
items = Quota.objects.filter(**filter_kwargs)\
.values('name').annotate(usage=Sum('usage'))
for item in items:
result[item['name'] + '_usage'] = item['usage']
if 'limit' in fields:
unlimited_quotas = Quota.objects.filter(limit=-1, **filter_kwargs)
unlimited_quotas = list(unlimited_quotas.values_list('name', flat=True))
for quota_name in unlimited_quotas:
result[quota_name] = -1
items = Quota.objects\
.filter(**filter_kwargs)\
.exclude(name__in=unlimited_quotas)\
.values('name')\
.annotate(limit=Sum('limit'))
for item in items:
result[item['name']] = item['limit']
return result
|
Return dictionary with sum of all scopes' quotas.
Dictionary format:
{
'quota_name1': 'sum of limits for quotas with such quota_name1',
'quota_name1_usage': 'sum of usages for quotas with such quota_name1',
...
}
All `scopes` have to be instances of the same model.
`fields` keyword argument defines sum of which fields of quotas will present in result.
|
entailment
|
def list(self, request, *args, **kwargs):
"""
To get a list of events - run **GET** against */api/events/* as authenticated user. Note that a user can
only see events connected to objects she is allowed to see.
Sorting is supported in ascending and descending order by specifying a field to an **?o=** parameter. By default
events are sorted by @timestamp in descending order.
Run POST against */api/events/* to create an event. Only users with staff privileges can create events.
New event will be emitted with `custom_notification` event type.
Request should contain following fields:
- level: the level of current event. Following levels are supported: debug, info, warning, error
- message: string representation of event message
- scope: optional URL, which points to the loggable instance
Request example:
.. code-block:: javascript
POST /api/events/
Accept: application/json
Content-Type: application/json
Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4
Host: example.com
{
"level": "info",
"message": "message#1",
"scope": "http://example.com/api/customers/9cd869201e1b4158a285427fcd790c1c/"
}
"""
self.queryset = self.filter_queryset(self.get_queryset())
page = self.paginate_queryset(self.queryset)
if page is not None:
return self.get_paginated_response(page)
return response.Response(self.queryset)
|
To get a list of events - run **GET** against */api/events/* as authenticated user. Note that a user can
only see events connected to objects she is allowed to see.
Sorting is supported in ascending and descending order by specifying a field to an **?o=** parameter. By default
events are sorted by @timestamp in descending order.
Run POST against */api/events/* to create an event. Only users with staff privileges can create events.
New event will be emitted with `custom_notification` event type.
Request should contain following fields:
- level: the level of current event. Following levels are supported: debug, info, warning, error
- message: string representation of event message
- scope: optional URL, which points to the loggable instance
Request example:
.. code-block:: javascript
POST /api/events/
Accept: application/json
Content-Type: application/json
Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4
Host: example.com
{
"level": "info",
"message": "message#1",
"scope": "http://example.com/api/customers/9cd869201e1b4158a285427fcd790c1c/"
}
|
entailment
|
def count(self, request, *args, **kwargs):
"""
To get a count of events - run **GET** against */api/events/count/* as authenticated user.
Endpoint support same filters as events list.
Response example:
.. code-block:: javascript
{"count": 12321}
"""
self.queryset = self.filter_queryset(self.get_queryset())
return response.Response({'count': self.queryset.count()}, status=status.HTTP_200_OK)
|
To get a count of events - run **GET** against */api/events/count/* as authenticated user.
Endpoint support same filters as events list.
Response example:
.. code-block:: javascript
{"count": 12321}
|
entailment
|
def count_history(self, request, *args, **kwargs):
"""
To get a historical data of events amount - run **GET** against */api/events/count/history/*.
Endpoint support same filters as events list.
More about historical data - read at section *Historical data*.
Response example:
.. code-block:: javascript
[
{
"point": 141111111111,
"object": {
"count": 558
}
}
]
"""
queryset = self.filter_queryset(self.get_queryset())
mapped = {
'start': request.query_params.get('start'),
'end': request.query_params.get('end'),
'points_count': request.query_params.get('points_count'),
'point_list': request.query_params.getlist('point'),
}
serializer = core_serializers.HistorySerializer(data={k: v for k, v in mapped.items() if v})
serializer.is_valid(raise_exception=True)
timestamp_ranges = [{'end': point_date} for point_date in serializer.get_filter_data()]
aggregated_count = queryset.aggregated_count(timestamp_ranges)
return response.Response(
[{'point': int(ac['end']), 'object': {'count': ac['count']}} for ac in aggregated_count],
status=status.HTTP_200_OK)
|
To get a historical data of events amount - run **GET** against */api/events/count/history/*.
Endpoint support same filters as events list.
More about historical data - read at section *Historical data*.
Response example:
.. code-block:: javascript
[
{
"point": 141111111111,
"object": {
"count": 558
}
}
]
|
entailment
|
def scope_types(self, request, *args, **kwargs):
""" Returns a list of scope types acceptable by events filter. """
return response.Response(utils.get_scope_types_mapping().keys())
|
Returns a list of scope types acceptable by events filter.
|
entailment
|
def list(self, request, *args, **kwargs):
"""
To get a list of alerts, run **GET** against */api/alerts/* as authenticated user.
Alert severity field can take one of this values: "Error", "Warning", "Info", "Debug".
Field scope will contain link to object that cause alert.
Context - dictionary that contains information about all related to alert objects.
Alerts can be filtered by:
- ?severity=<severity> (can be list)
- ?alert_type=<alert_type> (can be list)
- ?scope=<url> concrete alert scope
- ?scope_type=<string> name of scope type (Ex.: instance, service_project_link, project...)
DEPRECATED use ?content_type instead
- ?created_from=<timestamp>
- ?created_to=<timestamp>
- ?closed_from=<timestamp>
- ?closed_to=<timestamp>
- ?from=<timestamp> - filter alerts that was active from given date
- ?to=<timestamp> - filter alerts that was active to given date
- ?opened - if this argument is in GET request endpoint will return only alerts that are not closed
- ?closed - if this argument is in GET request endpoint will return only alerts that are closed
- ?aggregate=aggregate_model_name (default: 'customer'. Have to be from list: 'customer', project')
- ?uuid=uuid_of_aggregate_model_object (not required. If this parameter will be defined - result ill contain only
object with given uuid)
- ?acknowledged=True|False - show only acknowledged (non-acknowledged) alerts
- ?content_type=<string> name of scope content type in format <app_name>.<scope_type>
(Ex.: structure.project, openstack.instance...)
- ?exclude_features=<feature> (can be list) - exclude alert from output if it's type corresponds o one of given features
Alerts can be ordered by:
-?o=severity - order by severity
-?o=created - order by creation time
.. code-block:: http
GET /api/alerts/
Accept: application/json
Content-Type: application/json
Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4
Host: example.com
[
{
"url": "http://example.com/api/alerts/e80e48a4e58b48ff9a1320a0aa0d68ab/",
"uuid": "e80e48a4e58b48ff9a1320a0aa0d68ab",
"alert_type": "first_alert",
"message": "message#1",
"severity": "Debug",
"scope": "http://example.com/api/instances/9d1d7e03b0d14fd0b42b5f649dfa3de5/",
"created": "2015-05-29T14:24:27.342Z",
"closed": null,
"context": {
'customer_abbreviation': 'customer_abbreviation',
'customer_contact_details': 'customer details',
'customer_name': 'Customer name',
'customer_uuid': '53c6e86406e349faa7924f4c865b15ab',
'quota_limit': '131072.0',
'quota_name': 'ram',
'quota_usage': '131071',
'quota_uuid': 'f6ae2f7ca86f4e2f9bb64de1015a2815',
'scope_name': 'project X',
'scope_uuid': '0238d71ee1934bd2839d4e71e5f9b91a'
}
"acknowledged": true,
}
]
"""
return super(AlertViewSet, self).list(request, *args, **kwargs)
|
To get a list of alerts, run **GET** against */api/alerts/* as authenticated user.
Alert severity field can take one of this values: "Error", "Warning", "Info", "Debug".
Field scope will contain link to object that cause alert.
Context - dictionary that contains information about all related to alert objects.
Alerts can be filtered by:
- ?severity=<severity> (can be list)
- ?alert_type=<alert_type> (can be list)
- ?scope=<url> concrete alert scope
- ?scope_type=<string> name of scope type (Ex.: instance, service_project_link, project...)
DEPRECATED use ?content_type instead
- ?created_from=<timestamp>
- ?created_to=<timestamp>
- ?closed_from=<timestamp>
- ?closed_to=<timestamp>
- ?from=<timestamp> - filter alerts that was active from given date
- ?to=<timestamp> - filter alerts that was active to given date
- ?opened - if this argument is in GET request endpoint will return only alerts that are not closed
- ?closed - if this argument is in GET request endpoint will return only alerts that are closed
- ?aggregate=aggregate_model_name (default: 'customer'. Have to be from list: 'customer', project')
- ?uuid=uuid_of_aggregate_model_object (not required. If this parameter will be defined - result ill contain only
object with given uuid)
- ?acknowledged=True|False - show only acknowledged (non-acknowledged) alerts
- ?content_type=<string> name of scope content type in format <app_name>.<scope_type>
(Ex.: structure.project, openstack.instance...)
- ?exclude_features=<feature> (can be list) - exclude alert from output if it's type corresponds o one of given features
Alerts can be ordered by:
-?o=severity - order by severity
-?o=created - order by creation time
.. code-block:: http
GET /api/alerts/
Accept: application/json
Content-Type: application/json
Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4
Host: example.com
[
{
"url": "http://example.com/api/alerts/e80e48a4e58b48ff9a1320a0aa0d68ab/",
"uuid": "e80e48a4e58b48ff9a1320a0aa0d68ab",
"alert_type": "first_alert",
"message": "message#1",
"severity": "Debug",
"scope": "http://example.com/api/instances/9d1d7e03b0d14fd0b42b5f649dfa3de5/",
"created": "2015-05-29T14:24:27.342Z",
"closed": null,
"context": {
'customer_abbreviation': 'customer_abbreviation',
'customer_contact_details': 'customer details',
'customer_name': 'Customer name',
'customer_uuid': '53c6e86406e349faa7924f4c865b15ab',
'quota_limit': '131072.0',
'quota_name': 'ram',
'quota_usage': '131071',
'quota_uuid': 'f6ae2f7ca86f4e2f9bb64de1015a2815',
'scope_name': 'project X',
'scope_uuid': '0238d71ee1934bd2839d4e71e5f9b91a'
}
"acknowledged": true,
}
]
|
entailment
|
def create(self, request, *args, **kwargs):
"""
Run **POST** against */api/alerts/* to create or update alert. If alert with posted scope and
alert_type already exists - it will be updated. Only users with staff privileges can create alerts.
Request example:
.. code-block:: javascript
POST /api/alerts/
Accept: application/json
Content-Type: application/json
Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4
Host: example.com
{
"scope": "http://testserver/api/projects/b9e8a102b5ff4469b9ac03253fae4b95/",
"message": "message#1",
"alert_type": "first_alert",
"severity": "Debug"
}
"""
return super(AlertViewSet, self).create(request, *args, **kwargs)
|
Run **POST** against */api/alerts/* to create or update alert. If alert with posted scope and
alert_type already exists - it will be updated. Only users with staff privileges can create alerts.
Request example:
.. code-block:: javascript
POST /api/alerts/
Accept: application/json
Content-Type: application/json
Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4
Host: example.com
{
"scope": "http://testserver/api/projects/b9e8a102b5ff4469b9ac03253fae4b95/",
"message": "message#1",
"alert_type": "first_alert",
"severity": "Debug"
}
|
entailment
|
def close(self, request, *args, **kwargs):
"""
To close alert - run **POST** against */api/alerts/<alert_uuid>/close/*. No data is required.
Only users with staff privileges can close alerts.
"""
if not request.user.is_staff:
raise PermissionDenied()
alert = self.get_object()
alert.close()
return response.Response(status=status.HTTP_204_NO_CONTENT)
|
To close alert - run **POST** against */api/alerts/<alert_uuid>/close/*. No data is required.
Only users with staff privileges can close alerts.
|
entailment
|
def acknowledge(self, request, *args, **kwargs):
"""
To acknowledge alert - run **POST** against */api/alerts/<alert_uuid>/acknowledge/*. No payload is required.
All users that can see alerts can also acknowledge it. If alert is already acknowledged endpoint
will return error with code 409(conflict).
"""
alert = self.get_object()
if not alert.acknowledged:
alert.acknowledge()
return response.Response(status=status.HTTP_200_OK)
else:
return response.Response({'detail': _('Alert is already acknowledged.')}, status=status.HTTP_409_CONFLICT)
|
To acknowledge alert - run **POST** against */api/alerts/<alert_uuid>/acknowledge/*. No payload is required.
All users that can see alerts can also acknowledge it. If alert is already acknowledged endpoint
will return error with code 409(conflict).
|
entailment
|
def stats(self, request, *args, **kwargs):
"""
To get count of alerts per severities - run **GET** request against */api/alerts/stats/*.
This endpoint supports all filters that are available for alerts list (*/api/alerts/*).
Response example:
.. code-block:: javascript
{
"debug": 2,
"error": 1,
"info": 1,
"warning": 1
}
"""
queryset = self.filter_queryset(self.get_queryset())
alerts_severities_count = queryset.values('severity').annotate(count=Count('severity'))
severity_names = dict(models.Alert.SeverityChoices.CHOICES)
# For consistency with all other endpoint we need to return severity names in lower case.
alerts_severities_count = {
severity_names[asc['severity']].lower(): asc['count'] for asc in alerts_severities_count}
for severity_name in severity_names.values():
if severity_name.lower() not in alerts_severities_count:
alerts_severities_count[severity_name.lower()] = 0
return response.Response(alerts_severities_count, status=status.HTTP_200_OK)
|
To get count of alerts per severities - run **GET** request against */api/alerts/stats/*.
This endpoint supports all filters that are available for alerts list (*/api/alerts/*).
Response example:
.. code-block:: javascript
{
"debug": 2,
"error": 1,
"info": 1,
"warning": 1
}
|
entailment
|
def create(self, request, *args, **kwargs):
"""
To create new web hook issue **POST** against */api/hooks-web/* as an authenticated user.
You should specify list of event_types or event_groups.
Example of a request:
.. code-block:: http
POST /api/hooks-web/ HTTP/1.1
Content-Type: application/json
Accept: application/json
Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4
Host: example.com
{
"event_types": ["resource_start_succeeded"],
"event_groups": ["users"],
"destination_url": "http://example.com/"
}
When hook is activated, **POST** request is issued against destination URL with the following data:
.. code-block:: javascript
{
"timestamp": "2015-07-14T12:12:56.000000",
"message": "Customer ABC LLC has been updated.",
"type": "customer_update_succeeded",
"context": {
"user_native_name": "Walter Lebrowski",
"customer_contact_details": "",
"user_username": "Walter",
"user_uuid": "1c3323fc4ae44120b57ec40dea1be6e6",
"customer_uuid": "4633bbbb0b3a4b91bffc0e18f853de85",
"ip_address": "8.8.8.8",
"user_full_name": "Walter Lebrowski",
"customer_abbreviation": "ABC LLC",
"customer_name": "ABC LLC"
},
"levelname": "INFO"
}
Note that context depends on event type.
"""
return super(WebHookViewSet, self).create(request, *args, **kwargs)
|
To create new web hook issue **POST** against */api/hooks-web/* as an authenticated user.
You should specify list of event_types or event_groups.
Example of a request:
.. code-block:: http
POST /api/hooks-web/ HTTP/1.1
Content-Type: application/json
Accept: application/json
Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4
Host: example.com
{
"event_types": ["resource_start_succeeded"],
"event_groups": ["users"],
"destination_url": "http://example.com/"
}
When hook is activated, **POST** request is issued against destination URL with the following data:
.. code-block:: javascript
{
"timestamp": "2015-07-14T12:12:56.000000",
"message": "Customer ABC LLC has been updated.",
"type": "customer_update_succeeded",
"context": {
"user_native_name": "Walter Lebrowski",
"customer_contact_details": "",
"user_username": "Walter",
"user_uuid": "1c3323fc4ae44120b57ec40dea1be6e6",
"customer_uuid": "4633bbbb0b3a4b91bffc0e18f853de85",
"ip_address": "8.8.8.8",
"user_full_name": "Walter Lebrowski",
"customer_abbreviation": "ABC LLC",
"customer_name": "ABC LLC"
},
"levelname": "INFO"
}
Note that context depends on event type.
|
entailment
|
def create(self, request, *args, **kwargs):
"""
To create new email hook issue **POST** against */api/hooks-email/* as an authenticated user.
You should specify list of event_types or event_groups.
Example of a request:
.. code-block:: http
POST /api/hooks-email/ HTTP/1.1
Content-Type: application/json
Accept: application/json
Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4
Host: example.com
{
"event_types": ["openstack_instance_start_succeeded"],
"event_groups": ["users"],
"email": "test@example.com"
}
You may temporarily disable hook without deleting it by issuing following **PATCH** request against hook URL:
.. code-block:: javascript
{
"is_active": "false"
}
"""
return super(EmailHookViewSet, self).create(request, *args, **kwargs)
|
To create new email hook issue **POST** against */api/hooks-email/* as an authenticated user.
You should specify list of event_types or event_groups.
Example of a request:
.. code-block:: http
POST /api/hooks-email/ HTTP/1.1
Content-Type: application/json
Accept: application/json
Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4
Host: example.com
{
"event_types": ["openstack_instance_start_succeeded"],
"event_groups": ["users"],
"email": "test@example.com"
}
You may temporarily disable hook without deleting it by issuing following **PATCH** request against hook URL:
.. code-block:: javascript
{
"is_active": "false"
}
|
entailment
|
def create(self, request, *args, **kwargs):
"""
To create new push hook issue **POST** against */api/hooks-push/* as an authenticated user.
You should specify list of event_types or event_groups.
Example of a request:
.. code-block:: http
POST /api/hooks-push/ HTTP/1.1
Content-Type: application/json
Accept: application/json
Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4
Host: example.com
{
"event_types": ["resource_start_succeeded"],
"event_groups": ["users"],
"type": "Android"
}
You may temporarily disable hook without deleting it by issuing following **PATCH** request against hook URL:
.. code-block:: javascript
{
"is_active": "false"
}
"""
return super(PushHookViewSet, self).create(request, *args, **kwargs)
|
To create new push hook issue **POST** against */api/hooks-push/* as an authenticated user.
You should specify list of event_types or event_groups.
Example of a request:
.. code-block:: http
POST /api/hooks-push/ HTTP/1.1
Content-Type: application/json
Accept: application/json
Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4
Host: example.com
{
"event_types": ["resource_start_succeeded"],
"event_groups": ["users"],
"type": "Android"
}
You may temporarily disable hook without deleting it by issuing following **PATCH** request against hook URL:
.. code-block:: javascript
{
"is_active": "false"
}
|
entailment
|
def import_from_file(self, index, filename):
"""Import this instrument's settings from the given file. Will
automatically add the instrument's synth and table to the song's
synths and tables if needed.
Note that this may invalidate existing instrument accessor objects.
:param index: the index into which to import
:param filename: the file from which to load
:raises ImportException: if importing failed, usually because the song
doesn't have enough synth or table slots left for the instrument's
synth or table
"""
with open(filename, 'r') as fp:
self._import_from_struct(index, json.load(fp))
|
Import this instrument's settings from the given file. Will
automatically add the instrument's synth and table to the song's
synths and tables if needed.
Note that this may invalidate existing instrument accessor objects.
:param index: the index into which to import
:param filename: the file from which to load
:raises ImportException: if importing failed, usually because the song
doesn't have enough synth or table slots left for the instrument's
synth or table
|
entailment
|
def load_lsdsng(filename):
"""Load a Project from a ``.lsdsng`` file.
:param filename: the name of the file from which to load
:rtype: :py:class:`pylsdj.Project`
"""
# Load preamble data so that we know the name and version of the song
with open(filename, 'rb') as fp:
preamble_data = bread.parse(fp, spec.lsdsng_preamble)
with open(filename, 'rb') as fp:
# Skip the preamble this time around
fp.seek(int(len(preamble_data) / 8))
# Load compressed data into a block map and use BlockReader to
# decompress it
factory = BlockFactory()
while True:
block_data = bytearray(fp.read(blockutils.BLOCK_SIZE))
if len(block_data) == 0:
break
block = factory.new_block()
block.data = block_data
remapped_blocks = filepack.renumber_block_keys(factory.blocks)
reader = BlockReader()
compressed_data = reader.read(remapped_blocks)
# Now, decompress the raw data and use it and the preamble to construct
# a Project
raw_data = filepack.decompress(compressed_data)
name = preamble_data.name
version = preamble_data.version
size_blks = int(math.ceil(
float(len(compressed_data)) / blockutils.BLOCK_SIZE))
return Project(name, version, size_blks, raw_data)
|
Load a Project from a ``.lsdsng`` file.
:param filename: the name of the file from which to load
:rtype: :py:class:`pylsdj.Project`
|
entailment
|
def load_srm(filename):
"""Load a Project from an ``.srm`` file.
:param filename: the name of the file from which to load
:rtype: :py:class:`pylsdj.Project`
"""
# .srm files are just decompressed projects without headers
# In order to determine the file's size in compressed blocks, we have to
# compress it first
with open(filename, 'rb') as fp:
raw_data = fp.read()
compressed_data = filepack.compress(raw_data)
factory = BlockFactory()
writer = BlockWriter()
writer.write(compressed_data, factory)
size_in_blocks = len(factory.blocks)
# We'll give the file a dummy name ("SRMLOAD") and version, since we know
# neither
name = "SRMLOAD"
version = 0
return Project(name, version, size_in_blocks, raw_data)
|
Load a Project from an ``.srm`` file.
:param filename: the name of the file from which to load
:rtype: :py:class:`pylsdj.Project`
|
entailment
|
def song(self):
"""the song associated with the project"""
if self._song is None:
self._song = Song(self._song_data)
return self._song
|
the song associated with the project
|
entailment
|
def save(self, filename):
"""Save a project in .lsdsng format to the target file.
:param filename: the name of the file to which to save
:deprecated: use ``save_lsdsng(filename)`` instead
"""
with open(filename, 'wb') as fp:
writer = BlockWriter()
factory = BlockFactory()
preamble_dummy_bytes = bytearray([0] * 9)
preamble = bread.parse(
preamble_dummy_bytes, spec.lsdsng_preamble)
preamble.name = self.name
preamble.version = self.version
preamble_data = bread.write(preamble)
raw_data = self.get_raw_data()
compressed_data = filepack.compress(raw_data)
writer.write(compressed_data, factory)
fp.write(preamble_data)
for key in sorted(factory.blocks.keys()):
fp.write(bytearray(factory.blocks[key].data))
|
Save a project in .lsdsng format to the target file.
:param filename: the name of the file to which to save
:deprecated: use ``save_lsdsng(filename)`` instead
|
entailment
|
def save_srm(self, filename):
"""Save a project in .srm format to the target file.
:param filename: the name of the file to which to save
"""
with open(filename, 'wb') as fp:
raw_data = bread.write(self._song_data, spec.song)
fp.write(raw_data)
|
Save a project in .srm format to the target file.
:param filename: the name of the file to which to save
|
entailment
|
def phase_type(self, value):
'''compresses the waveform horizontally; one of
``"normal"``, ``"resync"``, ``"resync2"``'''
self._params.phase_type = value
self._overwrite_lock.disable()
|
compresses the waveform horizontally; one of
``"normal"``, ``"resync"``, ``"resync2"``
|
entailment
|
def project_list(self):
"""The list of :py:class:`pylsdj.Project` s that the
.sav file contains"""
return [(i, self.projects[i]) for i in sorted(self.projects.keys())]
|
The list of :py:class:`pylsdj.Project` s that the
.sav file contains
|
entailment
|
def save(self, filename, callback=_noop_callback):
"""Save this file.
:param filename: the file to which to save the .sav file
:type filename: str
:param callback: a progress callback function
:type callback: function
"""
with open(filename, 'wb') as fp:
self._save(fp, callback)
|
Save this file.
:param filename: the file to which to save the .sav file
:type filename: str
:param callback: a progress callback function
:type callback: function
|
entailment
|
def split(compressed_data, segment_size, block_factory):
"""Splits compressed data into blocks.
:param compressed_data: the compressed data to split
:param segment_size: the size of a block in bytes
:param block_factory: a BlockFactory used to construct the blocks
:rtype: a list of block IDs of blocks that the block factory created while
splitting
"""
# Split compressed data into blocks
segments = []
current_segment_start = 0
index = 0
data_size = len(compressed_data)
while index < data_size:
current_byte = compressed_data[index]
if index < data_size - 1:
next_byte = compressed_data[index + 1]
else:
next_byte = None
jump_size = 1
if current_byte == RLE_BYTE:
assert next_byte is not None, "Expected a command to follow " \
"RLE byte"
if next_byte == RLE_BYTE:
jump_size = 2
else:
jump_size = 3
elif current_byte == SPECIAL_BYTE:
assert next_byte is not None, "Expected a command to follow " \
"special byte"
if next_byte == SPECIAL_BYTE:
jump_size = 2
elif next_byte == DEFAULT_INSTR_BYTE or \
next_byte == DEFAULT_WAVE_BYTE:
jump_size = 3
else:
assert False, "Encountered unexpected EOF or block " \
"switch while segmenting"
# Need two bytes for the jump or EOF
if index - current_segment_start + jump_size > segment_size - 2:
segments.append(compressed_data[
current_segment_start:index])
current_segment_start = index
else:
index += jump_size
# Append the last segment, if any
if current_segment_start != index:
segments.append(compressed_data[
current_segment_start:current_segment_start + index])
# Make sure that no data was lost while segmenting
total_segment_length = sum(map(len, segments))
assert total_segment_length == len(compressed_data), "Lost %d bytes of " \
"data while segmenting" % (len(compressed_data) - total_segment_length)
block_ids = []
for segment in segments:
block = block_factory.new_block()
block_ids.append(block.id)
for (i, segment) in enumerate(segments):
block = block_factory.blocks[block_ids[i]]
assert len(block.data) == 0, "Encountered a block with "
"pre-existing data while writing"
if i == len(segments) - 1:
# Write EOF to the end of the segment
add_eof(segment)
else:
# Write a pointer to the next segment
add_block_switch(segment, block_ids[i + 1])
# Pad segment with zeroes until it's large enough
pad(segment, segment_size)
block.data = segment
return block_ids
|
Splits compressed data into blocks.
:param compressed_data: the compressed data to split
:param segment_size: the size of a block in bytes
:param block_factory: a BlockFactory used to construct the blocks
:rtype: a list of block IDs of blocks that the block factory created while
splitting
|
entailment
|
def renumber_block_keys(blocks):
"""Renumber a block map's indices so that tehy match the blocks' block
switch statements.
:param blocks a block map to renumber
:rtype: a renumbered copy of the block map
"""
# There is an implicit block switch to the 0th block at the start of the
# file
byte_switch_keys = [0]
block_keys = list(blocks.keys())
# Scan the blocks, recording every block switch statement
for block in list(blocks.values()):
i = 0
while i < len(block.data) - 1:
current_byte = block.data[i]
next_byte = block.data[i + 1]
if current_byte == RLE_BYTE:
if next_byte == RLE_BYTE:
i += 2
else:
i += 3
elif current_byte == SPECIAL_BYTE:
if next_byte in SPECIAL_DEFAULTS:
i += 3
elif next_byte == SPECIAL_BYTE:
i += 2
else:
if next_byte != EOF_BYTE:
byte_switch_keys.append(next_byte)
break
else:
i += 1
byte_switch_keys.sort()
block_keys.sort()
assert len(byte_switch_keys) == len(block_keys), (
"Number of blocks that are target of block switches (%d) "
% (len(byte_switch_keys)) +
"does not equal number of blocks in the song (%d)"
% (len(block_keys)) +
"; possible corruption")
if byte_switch_keys == block_keys:
# No remapping necessary
return blocks
new_block_map = {}
for block_key, byte_switch_key in zip(
block_keys, byte_switch_keys):
new_block_map[byte_switch_key] = blocks[block_key]
return new_block_map
|
Renumber a block map's indices so that tehy match the blocks' block
switch statements.
:param blocks a block map to renumber
:rtype: a renumbered copy of the block map
|
entailment
|
def merge(blocks):
"""Merge the given blocks into a contiguous block of compressed data.
:param blocks: the list of blocks
:rtype: a list of compressed bytes
"""
current_block = blocks[sorted(blocks.keys())[0]]
compressed_data = []
eof = False
while not eof:
data_size_to_append = None
next_block = None
i = 0
while i < len(current_block.data) - 1:
current_byte = current_block.data[i]
next_byte = current_block.data[i + 1]
if current_byte == RLE_BYTE:
if next_byte == RLE_BYTE:
i += 2
else:
i += 3
elif current_byte == SPECIAL_BYTE:
if next_byte in SPECIAL_DEFAULTS:
i += 3
elif next_byte == SPECIAL_BYTE:
i += 2
else:
data_size_to_append = i
# hit end of file
if next_byte == EOF_BYTE:
eof = True
else:
next_block = blocks[next_byte]
break
else:
i += 1
assert data_size_to_append is not None, "Ran off the end of a "\
"block without encountering a block switch or EOF"
compressed_data.extend(current_block.data[0:data_size_to_append])
if not eof:
assert next_block is not None, "Switched blocks, but did " \
"not provide the next block to switch to"
current_block = next_block
return compressed_data
|
Merge the given blocks into a contiguous block of compressed data.
:param blocks: the list of blocks
:rtype: a list of compressed bytes
|
entailment
|
def pad(segment, size):
"""Add zeroes to a segment until it reaches a certain size.
:param segment: the segment to pad
:param size: the size to which to pad the segment
"""
for i in range(size - len(segment)):
segment.append(0)
assert len(segment) == size
|
Add zeroes to a segment until it reaches a certain size.
:param segment: the segment to pad
:param size: the size to which to pad the segment
|
entailment
|
def decompress(compressed_data):
"""Decompress data that has been compressed by the filepack algorithm.
:param compressed_data: an array of compressed data bytes to decompress
:rtype: an array of decompressed bytes"""
raw_data = []
index = 0
while index < len(compressed_data):
current = compressed_data[index]
index += 1
if current == RLE_BYTE:
directive = compressed_data[index]
index += 1
if directive == RLE_BYTE:
raw_data.append(RLE_BYTE)
else:
count = compressed_data[index]
index += 1
raw_data.extend([directive] * count)
elif current == SPECIAL_BYTE:
directive = compressed_data[index]
index += 1
if directive == SPECIAL_BYTE:
raw_data.append(SPECIAL_BYTE)
elif directive == DEFAULT_WAVE_BYTE:
count = compressed_data[index]
index += 1
raw_data.extend(DEFAULT_WAVE * count)
elif directive == DEFAULT_INSTR_BYTE:
count = compressed_data[index]
index += 1
raw_data.extend(DEFAULT_INSTRUMENT_FILEPACK * count)
elif directive == EOF_BYTE:
assert False, ("Unexpected EOF command encountered while "
"decompressing")
else:
assert False, "Countered unexpected sequence 0x%02x 0x%02x" % (
current, directive)
else:
raw_data.append(current)
return raw_data
|
Decompress data that has been compressed by the filepack algorithm.
:param compressed_data: an array of compressed data bytes to decompress
:rtype: an array of decompressed bytes
|
entailment
|
def compress(raw_data):
"""Compress raw bytes with the filepack algorithm.
:param raw_data: an array of raw data bytes to compress
:rtype: a list of compressed bytes
"""
raw_data = bytearray(raw_data)
compressed_data = []
data_size = len(raw_data)
index = 0
next_bytes = [-1, -1, -1]
def is_default_instrument(index):
if index + len(DEFAULT_INSTRUMENT_FILEPACK) > len(raw_data):
return False
instr_bytes = raw_data[index:index + len(DEFAULT_INSTRUMENT_FILEPACK)]
if instr_bytes[0] != 0xa8 or instr_bytes[1] != 0:
return False
return instr_bytes == DEFAULT_INSTRUMENT_FILEPACK
def is_default_wave(index):
return (index + len(DEFAULT_WAVE) <= len(raw_data) and
raw_data[index:index + len(DEFAULT_WAVE)] == DEFAULT_WAVE)
while index < data_size:
current_byte = raw_data[index]
for i in range(3):
if index < data_size - (i + 1):
next_bytes[i] = raw_data[index + (i + 1)]
else:
next_bytes[i] = -1
if current_byte == RLE_BYTE:
compressed_data.append(RLE_BYTE)
compressed_data.append(RLE_BYTE)
index += 1
elif current_byte == SPECIAL_BYTE:
compressed_data.append(SPECIAL_BYTE)
compressed_data.append(SPECIAL_BYTE)
index += 1
elif is_default_instrument(index):
counter = 1
index += len(DEFAULT_INSTRUMENT_FILEPACK)
while (is_default_instrument(index) and
counter < 0x100):
counter += 1
index += len(DEFAULT_INSTRUMENT_FILEPACK)
compressed_data.append(SPECIAL_BYTE)
compressed_data.append(DEFAULT_INSTR_BYTE)
compressed_data.append(counter)
elif is_default_wave(index):
counter = 1
index += len(DEFAULT_WAVE)
while is_default_wave(index) and counter < 0xff:
counter += 1
index += len(DEFAULT_WAVE)
compressed_data.append(SPECIAL_BYTE)
compressed_data.append(DEFAULT_WAVE_BYTE)
compressed_data.append(counter)
elif (current_byte == next_bytes[0] and
next_bytes[0] == next_bytes[1] and
next_bytes[1] == next_bytes[2]):
# Do RLE compression
compressed_data.append(RLE_BYTE)
compressed_data.append(current_byte)
counter = 0
while (index < data_size and
raw_data[index] == current_byte and
counter < 0xff):
index += 1
counter += 1
compressed_data.append(counter)
else:
compressed_data.append(current_byte)
index += 1
return compressed_data
|
Compress raw bytes with the filepack algorithm.
:param raw_data: an array of raw data bytes to compress
:rtype: a list of compressed bytes
|
entailment
|
def name_without_zeroes(name):
"""
Return a human-readable name without LSDJ's trailing zeroes.
:param name: the name from which to strip zeroes
:rtype: the name, without trailing zeroes
"""
first_zero = name.find(b'\0')
if first_zero == -1:
return name
else:
return str(name[:first_zero])
|
Return a human-readable name without LSDJ's trailing zeroes.
:param name: the name from which to strip zeroes
:rtype: the name, without trailing zeroes
|
entailment
|
def name(self):
"""the instrument's name (5 characters, zero-padded)"""
instr_name = self.song.song_data.instrument_names[self.index]
if type(instr_name) == bytes:
instr_name = instr_name.decode('utf-8')
return instr_name
|
the instrument's name (5 characters, zero-padded)
|
entailment
|
def table(self):
"""a ```pylsdj.Table``` referencing the instrument's table, or None
if the instrument doesn't have a table"""
if hasattr(self.data, 'table_on') and self.data.table_on:
assert_index_sane(self.data.table, len(self.song.tables))
return self.song.tables[self.data.table]
|
a ```pylsdj.Table``` referencing the instrument's table, or None
if the instrument doesn't have a table
|
entailment
|
def import_lsdinst(self, struct_data):
"""import from an lsdinst struct"""
self.name = struct_data['name']
self.automate = struct_data['data']['automate']
self.pan = struct_data['data']['pan']
if self.table is not None:
self.table.import_lsdinst(struct_data)
|
import from an lsdinst struct
|
entailment
|
def export_to_file(self, filename):
"""Export this instrument's settings to a file.
:param filename: the name of the file
"""
instr_json = self.export_struct()
with open(filename, 'w') as fp:
json.dump(instr_json, fp, indent=2)
|
Export this instrument's settings to a file.
:param filename: the name of the file
|
entailment
|
def write_wav(self, filename):
"""Write this sample to a WAV file.
:param filename: the file to which to write
"""
wave_output = None
try:
wave_output = wave.open(filename, 'w')
wave_output.setparams(WAVE_PARAMS)
frames = bytearray([x << 4 for x in self.sample_data])
wave_output.writeframes(frames)
finally:
if wave_output is not None:
wave_output.close()
|
Write this sample to a WAV file.
:param filename: the file to which to write
|
entailment
|
def read_wav(self, filename):
"""Read sample data for this sample from a WAV file.
:param filename: the file from which to read
"""
wave_input = None
try:
wave_input = wave.open(filename, 'r')
wave_frames = bytearray(
wave_input.readframes(wave_input.getnframes()))
self.sample_data = [x >> 4 for x in wave_frames]
finally:
if wave_input is not None:
wave_input.close()
|
Read sample data for this sample from a WAV file.
:param filename: the file from which to read
|
entailment
|
def get_device_address(device):
""" find the local ip address on the given device """
if device is None:
return None
command = ['ip', 'route', 'list', 'dev', device]
ip_routes = subprocess.check_output(command).strip()
for line in ip_routes.split('\n'):
seen = ''
for a in line.split():
if seen == 'src':
return a
seen = a
return None
|
find the local ip address on the given device
|
entailment
|
def get_default_net_device():
""" Find the device where the default route is. """
with open('/proc/net/route') as fh:
for line in fh:
iface, dest, _ = line.split(None, 2)
if dest == '00000000':
return iface
return None
|
Find the device where the default route is.
|
entailment
|
def add_missing_optional_args_with_value_none(args, optional_args):
'''
Adds key-value pairs to the passed dictionary, so that
afterwards, the dictionary can be used without needing
to check for KeyErrors.
If the keys passed as a second argument are not present,
they are added with None as a value.
:args: The dictionary to be completed.
:optional_args: The keys that need to be added, if
they are not present.
:return: The modified dictionary.
'''
for name in optional_args:
if not name in args.keys():
args[name] = None
return args
|
Adds key-value pairs to the passed dictionary, so that
afterwards, the dictionary can be used without needing
to check for KeyErrors.
If the keys passed as a second argument are not present,
they are added with None as a value.
:args: The dictionary to be completed.
:optional_args: The keys that need to be added, if
they are not present.
:return: The modified dictionary.
|
entailment
|
def check_presence_of_mandatory_args(args, mandatory_args):
'''
Checks whether all mandatory arguments are passed.
This function aims at methods with many arguments
which are passed as kwargs so that the order
in which the are passed does not matter.
:args: The dictionary passed as args.
:mandatory_args: A list of keys that have to be
present in the dictionary.
:raise: :exc:`~ValueError`
:returns: True, if all mandatory args are passed. If not,
an exception is raised.
'''
missing_args = []
for name in mandatory_args:
if name not in args.keys():
missing_args.append(name)
if len(missing_args) > 0:
raise ValueError('Missing mandatory arguments: '+', '.join(missing_args))
else:
return True
|
Checks whether all mandatory arguments are passed.
This function aims at methods with many arguments
which are passed as kwargs so that the order
in which the are passed does not matter.
:args: The dictionary passed as args.
:mandatory_args: A list of keys that have to be
present in the dictionary.
:raise: :exc:`~ValueError`
:returns: True, if all mandatory args are passed. If not,
an exception is raised.
|
entailment
|
def size(self, store_hashes=True):
"""
Retrieves the size in bytes of this ZIP content.
:return: Size of the zip content in bytes
"""
if self.modified:
self.__cache_content(store_hashes)
return len(self.cached_content)
|
Retrieves the size in bytes of this ZIP content.
:return: Size of the zip content in bytes
|
entailment
|
def monkey_patch_migration_template(self, app, fixture_path):
"""
Monkey patch the django.db.migrations.writer.MIGRATION_TEMPLATE
Monkey patching django.db.migrations.writer.MIGRATION_TEMPLATE means that we
don't have to do any complex regex or reflection.
It's hacky... but works atm.
"""
self._MIGRATION_TEMPLATE = writer.MIGRATION_TEMPLATE
module_split = app.module.__name__.split('.')
if len(module_split) == 1:
module_import = "import %s\n" % module_split[0]
else:
module_import = "from %s import %s\n" % (
'.'.join(module_split[:-1]),
module_split[-1:][0],
)
writer.MIGRATION_TEMPLATE = writer.MIGRATION_TEMPLATE\
.replace(
'%(imports)s',
"%(imports)s" + "\nfrom django_migration_fixture import fixture\n%s" % module_import
)\
.replace(
'%(operations)s',
" migrations.RunPython(**fixture(%s, ['%s'])),\n" % (
app.label,
os.path.basename(fixture_path)
) + "%(operations)s\n"
)
|
Monkey patch the django.db.migrations.writer.MIGRATION_TEMPLATE
Monkey patching django.db.migrations.writer.MIGRATION_TEMPLATE means that we
don't have to do any complex regex or reflection.
It's hacky... but works atm.
|
entailment
|
def migration_exists(self, app, fixture_path):
"""
Return true if it looks like a migration already exists.
"""
base_name = os.path.basename(fixture_path)
# Loop through all migrations
for migration_path in glob.glob(os.path.join(app.path, 'migrations', '*.py')):
if base_name in open(migration_path).read():
return True
return False
|
Return true if it looks like a migration already exists.
|
entailment
|
def create_migration(self, app, fixture_path):
"""
Create a data migration for app that uses fixture_path.
"""
self.monkey_patch_migration_template(app, fixture_path)
out = StringIO()
management.call_command('makemigrations', app.label, empty=True, stdout=out)
self.restore_migration_template()
self.stdout.write(out.getvalue())
|
Create a data migration for app that uses fixture_path.
|
entailment
|
def instantiate_for_read_and_search(handle_server_url, reverselookup_username, reverselookup_password, **config):
'''
Initialize client with read access and with search function.
:param handle_server_url: The URL of the Handle Server. May be None
(then, the default 'https://hdl.handle.net' is used).
:param reverselookup_username: The username to authenticate at the
reverse lookup servlet.
:param reverselookup_password: The password to authenticate at the
reverse lookup servlet.
:param \**config: More key-value pairs may be passed that will be passed
on to the constructor as config. Config options from the
credentials object are overwritten by this.
:return: An instance of the client.
'''
if handle_server_url is None and 'reverselookup_baseuri' not in config.keys():
raise TypeError('You must specify either "handle_server_url" or "reverselookup_baseuri".' + \
' Searching not possible without the URL of a search servlet.')
inst = EUDATHandleClient(
handle_server_url,
reverselookup_username=reverselookup_username,
reverselookup_password=reverselookup_password,
**config
)
return inst
|
Initialize client with read access and with search function.
:param handle_server_url: The URL of the Handle Server. May be None
(then, the default 'https://hdl.handle.net' is used).
:param reverselookup_username: The username to authenticate at the
reverse lookup servlet.
:param reverselookup_password: The password to authenticate at the
reverse lookup servlet.
:param \**config: More key-value pairs may be passed that will be passed
on to the constructor as config. Config options from the
credentials object are overwritten by this.
:return: An instance of the client.
|
entailment
|
def instantiate_with_username_and_password(handle_server_url, username, password, **config):
'''
Initialize client against an HSv8 instance with full read/write access.
The method will throw an exception upon bad syntax or non-existing
Handle. The existence or validity of the password in the handle is
not checked at this moment.
:param handle_server_url: The URL of the Handle System server.
:param username: This must be a handle value reference in the format
"index:prefix/suffix".
:param password: This is the password stored as secret key in the
actual Handle value the username points to.
:param \**config: More key-value pairs may be passed that will be passed
on to the constructor as config.
:raises: :exc:`~b2handle.handleexceptions.HandleNotFoundException`: If the username handle is not found.
:raises: :exc:`~b2handle.handleexceptions.HandleSyntaxError`
:return: An instance of the client.
'''
inst = EUDATHandleClient(handle_server_url, username=username, password=password, **config)
return inst
|
Initialize client against an HSv8 instance with full read/write access.
The method will throw an exception upon bad syntax or non-existing
Handle. The existence or validity of the password in the handle is
not checked at this moment.
:param handle_server_url: The URL of the Handle System server.
:param username: This must be a handle value reference in the format
"index:prefix/suffix".
:param password: This is the password stored as secret key in the
actual Handle value the username points to.
:param \**config: More key-value pairs may be passed that will be passed
on to the constructor as config.
:raises: :exc:`~b2handle.handleexceptions.HandleNotFoundException`: If the username handle is not found.
:raises: :exc:`~b2handle.handleexceptions.HandleSyntaxError`
:return: An instance of the client.
|
entailment
|
def instantiate_with_credentials(credentials, **config):
'''
Initialize the client against an HSv8 instance with full read/write
access.
:param credentials: A credentials object, see separate class
PIDClientCredentials.
:param \**config: More key-value pairs may be passed that will be passed
on to the constructor as config. Config options from the
credentials object are overwritten by this.
:raises: :exc:`~b2handle.handleexceptions.HandleNotFoundException`: If the username handle is not found.
:return: An instance of the client.
'''
key_value_pairs = credentials.get_all_args()
if config is not None:
key_value_pairs.update(**config) # passed config overrides json file
inst = EUDATHandleClient(**key_value_pairs)
return inst
|
Initialize the client against an HSv8 instance with full read/write
access.
:param credentials: A credentials object, see separate class
PIDClientCredentials.
:param \**config: More key-value pairs may be passed that will be passed
on to the constructor as config. Config options from the
credentials object are overwritten by this.
:raises: :exc:`~b2handle.handleexceptions.HandleNotFoundException`: If the username handle is not found.
:return: An instance of the client.
|
entailment
|
def retrieve_handle_record_json(self, handle):
'''
Retrieve a handle record from the Handle server as a complete nested
dict (including index, ttl, timestamp, ...) for later use.
Note: For retrieving a simple dict with only the keys and values,
please use :meth:`~b2handle.handleclient.EUDATHandleClient.retrieve_handle_record`.
:param handle: The Handle whose record to retrieve.
:raises: :exc:`~b2handle.handleexceptions.HandleSyntaxError`
:return: The handle record as a nested dict. If the handle does not
exist, returns None.
'''
LOGGER.debug('retrieve_handle_record_json...')
utilhandle.check_handle_syntax(handle)
response = self.__send_handle_get_request(handle)
response_content = decoded_response(response)
if hsresponses.handle_not_found(response):
return None
elif hsresponses.does_handle_exist(response):
handlerecord_json = json.loads(response_content)
if not handlerecord_json['handle'] == handle:
raise GenericHandleError(
operation='retrieving handle record',
handle=handle,
response=response,
custom_message='The retrieve returned a different handle than was asked for.'
)
return handlerecord_json
elif hsresponses.is_handle_empty(response):
handlerecord_json = json.loads(response_content)
return handlerecord_json
else:
raise GenericHandleError(
operation='retrieving',
handle=handle,
response=response
)
|
Retrieve a handle record from the Handle server as a complete nested
dict (including index, ttl, timestamp, ...) for later use.
Note: For retrieving a simple dict with only the keys and values,
please use :meth:`~b2handle.handleclient.EUDATHandleClient.retrieve_handle_record`.
:param handle: The Handle whose record to retrieve.
:raises: :exc:`~b2handle.handleexceptions.HandleSyntaxError`
:return: The handle record as a nested dict. If the handle does not
exist, returns None.
|
entailment
|
def retrieve_handle_record(self, handle, handlerecord_json=None):
'''
Retrieve a handle record from the Handle server as a dict. If there
is several entries of the same type, only the first one is
returned. Values of complex types (such as HS_ADMIN) are
transformed to strings.
:param handle: The handle whose record to retrieve.
:param handlerecord_json: Optional. If the handlerecord has already
been retrieved from the server, it can be reused.
:return: A dict where the keys are keys from the Handle record (except
for hidden entries) and every value is a string. The result will be
None if the Handle does not exist.
:raises: :exc:`~b2handle.handleexceptions.HandleSyntaxError`
'''
LOGGER.debug('retrieve_handle_record...')
handlerecord_json = self.__get_handle_record_if_necessary(handle, handlerecord_json)
if handlerecord_json is None:
return None # Instead of HandleNotFoundException!
list_of_entries = handlerecord_json['values']
record_as_dict = {}
for entry in list_of_entries:
key = entry['type']
if not key in record_as_dict.keys():
record_as_dict[key] = str(entry['data']['value'])
return record_as_dict
|
Retrieve a handle record from the Handle server as a dict. If there
is several entries of the same type, only the first one is
returned. Values of complex types (such as HS_ADMIN) are
transformed to strings.
:param handle: The handle whose record to retrieve.
:param handlerecord_json: Optional. If the handlerecord has already
been retrieved from the server, it can be reused.
:return: A dict where the keys are keys from the Handle record (except
for hidden entries) and every value is a string. The result will be
None if the Handle does not exist.
:raises: :exc:`~b2handle.handleexceptions.HandleSyntaxError`
|
entailment
|
def get_value_from_handle(self, handle, key, handlerecord_json=None):
'''
Retrieve a single value from a single Handle. If several entries with
this key exist, the methods returns the first one. If the handle
does not exist, the method will raise a HandleNotFoundException.
:param handle: The handle to take the value from.
:param key: The key.
:return: A string containing the value or None if the Handle record
does not contain the key.
:raises: :exc:`~b2handle.handleexceptions.HandleSyntaxError`
:raises: :exc:`~b2handle.handleexceptions.HandleNotFoundException`
'''
LOGGER.debug('get_value_from_handle...')
handlerecord_json = self.__get_handle_record_if_necessary(handle, handlerecord_json)
if handlerecord_json is None:
raise HandleNotFoundException(handle=handle)
list_of_entries = handlerecord_json['values']
indices = []
for i in xrange(len(list_of_entries)):
if list_of_entries[i]['type'] == key:
indices.append(i)
if len(indices) == 0:
return None
else:
if len(indices) > 1:
LOGGER.debug('get_value_from_handle: The handle ' + handle + \
' contains several entries of type "' + key + \
'". Only the first one is returned.')
return list_of_entries[indices[0]]['data']['value']
|
Retrieve a single value from a single Handle. If several entries with
this key exist, the methods returns the first one. If the handle
does not exist, the method will raise a HandleNotFoundException.
:param handle: The handle to take the value from.
:param key: The key.
:return: A string containing the value or None if the Handle record
does not contain the key.
:raises: :exc:`~b2handle.handleexceptions.HandleSyntaxError`
:raises: :exc:`~b2handle.handleexceptions.HandleNotFoundException`
|
entailment
|
def is_10320LOC_empty(self, handle, handlerecord_json=None):
'''
Checks if there is a 10320/LOC entry in the handle record.
*Note:* In the unlikely case that there is a 10320/LOC entry, but it does
not contain any locations, it is treated as if there was none.
:param handle: The handle.
:param handlerecord_json: Optional. The content of the response of a
GET request for the handle as a dict. Avoids another GET request.
:raises: :exc:`~b2handle.handleexceptions.HandleNotFoundException`
:raises: :exc:`~b2handle.handleexceptions.HandleSyntaxError`
:return: True if the record contains NO 10320/LOC entry; False if it
does contain one.
'''
LOGGER.debug('is_10320LOC_empty...')
handlerecord_json = self.__get_handle_record_if_necessary(handle, handlerecord_json)
if handlerecord_json is None:
raise HandleNotFoundException(handle=handle)
list_of_entries = handlerecord_json['values']
num_entries = 0
num_URL = 0
for entry in list_of_entries:
if entry['type'] == '10320/LOC':
num_entries += 1
xmlroot = ET.fromstring(entry['data']['value'])
list_of_locations = xmlroot.findall('location')
for item in list_of_locations:
if item.get('href') is not None:
num_URL += 1
if num_entries == 0:
return True
else:
if num_URL == 0:
return True
else:
return False
|
Checks if there is a 10320/LOC entry in the handle record.
*Note:* In the unlikely case that there is a 10320/LOC entry, but it does
not contain any locations, it is treated as if there was none.
:param handle: The handle.
:param handlerecord_json: Optional. The content of the response of a
GET request for the handle as a dict. Avoids another GET request.
:raises: :exc:`~b2handle.handleexceptions.HandleNotFoundException`
:raises: :exc:`~b2handle.handleexceptions.HandleSyntaxError`
:return: True if the record contains NO 10320/LOC entry; False if it
does contain one.
|
entailment
|
def generate_and_register_handle(self, prefix, location, checksum=None, additional_URLs=None, **extratypes):
'''
Register a new Handle with a unique random name (random UUID).
:param prefix: The prefix of the handle to be registered. The method
will generate a suffix.
:param location: The URL of the data entity to be referenced.
:param checksum: Optional. The checksum string.
:param extratypes: Optional. Additional key value pairs as dict.
:param additional_URLs: Optional. A list of URLs (as strings) to be
added to the handle record as 10320/LOC entry.
:raises: :exc:`~b2handle.handleexceptions.HandleAuthenticationError`
:return: The new handle name.
'''
LOGGER.debug('generate_and_register_handle...')
handle = self.generate_PID_name(prefix)
handle = self.register_handle(
handle,
location,
checksum,
additional_URLs,
overwrite=True,
**extratypes
)
return handle
|
Register a new Handle with a unique random name (random UUID).
:param prefix: The prefix of the handle to be registered. The method
will generate a suffix.
:param location: The URL of the data entity to be referenced.
:param checksum: Optional. The checksum string.
:param extratypes: Optional. Additional key value pairs as dict.
:param additional_URLs: Optional. A list of URLs (as strings) to be
added to the handle record as 10320/LOC entry.
:raises: :exc:`~b2handle.handleexceptions.HandleAuthenticationError`
:return: The new handle name.
|
entailment
|
def modify_handle_value(self, handle, ttl=None, add_if_not_exist=True, **kvpairs):
'''
Modify entries (key-value-pairs) in a handle record. If the key
does not exist yet, it is created.
*Note:* We assume that a key exists only once. In case a key exists
several time, an exception will be raised.
*Note:* To modify 10320/LOC, please use :meth:`~b2handle.handleclient.EUDATHandleClient.add_additional_URL` or
:meth:`~b2handle.handleclient.EUDATHandleClient.remove_additional_URL`.
:param handle: Handle whose record is to be modified
:param ttl: Optional. Integer value. If ttl should be set to a
non-default value.
:param all other args: The user can specify several key-value-pairs.
These will be the handle value types and values that will be
modified. The keys are the names or the handle value types (e.g.
"URL"). The values are the new values to store in "data". If the
key is 'HS_ADMIN', the new value needs to be of the form
{'handle':'xyz', 'index':xyz}. The permissions will be set to the
default permissions.
:raises: :exc:`~b2handle.handleexceptions.HandleAuthenticationError`
:raises: :exc:`~b2handle.handleexceptions.HandleNotFoundException`
:raises: :exc:`~b2handle.handleexceptions.HandleSyntaxError`
'''
LOGGER.debug('modify_handle_value...')
# Read handle record:
handlerecord_json = self.retrieve_handle_record_json(handle)
if handlerecord_json is None:
msg = 'Cannot modify unexisting handle'
raise HandleNotFoundException(handle=handle, msg=msg)
list_of_entries = handlerecord_json['values']
# HS_ADMIN
if 'HS_ADMIN' in kvpairs.keys() and not self.__modify_HS_ADMIN:
msg = 'You may not modify HS_ADMIN'
raise IllegalOperationException(
msg=msg,
operation='modifying HS_ADMIN',
handle=handle
)
nothingchanged = True
new_list_of_entries = []
list_of_old_and_new_entries = list_of_entries[:]
keys = kvpairs.keys()
for key, newval in kvpairs.items():
# Change existing entry:
changed = False
for i in xrange(len(list_of_entries)):
if list_of_entries[i]['type'] == key:
if not changed:
list_of_entries[i]['data'] = newval
list_of_entries[i].pop('timestamp') # will be ignored anyway
if key == 'HS_ADMIN':
newval['permissions'] = self.__HS_ADMIN_permissions
list_of_entries[i].pop('timestamp') # will be ignored anyway
list_of_entries[i]['data'] = {
'format':'admin',
'value':newval
}
LOGGER.info('Modified' + \
' "HS_ADMIN" of handle ' + handle)
changed = True
nothingchanged = False
new_list_of_entries.append(list_of_entries[i])
list_of_old_and_new_entries.append(list_of_entries[i])
else:
msg = 'There is several entries of type "' + key + '".' + \
' This can lead to unexpected behaviour.' + \
' Please clean up before modifying the record.'
raise BrokenHandleRecordException(handle=handle, msg=msg)
# If the entry doesn't exist yet, add it:
if not changed:
if add_if_not_exist:
LOGGER.debug('modify_handle_value: Adding entry "' + key + '"' + \
' to handle ' + handle)
index = self.__make_another_index(list_of_old_and_new_entries)
entry_to_add = self.__create_entry(key, newval, index, ttl)
new_list_of_entries.append(entry_to_add)
list_of_old_and_new_entries.append(entry_to_add)
changed = True
nothingchanged = False
# Add the indices
indices = []
for i in xrange(len(new_list_of_entries)):
indices.append(new_list_of_entries[i]['index'])
# append to the old record:
if nothingchanged:
LOGGER.debug('modify_handle_value: There was no entries ' + \
str(kvpairs.keys()) + ' to be modified (handle ' + handle + ').' + \
' To add them, set add_if_not_exist = True')
else:
op = 'modifying handle values'
resp, put_payload = self.__send_handle_put_request(
handle,
new_list_of_entries,
indices=indices,
overwrite=True,
op=op)
if hsresponses.handle_success(resp):
LOGGER.info('Handle modified: ' + handle)
else:
msg = 'Values: ' + str(kvpairs)
raise GenericHandleError(
operation=op,
handle=handle,
response=resp,
msg=msg,
payload=put_payload
)
|
Modify entries (key-value-pairs) in a handle record. If the key
does not exist yet, it is created.
*Note:* We assume that a key exists only once. In case a key exists
several time, an exception will be raised.
*Note:* To modify 10320/LOC, please use :meth:`~b2handle.handleclient.EUDATHandleClient.add_additional_URL` or
:meth:`~b2handle.handleclient.EUDATHandleClient.remove_additional_URL`.
:param handle: Handle whose record is to be modified
:param ttl: Optional. Integer value. If ttl should be set to a
non-default value.
:param all other args: The user can specify several key-value-pairs.
These will be the handle value types and values that will be
modified. The keys are the names or the handle value types (e.g.
"URL"). The values are the new values to store in "data". If the
key is 'HS_ADMIN', the new value needs to be of the form
{'handle':'xyz', 'index':xyz}. The permissions will be set to the
default permissions.
:raises: :exc:`~b2handle.handleexceptions.HandleAuthenticationError`
:raises: :exc:`~b2handle.handleexceptions.HandleNotFoundException`
:raises: :exc:`~b2handle.handleexceptions.HandleSyntaxError`
|
entailment
|
def delete_handle_value(self, handle, key):
'''
Delete a key-value pair from a handle record. If the key exists more
than once, all key-value pairs with this key are deleted.
:param handle: Handle from whose record the entry should be deleted.
:param key: Key to be deleted. Also accepts a list of keys.
:raises: :exc:`~b2handle.handleexceptions.HandleAuthenticationError`
:raises: :exc:`~b2handle.handleexceptions.HandleNotFoundException`
:raises: :exc:`~b2handle.handleexceptions.HandleSyntaxError`
'''
LOGGER.debug('delete_handle_value...')
# read handle record:
handlerecord_json = self.retrieve_handle_record_json(handle)
if handlerecord_json is None:
msg = 'Cannot modify unexisting handle'
raise HandleNotFoundException(handle=handle, msg=msg)
list_of_entries = handlerecord_json['values']
# find indices to delete:
keys = None
indices = []
if type(key) != type([]):
keys = [key]
else:
keys = key
keys_done = []
for key in keys:
# filter HS_ADMIN
if key == 'HS_ADMIN':
op = 'deleting "HS_ADMIN"'
raise IllegalOperationException(operation=op, handle=handle)
if key not in keys_done:
indices_onekey = self.get_handlerecord_indices_for_key(key, list_of_entries)
indices = indices + indices_onekey
keys_done.append(key)
# Important: If key not found, do not continue, as deleting without indices would delete the entire handle!!
if not len(indices) > 0:
LOGGER.debug('delete_handle_value: No values for key(s) ' + str(keys))
return None
else:
# delete and process response:
op = 'deleting "' + str(keys) + '"'
resp = self.__send_handle_delete_request(handle, indices=indices, op=op)
if hsresponses.handle_success(resp):
LOGGER.debug("delete_handle_value: Deleted handle values " + str(keys) + "of handle " + handle)
elif hsresponses.values_not_found(resp):
pass
else:
raise GenericHandleError(
operation=op,
handle=handle,
response=resp
)
|
Delete a key-value pair from a handle record. If the key exists more
than once, all key-value pairs with this key are deleted.
:param handle: Handle from whose record the entry should be deleted.
:param key: Key to be deleted. Also accepts a list of keys.
:raises: :exc:`~b2handle.handleexceptions.HandleAuthenticationError`
:raises: :exc:`~b2handle.handleexceptions.HandleNotFoundException`
:raises: :exc:`~b2handle.handleexceptions.HandleSyntaxError`
|
entailment
|
def delete_handle(self, handle, *other):
'''Delete the handle and its handle record. If the Handle is not found, an Exception is raised.
:param handle: Handle to be deleted.
:param other: Deprecated. This only exists to catch wrong method usage
by users who are used to delete handle VALUES with the method.
:raises: :exc:`~b2handle.handleexceptions.HandleAuthenticationError`
:raises: :exc:`~b2handle.handleexceptions.HandleNotFoundException`
:raises: :exc:`~b2handle.handleexceptions.HandleSyntaxError`
'''
LOGGER.debug('delete_handle...')
utilhandle.check_handle_syntax(handle)
# Safety check. In old epic client, the method could be used for
# deleting handle values (not entire handle) by specifying more
# parameters.
if len(other) > 0:
message = 'You specified more than one argument. If you wanted' + \
' to delete just some values from a handle, please use the' + \
' new method "delete_handle_value()".'
raise TypeError(message)
op = 'deleting handle'
resp = self.__send_handle_delete_request(handle, op=op)
if hsresponses.handle_success(resp):
LOGGER.info('Handle ' + handle + ' deleted.')
elif hsresponses.handle_not_found(resp):
msg = ('delete_handle: Handle ' + handle + ' did not exist, '
'so it could not be deleted.')
LOGGER.debug(msg)
raise HandleNotFoundException(msg=msg, handle=handle, response=resp)
else:
raise GenericHandleError(op=op, handle=handle, response=resp)
|
Delete the handle and its handle record. If the Handle is not found, an Exception is raised.
:param handle: Handle to be deleted.
:param other: Deprecated. This only exists to catch wrong method usage
by users who are used to delete handle VALUES with the method.
:raises: :exc:`~b2handle.handleexceptions.HandleAuthenticationError`
:raises: :exc:`~b2handle.handleexceptions.HandleNotFoundException`
:raises: :exc:`~b2handle.handleexceptions.HandleSyntaxError`
|
entailment
|
def exchange_additional_URL(self, handle, old, new):
'''
Exchange an URL in the 10320/LOC entry against another, keeping the same id
and other attributes.
:param handle: The handle to modify.
:param old: The URL to replace.
:param new: The URL to set as new URL.
'''
LOGGER.debug('exchange_additional_URL...')
handlerecord_json = self.retrieve_handle_record_json(handle)
if handlerecord_json is None:
msg = 'Cannot exchange URLs in unexisting handle'
raise HandleNotFoundException(
handle=handle,
msg=msg
)
list_of_entries = handlerecord_json['values']
if not self.is_URL_contained_in_10320LOC(handle, old, handlerecord_json):
LOGGER.debug('exchange_additional_URL: No URLs exchanged, as the url was not in the record.')
else:
self.__exchange_URL_in_13020loc(old, new, list_of_entries, handle)
op = 'exchanging URLs'
resp, put_payload = self.__send_handle_put_request(
handle,
list_of_entries,
overwrite=True,
op=op
)
# TODO FIXME (one day): Implement overwriting by index (less risky)
if hsresponses.handle_success(resp):
pass
else:
msg = 'Could not exchange URL ' + str(old) + ' against ' + str(new)
raise GenericHandleError(
operation=op,
handle=handle,
reponse=resp,
msg=msg,
payload=put_payload
)
|
Exchange an URL in the 10320/LOC entry against another, keeping the same id
and other attributes.
:param handle: The handle to modify.
:param old: The URL to replace.
:param new: The URL to set as new URL.
|
entailment
|
def add_additional_URL(self, handle, *urls, **attributes):
'''
Add a URL entry to the handle record's 10320/LOC entry. If 10320/LOC
does not exist yet, it is created. If the 10320/LOC entry already
contains the URL, it is not added a second time.
:param handle: The handle to add the URL to.
:param urls: The URL(s) to be added. Several URLs may be specified.
:param attributes: Optional. Additional key-value pairs to set as
attributes to the <location> elements, e.g. weight, http_role or
custom attributes. Note: If the URL already exists but the
attributes are different, they are updated!
:raises: :exc:`~b2handle.handleexceptions.HandleNotFoundException`
:raises: :exc:`~b2handle.handleexceptions.HandleSyntaxError`
:raises: :exc:`~b2handle.handleexceptions.HandleAuthenticationError`
'''
LOGGER.debug('add_additional_URL...')
handlerecord_json = self.retrieve_handle_record_json(handle)
if handlerecord_json is None:
msg = 'Cannot add URLS to unexisting handle!'
raise HandleNotFoundException(handle=handle, msg=msg)
list_of_entries = handlerecord_json['values']
is_new = False
for url in urls:
if not self.is_URL_contained_in_10320LOC(handle, url, handlerecord_json):
is_new = True
if not is_new:
LOGGER.debug("add_additional_URL: No new URL to be added (so no URL is added at all).")
else:
for url in urls:
self.__add_URL_to_10320LOC(url, list_of_entries, handle)
op = 'adding URLs'
resp, put_payload = self.__send_handle_put_request(handle, list_of_entries, overwrite=True, op=op)
# TODO FIXME (one day) Overwrite by index.
if hsresponses.handle_success(resp):
pass
else:
msg = 'Could not add URLs ' + str(urls)
raise GenericHandleError(
operation=op,
handle=handle,
reponse=resp,
msg=msg,
payload=put_payload
)
|
Add a URL entry to the handle record's 10320/LOC entry. If 10320/LOC
does not exist yet, it is created. If the 10320/LOC entry already
contains the URL, it is not added a second time.
:param handle: The handle to add the URL to.
:param urls: The URL(s) to be added. Several URLs may be specified.
:param attributes: Optional. Additional key-value pairs to set as
attributes to the <location> elements, e.g. weight, http_role or
custom attributes. Note: If the URL already exists but the
attributes are different, they are updated!
:raises: :exc:`~b2handle.handleexceptions.HandleNotFoundException`
:raises: :exc:`~b2handle.handleexceptions.HandleSyntaxError`
:raises: :exc:`~b2handle.handleexceptions.HandleAuthenticationError`
|
entailment
|
def remove_additional_URL(self, handle, *urls):
'''
Remove a URL from the handle record's 10320/LOC entry.
:param handle: The handle to modify.
:param urls: The URL(s) to be removed. Several URLs may be specified.
:raises: :exc:`~b2handle.handleexceptions.HandleNotFoundException`
:raises: :exc:`~b2handle.handleexceptions.HandleSyntaxError`
:raises: :exc:`~b2handle.handleexceptions.HandleAuthenticationError`
'''
LOGGER.debug('remove_additional_URL...')
handlerecord_json = self.retrieve_handle_record_json(handle)
if handlerecord_json is None:
msg = 'Cannot remove URLs from unexisting handle'
raise HandleNotFoundException(handle=handle, msg=msg)
list_of_entries = handlerecord_json['values']
for url in urls:
self.__remove_URL_from_10320LOC(url, list_of_entries, handle)
op = 'removing URLs'
resp, put_payload = self.__send_handle_put_request(
handle,
list_of_entries,
overwrite=True,
op=op
)
# TODO FIXME (one day): Implement overwriting by index (less risky),
# once HS have fixed the issue with the indices.
if hsresponses.handle_success(resp):
pass
else:
op = 'removing "' + str(urls) + '"'
msg = 'Could not remove URLs ' + str(urls)
raise GenericHandleError(
operation=op,
handle=handle,
reponse=resp,
msg=msg,
payload=put_payload
)
|
Remove a URL from the handle record's 10320/LOC entry.
:param handle: The handle to modify.
:param urls: The URL(s) to be removed. Several URLs may be specified.
:raises: :exc:`~b2handle.handleexceptions.HandleNotFoundException`
:raises: :exc:`~b2handle.handleexceptions.HandleSyntaxError`
:raises: :exc:`~b2handle.handleexceptions.HandleAuthenticationError`
|
entailment
|
def register_handle(self, handle, location, checksum=None, additional_URLs=None, overwrite=False, **extratypes):
'''
Registers a new Handle with given name. If the handle already exists
and overwrite is not set to True, the method will throw an
exception.
:param handle: The full name of the handle to be registered (prefix
and suffix)
:param location: The URL of the data entity to be referenced
:param checksum: Optional. The checksum string.
:param extratypes: Optional. Additional key value pairs.
:param additional_URLs: Optional. A list of URLs (as strings) to be
added to the handle record as 10320/LOC entry.
:param overwrite: Optional. If set to True, an existing handle record
will be overwritten. Defaults to False.
:raises: :exc:`~b2handle.handleexceptions.HandleAlreadyExistsException` Only if overwrite is not set or
set to False.
:raises: :exc:`~b2handle.handleexceptions.HandleAuthenticationError`
:raises: :exc:`~b2handle.handleexceptions.HandleSyntaxError`
:return: The handle name.
'''
LOGGER.debug('register_handle...')
# If already exists and can't be overwritten:
if overwrite == False:
handlerecord_json = self.retrieve_handle_record_json(handle)
if handlerecord_json is not None:
msg = 'Could not register handle'
LOGGER.error(msg + ', as it already exists.')
raise HandleAlreadyExistsException(handle=handle, msg=msg)
# Create admin entry
list_of_entries = []
adminentry = self.__create_admin_entry(
self.__handleowner,
self.__HS_ADMIN_permissions,
self.__make_another_index(list_of_entries, hs_admin=True),
handle
)
list_of_entries.append(adminentry)
# Create other entries
entry_URL = self.__create_entry(
'URL',
location,
self.__make_another_index(list_of_entries, url=True)
)
list_of_entries.append(entry_URL)
if checksum is not None:
entryChecksum = self.__create_entry(
'CHECKSUM',
checksum,
self.__make_another_index(list_of_entries)
)
list_of_entries.append(entryChecksum)
if extratypes is not None:
for key, value in extratypes.items():
entry = self.__create_entry(
key,
value,
self.__make_another_index(list_of_entries)
)
list_of_entries.append(entry)
if additional_URLs is not None and len(additional_URLs) > 0:
for url in additional_URLs:
self.__add_URL_to_10320LOC(url, list_of_entries, handle)
# Create record itself and put to server
op = 'registering handle'
resp, put_payload = self.__send_handle_put_request(
handle,
list_of_entries,
overwrite=overwrite,
op=op
)
resp_content = decoded_response(resp)
if hsresponses.was_handle_created(resp) or hsresponses.handle_success(resp):
LOGGER.info("Handle registered: " + handle)
return json.loads(resp_content)['handle']
elif hsresponses.is_temporary_redirect(resp):
oldurl = resp.url
newurl = resp.headers['location']
raise GenericHandleError(
operation=op,
handle=handle,
response=resp,
payload=put_payload,
msg='Temporary redirect from ' + oldurl + ' to ' + newurl + '.'
)
elif hsresponses.handle_not_found(resp):
raise GenericHandleError(
operation=op,
handle=handle,
response=resp,
payload=put_payload,
msg='Could not create handle. Possibly you used HTTP instead of HTTPS?'
)
else:
raise GenericHandleError(
operation=op,
handle=handle,
reponse=resp,
payload=put_payload
)
|
Registers a new Handle with given name. If the handle already exists
and overwrite is not set to True, the method will throw an
exception.
:param handle: The full name of the handle to be registered (prefix
and suffix)
:param location: The URL of the data entity to be referenced
:param checksum: Optional. The checksum string.
:param extratypes: Optional. Additional key value pairs.
:param additional_URLs: Optional. A list of URLs (as strings) to be
added to the handle record as 10320/LOC entry.
:param overwrite: Optional. If set to True, an existing handle record
will be overwritten. Defaults to False.
:raises: :exc:`~b2handle.handleexceptions.HandleAlreadyExistsException` Only if overwrite is not set or
set to False.
:raises: :exc:`~b2handle.handleexceptions.HandleAuthenticationError`
:raises: :exc:`~b2handle.handleexceptions.HandleSyntaxError`
:return: The handle name.
|
entailment
|
def search_handle(self, URL=None, prefix=None, **key_value_pairs):
'''
Search for handles containing the specified key with the specified
value. The search terms are passed on to the reverse lookup servlet
as-is. The servlet is supposed to be case-insensitive, but if it
isn't, the wrong case will cause a :exc:`~b2handle.handleexceptions.ReverseLookupException`.
*Note:* If allowed search keys are configured, only these are used. If
no allowed search keys are specified, all key-value pairs are
passed on to the reverse lookup servlet, possibly causing a
:exc:`~b2handle.handleexceptions.ReverseLookupException`.
Example calls:
.. code:: python
list_of_handles = search_handle('http://www.foo.com')
list_of_handles = search_handle('http://www.foo.com', CHECKSUM=99999)
list_of_handles = search_handle(URL='http://www.foo.com', CHECKSUM=99999)
:param URL: Optional. The URL to search for (reverse lookup). [This is
NOT the URL of the search servlet!]
:param prefix: Optional. The Handle prefix to which the search should
be limited to. If unspecified, the method will search across all
prefixes present at the server given to the constructor.
:param key_value_pairs: Optional. Several search fields and values can
be specified as key-value-pairs,
e.g. CHECKSUM=123456, URL=www.foo.com
:raise: :exc:`~b2handle.handleexceptions.ReverseLookupException`: If a search field is specified that
cannot be used, or if something else goes wrong.
:return: A list of all Handles (strings) that bear the given key with
given value of given prefix or server. The list may be empty and
may also contain more than one element.
'''
LOGGER.debug('search_handle...')
list_of_handles = self.__searcher.search_handle(URL=URL, prefix=prefix, **key_value_pairs)
return list_of_handles
|
Search for handles containing the specified key with the specified
value. The search terms are passed on to the reverse lookup servlet
as-is. The servlet is supposed to be case-insensitive, but if it
isn't, the wrong case will cause a :exc:`~b2handle.handleexceptions.ReverseLookupException`.
*Note:* If allowed search keys are configured, only these are used. If
no allowed search keys are specified, all key-value pairs are
passed on to the reverse lookup servlet, possibly causing a
:exc:`~b2handle.handleexceptions.ReverseLookupException`.
Example calls:
.. code:: python
list_of_handles = search_handle('http://www.foo.com')
list_of_handles = search_handle('http://www.foo.com', CHECKSUM=99999)
list_of_handles = search_handle(URL='http://www.foo.com', CHECKSUM=99999)
:param URL: Optional. The URL to search for (reverse lookup). [This is
NOT the URL of the search servlet!]
:param prefix: Optional. The Handle prefix to which the search should
be limited to. If unspecified, the method will search across all
prefixes present at the server given to the constructor.
:param key_value_pairs: Optional. Several search fields and values can
be specified as key-value-pairs,
e.g. CHECKSUM=123456, URL=www.foo.com
:raise: :exc:`~b2handle.handleexceptions.ReverseLookupException`: If a search field is specified that
cannot be used, or if something else goes wrong.
:return: A list of all Handles (strings) that bear the given key with
given value of given prefix or server. The list may be empty and
may also contain more than one element.
|
entailment
|
def generate_PID_name(self, prefix=None):
'''
Generate a unique random Handle name (random UUID). The Handle is not
registered. If a prefix is specified, the PID name has the syntax
<prefix>/<generatedname>, otherwise it just returns the generated
random name (suffix for the Handle).
:param prefix: Optional. The prefix to be used for the Handle name.
:return: The handle name in the form <prefix>/<generatedsuffix> or
<generatedsuffix>.
'''
LOGGER.debug('generate_PID_name...')
randomuuid = uuid.uuid4()
if prefix is not None:
return prefix + '/' + str(randomuuid)
else:
return str(randomuuid)
|
Generate a unique random Handle name (random UUID). The Handle is not
registered. If a prefix is specified, the PID name has the syntax
<prefix>/<generatedname>, otherwise it just returns the generated
random name (suffix for the Handle).
:param prefix: Optional. The prefix to be used for the Handle name.
:return: The handle name in the form <prefix>/<generatedsuffix> or
<generatedsuffix>.
|
entailment
|
def get_handlerecord_indices_for_key(self, key, list_of_entries):
'''
Finds the Handle entry indices of all entries that have a specific
type.
*Important:* It finds the Handle System indices! These are not
the python indices of the list, so they can not be used for
iteration.
:param key: The key (Handle Record type)
:param list_of_entries: A list of the existing entries in which to find
the indices.
:return: A list of strings, the indices of the entries of type "key" in
the given handle record.
'''
LOGGER.debug('get_handlerecord_indices_for_key...')
indices = []
for entry in list_of_entries:
if entry['type'] == key:
indices.append(entry['index'])
return indices
|
Finds the Handle entry indices of all entries that have a specific
type.
*Important:* It finds the Handle System indices! These are not
the python indices of the list, so they can not be used for
iteration.
:param key: The key (Handle Record type)
:param list_of_entries: A list of the existing entries in which to find
the indices.
:return: A list of strings, the indices of the entries of type "key" in
the given handle record.
|
entailment
|
def __send_handle_delete_request(self, handle, indices=None, op=None):
'''
Send a HTTP DELETE request to the handle server to delete either an
entire handle or to some specified values from a handle record,
using the requests module.
:param handle: The handle.
:param indices: Optional. A list of indices to delete. Defaults to
None (i.e. the entire handle is deleted.). The list can contain
integers or strings.
:return: The server's response.
'''
resp = self.__handlesystemconnector.send_handle_delete_request(
handle=handle,
indices=indices,
op=op)
return resp
|
Send a HTTP DELETE request to the handle server to delete either an
entire handle or to some specified values from a handle record,
using the requests module.
:param handle: The handle.
:param indices: Optional. A list of indices to delete. Defaults to
None (i.e. the entire handle is deleted.). The list can contain
integers or strings.
:return: The server's response.
|
entailment
|
def __send_handle_put_request(self, handle, list_of_entries, indices=None, overwrite=False, op=None):
'''
Send a HTTP PUT request to the handle server to write either an entire
handle or to some specified values to an handle record, using the
requests module.
:param handle: The handle.
:param list_of_entries: A list of handle record entries to be written,
in the format [{"index":xyz, "type":"xyz", "data":"xyz"}] or similar.
:param indices: Optional. A list of indices to modify. Defaults
to None (i.e. the entire handle is updated.). The list can
contain integers or strings.
:param overwrite: Optional. Whether the handle should be overwritten
if it exists already.
:return: The server's response.
'''
resp, payload = self.__handlesystemconnector.send_handle_put_request(
handle=handle,
list_of_entries=list_of_entries,
indices=indices,
overwrite=overwrite,
op=op
)
return resp, payload
|
Send a HTTP PUT request to the handle server to write either an entire
handle or to some specified values to an handle record, using the
requests module.
:param handle: The handle.
:param list_of_entries: A list of handle record entries to be written,
in the format [{"index":xyz, "type":"xyz", "data":"xyz"}] or similar.
:param indices: Optional. A list of indices to modify. Defaults
to None (i.e. the entire handle is updated.). The list can
contain integers or strings.
:param overwrite: Optional. Whether the handle should be overwritten
if it exists already.
:return: The server's response.
|
entailment
|
def __send_handle_get_request(self, handle, indices=None):
'''
Send a HTTP GET request to the handle server to read either an entire
handle or to some specified values from a handle record, using the
requests module.
:param handle: The handle.
:param indices: Optional. A list of indices to delete. Defaults to
None (i.e. the entire handle is deleted.). The list can contain
integers or strings.
:return: The server's response.
'''
resp = self.__handlesystemconnector.send_handle_get_request(handle, indices)
return resp
|
Send a HTTP GET request to the handle server to read either an entire
handle or to some specified values from a handle record, using the
requests module.
:param handle: The handle.
:param indices: Optional. A list of indices to delete. Defaults to
None (i.e. the entire handle is deleted.). The list can contain
integers or strings.
:return: The server's response.
|
entailment
|
def __get_handle_record_if_necessary(self, handle, handlerecord_json):
'''
Returns the handle record if it is None or if its handle is not the
same as the specified handle.
'''
if handlerecord_json is None:
handlerecord_json = self.retrieve_handle_record_json(handle)
else:
if handle != handlerecord_json['handle']:
handlerecord_json = self.retrieve_handle_record_json(handle)
return handlerecord_json
|
Returns the handle record if it is None or if its handle is not the
same as the specified handle.
|
entailment
|
def __make_another_index(self, list_of_entries, url=False, hs_admin=False):
'''
Find an index not yet used in the handle record and not reserved for
any (other) special type.
:param: list_of_entries: List of all entries to find which indices are
used already.
:param url: If True, an index for an URL entry is returned (1, unless
it is already in use).
:param hs_admin: If True, an index for HS_ADMIN is returned (100 or one
of the following).
:return: An integer.
'''
start = 2
# reserved indices:
reserved_for_url = set([1])
reserved_for_admin = set(range(100, 200))
prohibited_indices = reserved_for_url | reserved_for_admin
if url:
prohibited_indices = prohibited_indices - reserved_for_url
start = 1
elif hs_admin:
prohibited_indices = prohibited_indices - reserved_for_admin
start = 100
# existing indices
existing_indices = set()
if list_of_entries is not None:
for entry in list_of_entries:
existing_indices.add(int(entry['index']))
# find new index:
all_prohibited_indices = existing_indices | prohibited_indices
searchmax = max(start, max(all_prohibited_indices)) + 2
for index in xrange(start, searchmax):
if index not in all_prohibited_indices:
return index
|
Find an index not yet used in the handle record and not reserved for
any (other) special type.
:param: list_of_entries: List of all entries to find which indices are
used already.
:param url: If True, an index for an URL entry is returned (1, unless
it is already in use).
:param hs_admin: If True, an index for HS_ADMIN is returned (100 or one
of the following).
:return: An integer.
|
entailment
|
def __create_entry(self, entrytype, data, index, ttl=None):
'''
Create an entry of any type except HS_ADMIN.
:param entrytype: THe type of entry to create, e.g. 'URL' or
'checksum' or ... Note: For entries of type 'HS_ADMIN', please
use __create_admin_entry(). For type '10320/LOC', please use
'add_additional_URL()'
:param data: The actual value for the entry. Can be a simple string,
e.g. "example", or a dict {"format":"string", "value":"example"}.
:param index: The integer to be used as index.
:param ttl: Optional. If not set, the library's default is set. If
there is no default, it is not set by this library, so Handle
System sets it.
:return: The entry as a dict.
'''
if entrytype == 'HS_ADMIN':
op = 'creating HS_ADMIN entry'
msg = 'This method can not create HS_ADMIN entries.'
raise IllegalOperationException(operation=op, msg=msg)
entry = {'index':index, 'type':entrytype, 'data':data}
if ttl is not None:
entry['ttl'] = ttl
return entry
|
Create an entry of any type except HS_ADMIN.
:param entrytype: THe type of entry to create, e.g. 'URL' or
'checksum' or ... Note: For entries of type 'HS_ADMIN', please
use __create_admin_entry(). For type '10320/LOC', please use
'add_additional_URL()'
:param data: The actual value for the entry. Can be a simple string,
e.g. "example", or a dict {"format":"string", "value":"example"}.
:param index: The integer to be used as index.
:param ttl: Optional. If not set, the library's default is set. If
there is no default, it is not set by this library, so Handle
System sets it.
:return: The entry as a dict.
|
entailment
|
def __create_admin_entry(self, handleowner, permissions, index, handle, ttl=None):
'''
Create an entry of type "HS_ADMIN".
:param username: The username, i.e. a handle with an index
(index:prefix/suffix). The value referenced by the index contains
authentcation information, e.g. a hidden entry containing a key.
:param permissions: The permissions as a string of zeros and ones,
e.g. '0111011101011'. If not all twelve bits are set, the remaining
ones are set to zero.
:param index: The integer to be used as index of this admin entry (not
of the username!). Should be 1xx.
:param ttl: Optional. If not set, the library's default is set. If
there is no default, it is not set by this library, so Handle
System sets it.
:return: The entry as a dict.
'''
# If the handle owner is specified, use it. Otherwise, use 200:0.NA/prefix
# With the prefix taken from the handle that is being created, not from anywhere else.
if handleowner is None:
adminindex = '200'
prefix = handle.split('/')[0]
adminhandle = '0.NA/' + prefix
else:
adminindex, adminhandle = utilhandle.remove_index_from_handle(handleowner)
data = {
'value':{
'index':adminindex,
'handle':adminhandle,
'permissions':permissions
},
'format':'admin'
}
entry = {'index':index, 'type':'HS_ADMIN', 'data':data}
if ttl is not None:
entry['ttl'] = ttl
return entry
|
Create an entry of type "HS_ADMIN".
:param username: The username, i.e. a handle with an index
(index:prefix/suffix). The value referenced by the index contains
authentcation information, e.g. a hidden entry containing a key.
:param permissions: The permissions as a string of zeros and ones,
e.g. '0111011101011'. If not all twelve bits are set, the remaining
ones are set to zero.
:param index: The integer to be used as index of this admin entry (not
of the username!). Should be 1xx.
:param ttl: Optional. If not set, the library's default is set. If
there is no default, it is not set by this library, so Handle
System sets it.
:return: The entry as a dict.
|
entailment
|
def __get_python_indices_for_key(self, key, list_of_entries):
'''
Finds the indices of all entries that have a specific type. Important:
This method finds the python indices of the list of entries! These
are not the Handle System index values!
:param key: The key (Handle Record type)
:param list_of_entries: A list of the existing entries in which to find
the indices.
:return: A list of integers, the indices of the entries of type "key"
in the given list.
'''
indices = []
for i in xrange(len(list_of_entries)):
if list_of_entries[i]['type'] == key:
indices.append(i)
return indices
|
Finds the indices of all entries that have a specific type. Important:
This method finds the python indices of the list of entries! These
are not the Handle System index values!
:param key: The key (Handle Record type)
:param list_of_entries: A list of the existing entries in which to find
the indices.
:return: A list of integers, the indices of the entries of type "key"
in the given list.
|
entailment
|
def __exchange_URL_in_13020loc(self, oldurl, newurl, list_of_entries, handle):
'''
Exchange every occurrence of oldurl against newurl in a 10320/LOC entry.
This does not change the ids or other xml attributes of the
<location> element.
:param oldurl: The URL that will be overwritten.
:param newurl: The URL to write into the entry.
:param list_of_entries: A list of the existing entries (to find and
remove the correct one).
:param handle: Only for the exception message.
:raise: GenericHandleError: If several 10320/LOC exist (unlikely).
'''
# Find existing 10320/LOC entries
python_indices = self.__get_python_indices_for_key(
'10320/LOC',
list_of_entries
)
num_exchanged = 0
if len(python_indices) > 0:
if len(python_indices) > 1:
msg = str(len(python_indices)) + ' entries of type "10320/LOC".'
raise BrokenHandleRecordException(handle=handle, msg=msg)
for index in python_indices:
entry = list_of_entries.pop(index)
xmlroot = ET.fromstring(entry['data']['value'])
all_URL_elements = xmlroot.findall('location')
for element in all_URL_elements:
if element.get('href') == oldurl:
LOGGER.debug('__exchange_URL_in_13020loc: Exchanging URL ' + oldurl + ' from 10320/LOC.')
num_exchanged += 1
element.set('href', newurl)
entry['data']['value'] = ET.tostring(xmlroot, encoding=encoding_value)
list_of_entries.append(entry)
if num_exchanged == 0:
LOGGER.debug('__exchange_URL_in_13020loc: No URLs exchanged.')
else:
message = '__exchange_URL_in_13020loc: The URL "' + oldurl + '" was exchanged ' + str(num_exchanged) + \
' times against the new url "' + newurl + '" in 10320/LOC.'
message = message.replace('1 times', 'once')
LOGGER.debug(message)
|
Exchange every occurrence of oldurl against newurl in a 10320/LOC entry.
This does not change the ids or other xml attributes of the
<location> element.
:param oldurl: The URL that will be overwritten.
:param newurl: The URL to write into the entry.
:param list_of_entries: A list of the existing entries (to find and
remove the correct one).
:param handle: Only for the exception message.
:raise: GenericHandleError: If several 10320/LOC exist (unlikely).
|
entailment
|
def __remove_URL_from_10320LOC(self, url, list_of_entries, handle):
'''
Remove an URL from the handle record's "10320/LOC" entry.
If it exists several times in the entry, all occurences are removed.
If the URL is not present, nothing happens.
If after removing, there is no more URLs in the entry, the entry is
removed.
:param url: The URL to be removed.
:param list_of_entries: A list of the existing entries (to find and
remove the correct one).
:param handle: Only for the exception message.
:raise: GenericHandleError: If several 10320/LOC exist (unlikely).
'''
# Find existing 10320/LOC entries
python_indices = self.__get_python_indices_for_key(
'10320/LOC',
list_of_entries
)
num_removed = 0
if len(python_indices) > 0:
if len(python_indices) > 1:
msg = str(len(python_indices)) + ' entries of type "10320/LOC".'
raise BrokenHandleRecordException(handle=handle, msg=msg)
for index in python_indices:
entry = list_of_entries.pop(index)
xmlroot = ET.fromstring(entry['data']['value'])
all_URL_elements = xmlroot.findall('location')
for element in all_URL_elements:
if element.get('href') == url:
LOGGER.debug('__remove_URL_from_10320LOC: Removing URL ' + url + '.')
num_removed += 1
xmlroot.remove(element)
remaining_URL_elements = xmlroot.findall('location')
if len(remaining_URL_elements) == 0:
LOGGER.debug("__remove_URL_from_10320LOC: All URLs removed.")
# TODO FIXME: If we start adapting the Handle Record by
# index (instead of overwriting the entire one), be careful
# to delete the ones that became empty!
else:
entry['data']['value'] = ET.tostring(xmlroot, encoding=encoding_value)
LOGGER.debug('__remove_URL_from_10320LOC: ' + str(len(remaining_URL_elements)) + ' URLs' + \
' left after removal operation.')
list_of_entries.append(entry)
if num_removed == 0:
LOGGER.debug('__remove_URL_from_10320LOC: No URLs removed.')
else:
message = '__remove_URL_from_10320LOC: The URL "' + url + '" was removed '\
+ str(num_removed) + ' times.'
message = message.replace('1 times', 'once')
LOGGER.debug(message)
|
Remove an URL from the handle record's "10320/LOC" entry.
If it exists several times in the entry, all occurences are removed.
If the URL is not present, nothing happens.
If after removing, there is no more URLs in the entry, the entry is
removed.
:param url: The URL to be removed.
:param list_of_entries: A list of the existing entries (to find and
remove the correct one).
:param handle: Only for the exception message.
:raise: GenericHandleError: If several 10320/LOC exist (unlikely).
|
entailment
|
def __add_URL_to_10320LOC(self, url, list_of_entries, handle=None, weight=None, http_role=None, **kvpairs):
'''
Add a url to the handle record's "10320/LOC" entry.
If no 10320/LOC entry exists, a new one is created (using the
default "chooseby" attribute, if configured).
If the URL is already present, it is not added again, but
the attributes (e.g. weight) are updated/added.
If the existing 10320/LOC entry is mal-formed, an exception will be
thrown (xml.etree.ElementTree.ParseError)
Note: In the unlikely case that several "10320/LOC" entries exist,
an exception is raised.
:param url: The URL to be added.
:param list_of_entries: A list of the existing entries (to find and
adapt the correct one).
:param weight: Optional. The weight to be set (integer between 0 and
1). If None, no weight attribute is set. If the value is outside
the accepted range, it is set to 1.
:param http_role: Optional. The http_role to be set. This accepts any
string. Currently, Handle System can process 'conneg'. In future,
it may be able to process 'no_conneg' and 'browser'.
:param handle: Optional. Only for the exception message.
:param all others: Optional. All other key-value pairs will be set to
the element. Any value is accepted and transformed to string.
:raise: GenericHandleError: If several 10320/LOC exist (unlikely).
'''
# Find existing 10320/LOC entry or create new
indices = self.__get_python_indices_for_key('10320/LOC', list_of_entries)
makenew = False
entry = None
if len(indices) == 0:
index = self.__make_another_index(list_of_entries)
entry = self.__create_entry('10320/LOC', 'add_later', index)
makenew = True
else:
if len(indices) > 1:
msg = 'There is ' + str(len(indices)) + ' 10320/LOC entries.'
raise BrokenHandleRecordException(handle=handle, msg=msg)
ind = indices[0]
entry = list_of_entries.pop(ind)
# Get xml data or make new:
xmlroot = None
if makenew:
xmlroot = ET.Element('locations')
if self.__10320LOC_chooseby is not None:
xmlroot.set('chooseby', self.__10320LOC_chooseby)
else:
try:
xmlroot = ET.fromstring(entry['data']['value'])
except TypeError:
xmlroot = ET.fromstring(entry['data'])
LOGGER.debug("__add_URL_to_10320LOC: xmlroot is (1) " + ET.tostring(xmlroot, encoding=encoding_value))
# Check if URL already there...
location_element = None
existing_location_ids = []
if not makenew:
list_of_locations = xmlroot.findall('location')
for item in list_of_locations:
try:
existing_location_ids.append(int(item.get('id')))
except TypeError:
pass
if item.get('href') == url:
location_element = item
existing_location_ids.sort()
# ... if not, add it!
if location_element is None:
location_id = 0
for existing_id in existing_location_ids:
if location_id == existing_id:
location_id += 1
location_element = ET.SubElement(xmlroot, 'location')
LOGGER.debug("__add_URL_to_10320LOC: location_element is (1) " + ET.tostring(location_element, encoding=encoding_value) + ', now add id ' + str(location_id))
location_element.set('id', str(location_id))
LOGGER.debug("__add_URL_to_10320LOC: location_element is (2) " + ET.tostring(location_element, encoding=encoding_value) + ', now add url ' + str(url))
location_element.set('href', url)
LOGGER.debug("__add_URL_to_10320LOC: location_element is (3) " + ET.tostring(location_element, encoding=encoding_value))
self.__set_or_adapt_10320LOC_attributes(location_element, weight, http_role, **kvpairs)
# FIXME: If we start adapting the Handle Record by index (instead of
# overwriting the entire one), be careful to add and/or overwrite!
# (Re-)Add entire 10320 to entry, add entry to list of entries:
LOGGER.debug("__add_URL_to_10320LOC: xmlroot is (2) " + ET.tostring(xmlroot, encoding=encoding_value))
entry['data'] = ET.tostring(xmlroot, encoding=encoding_value)
list_of_entries.append(entry)
|
Add a url to the handle record's "10320/LOC" entry.
If no 10320/LOC entry exists, a new one is created (using the
default "chooseby" attribute, if configured).
If the URL is already present, it is not added again, but
the attributes (e.g. weight) are updated/added.
If the existing 10320/LOC entry is mal-formed, an exception will be
thrown (xml.etree.ElementTree.ParseError)
Note: In the unlikely case that several "10320/LOC" entries exist,
an exception is raised.
:param url: The URL to be added.
:param list_of_entries: A list of the existing entries (to find and
adapt the correct one).
:param weight: Optional. The weight to be set (integer between 0 and
1). If None, no weight attribute is set. If the value is outside
the accepted range, it is set to 1.
:param http_role: Optional. The http_role to be set. This accepts any
string. Currently, Handle System can process 'conneg'. In future,
it may be able to process 'no_conneg' and 'browser'.
:param handle: Optional. Only for the exception message.
:param all others: Optional. All other key-value pairs will be set to
the element. Any value is accepted and transformed to string.
:raise: GenericHandleError: If several 10320/LOC exist (unlikely).
|
entailment
|
def __set_or_adapt_10320LOC_attributes(self, locelement, weight=None, http_role=None, **kvpairs):
'''
Adds or updates attributes of a <location> element. Existing attributes
are not removed!
:param locelement: A location element as xml snippet
(xml.etree.ElementTree.Element).
:param weight: Optional. The weight to be set (integer between 0 and
1). If None, no weight attribute is set. If the value is outside
the accepted range, it is set to 1.
:param http_role: Optional. The http_role to be set. This accepts any
string. Currently, Handle System can process 'conneg'. In future,
it may be able to process 'no_conneg' and 'browser'.
:param all others: Optional. All other key-value pairs will be set to
the element. Any value is accepted and transformed to string.
'''
if weight is not None:
LOGGER.debug('__set_or_adapt_10320LOC_attributes: weight (' + str(type(weight)) + '): ' + str(weight))
weight = float(weight)
if weight < 0 or weight > 1:
default = 1
LOGGER.debug('__set_or_adapt_10320LOC_attributes: Invalid weight (' + str(weight) + \
'), using default value (' + str(default) + ') instead.')
weight = default
weight = str(weight)
locelement.set('weight', weight)
if http_role is not None:
locelement.set('http_role', http_role)
for key, value in kvpairs.items():
locelement.set(key, str(value))
|
Adds or updates attributes of a <location> element. Existing attributes
are not removed!
:param locelement: A location element as xml snippet
(xml.etree.ElementTree.Element).
:param weight: Optional. The weight to be set (integer between 0 and
1). If None, no weight attribute is set. If the value is outside
the accepted range, it is set to 1.
:param http_role: Optional. The http_role to be set. This accepts any
string. Currently, Handle System can process 'conneg'. In future,
it may be able to process 'no_conneg' and 'browser'.
:param all others: Optional. All other key-value pairs will be set to
the element. Any value is accepted and transformed to string.
|
entailment
|
def authorize_url(self):
"""
authorization url
request weibo authorization url
:return:
code string 用于第二步调用oauth2/access_token接口,获取授权后的access token。
state string 如果传递参数,会回传该参数
"""
if self.oauth2_params and self.oauth2_params.get("display") == "mobile":
auth_url = self.mobile_url + "authorize"
else:
auth_url = self.site_url + "authorize"
params = {
'client_id': self.client_id,
'redirect_uri': self.redirect_url,
}
params.update(self.oauth2_params)
params = filter_params(params)
return "{auth_url}?{params}".format(auth_url=auth_url, params=urlencode(params))
|
authorization url
request weibo authorization url
:return:
code string 用于第二步调用oauth2/access_token接口,获取授权后的access token。
state string 如果传递参数,会回传该参数
|
entailment
|
def request(self, method, suffix, data):
"""
:param method: str, http method ["GET","POST","PUT"]
:param suffix: the url suffix
:param data:
:return:
"""
url = self.site_url + suffix
response = self.session.request(method, url, data=data)
if response.status_code == 200:
json_obj = response.json()
if isinstance(json_obj, dict) and json_obj.get("error_code"):
raise WeiboOauth2Error(
json_obj.get("error_code"),
json_obj.get("error"),
json_obj.get('error_description')
)
else:
return json_obj
else:
raise WeiboRequestError(
"Weibo API request error: status code: {code} url:{url} ->"
" method:{method}: data={data}".format(
code=response.status_code,
url=response.url,
method=method,
data=data
)
)
|
:param method: str, http method ["GET","POST","PUT"]
:param suffix: the url suffix
:param data:
:return:
|
entailment
|
def auth_access(self, auth_code):
"""
verify the fist authorization response url code
response data
返回值字段 字段类型 字段说明
access_token string 用户授权的唯一票据,用于调用微博的开放接口,同时也是第三方应用验证微博用户登录的唯一票据,
第三方应用应该用该票据和自己应用内的用户建立唯一影射关系,来识别登录状态,不能使用本返回值里的UID
字段来做登录识别。
expires_in string access_token的生命周期,单位是秒数。
remind_in string access_token的生命周期(该参数即将废弃,开发者请使用expires_in)。
uid string 授权用户的UID,本字段只是为了方便开发者,减少一次user/show接口调用而返回的,第三方应用不能用此字段作为用户
登录状态的识别,只有access_token才是用户授权的唯一票据。
:param auth_code: authorize_url response code
:return:
normal:
{
"access_token": "ACCESS_TOKEN",
"expires_in": 1234,
"remind_in":"798114",
"uid":"12341234"
}
mobile:
{
"access_token": "SlAV32hkKG",
"remind_in": 3600,
"expires_in": 3600
"refresh_token": "QXBK19xm62"
}
"""
data = {
'client_id': self.client_id,
'client_secret': self.client_secret,
'grant_type': 'authorization_code',
'code': auth_code,
'redirect_uri': self.redirect_url
}
return self.request("post", "access_token", data=data)
|
verify the fist authorization response url code
response data
返回值字段 字段类型 字段说明
access_token string 用户授权的唯一票据,用于调用微博的开放接口,同时也是第三方应用验证微博用户登录的唯一票据,
第三方应用应该用该票据和自己应用内的用户建立唯一影射关系,来识别登录状态,不能使用本返回值里的UID
字段来做登录识别。
expires_in string access_token的生命周期,单位是秒数。
remind_in string access_token的生命周期(该参数即将废弃,开发者请使用expires_in)。
uid string 授权用户的UID,本字段只是为了方便开发者,减少一次user/show接口调用而返回的,第三方应用不能用此字段作为用户
登录状态的识别,只有access_token才是用户授权的唯一票据。
:param auth_code: authorize_url response code
:return:
normal:
{
"access_token": "ACCESS_TOKEN",
"expires_in": 1234,
"remind_in":"798114",
"uid":"12341234"
}
mobile:
{
"access_token": "SlAV32hkKG",
"remind_in": 3600,
"expires_in": 3600
"refresh_token": "QXBK19xm62"
}
|
entailment
|
def revoke_auth_access(self, access_token):
"""
授权回收接口,帮助开发者主动取消用户的授权。
应用下线时,清空所有用户的授权
应用新上线了功能,需要取得用户scope权限,可以回收后重新引导用户授权
开发者调试应用,需要反复调试授权功能
应用内实现类似登出微博帐号的功能
并传递给你以下参数,source:应用appkey,uid :取消授权的用户,auth_end :取消授权的时间
:param access_token:
:return: bool
"""
result = self.request("post", "revokeoauth2", data={"access_token": access_token})
return bool(result.get("result"))
|
授权回收接口,帮助开发者主动取消用户的授权。
应用下线时,清空所有用户的授权
应用新上线了功能,需要取得用户scope权限,可以回收后重新引导用户授权
开发者调试应用,需要反复调试授权功能
应用内实现类似登出微博帐号的功能
并传递给你以下参数,source:应用appkey,uid :取消授权的用户,auth_end :取消授权的时间
:param access_token:
:return: bool
|
entailment
|
def __set_basic_auth_string(self, username, password):
'''
Creates and sets the authentication string for (write-)accessing the
Handle Server. No return, the string is set as an attribute to
the client instance.
:param username: Username handle with index: index:prefix/suffix.
:param password: The password contained in the index of the username
handle.
'''
auth = b2handle.utilhandle.create_authentication_string(username, password)
self.__basic_authentication_string = auth
|
Creates and sets the authentication string for (write-)accessing the
Handle Server. No return, the string is set as an attribute to
the client instance.
:param username: Username handle with index: index:prefix/suffix.
:param password: The password contained in the index of the username
handle.
|
entailment
|
def send_handle_get_request(self, handle, indices=None):
'''
Send a HTTP GET request to the handle server to read either an entire
handle or to some specified values from a handle record, using the
requests module.
:param handle: The handle.
:param indices: Optional. A list of indices to delete. Defaults to
None (i.e. the entire handle is deleted.). The list can contain
integers or strings.
:return: The server's response.
'''
# Assemble required info:
url = self.make_handle_URL(handle, indices)
LOGGER.debug('GET Request to '+url)
head = self.__get_headers('GET')
veri = self.__HTTPS_verify
# Send the request
if self.__cert_needed_for_get_request():
# If this is the first request and the connector uses client cert authentication, we need to send the cert along
# in the first request that builds the session.
resp = self.__session.get(url, headers=head, verify=veri, cert=self.__cert_object)
else:
# Normal case:
resp = self.__session.get(url, headers=head, verify=veri)
# Log and return
self.__log_request_response_to_file(
logger=REQUESTLOGGER,
op='GET',
handle=handle,
url=url,
headers=head,
verify=veri,
resp=resp
)
self.__first_request = False
return resp
|
Send a HTTP GET request to the handle server to read either an entire
handle or to some specified values from a handle record, using the
requests module.
:param handle: The handle.
:param indices: Optional. A list of indices to delete. Defaults to
None (i.e. the entire handle is deleted.). The list can contain
integers or strings.
:return: The server's response.
|
entailment
|
def send_handle_put_request(self, **args):
'''
Send a HTTP PUT request to the handle server to write either an entire
handle or to some specified values to an handle record, using the
requests module.
:param handle: The handle.
:param list_of_entries: A list of handle record entries to be written,
in the format [{"index":xyz, "type":"xyz", "data":"xyz"}] or similar.
:param indices: Optional. A list of indices to delete. Defaults
to None (i.e. the entire handle is deleted.). The list can
contain integers or strings.
:param overwrite: Optional. Whether the handle should be overwritten
if it exists already.
:return: The server's response.
'''
# Check if we have write access at all:
if not self.__has_write_access:
raise HandleAuthenticationError(msg=self.__no_auth_message)
# Check args:
mandatory_args = ['handle', 'list_of_entries']
optional_args = ['indices', 'op', 'overwrite']
b2handle.util.add_missing_optional_args_with_value_none(args, optional_args)
b2handle.util.check_presence_of_mandatory_args(args, mandatory_args)
handle = args['handle']
list_of_entries = args['list_of_entries']
indices = args['indices']
op = args['op']
overwrite = args['overwrite'] or False
# Make necessary values:
url = self.make_handle_URL(handle, indices, overwrite=overwrite)
LOGGER.debug('PUT Request to '+url)
payload = json.dumps({'values':list_of_entries})
LOGGER.debug('PUT Request payload: '+payload)
head = self.__get_headers('PUT')
LOGGER.debug('PUT Request headers: '+str(head))
veri = self.__HTTPS_verify
# Send request to server:
resp = self.__send_put_request_to_server(url, payload, head, veri, handle)
if b2handle.hsresponses.is_redirect_from_http_to_https(resp):
resp = self.__resend_put_request_on_302(payload, head, veri, handle, resp)
# Check response for authentication issues:
if b2handle.hsresponses.not_authenticated(resp):
raise HandleAuthenticationError(
operation=op,
handle=handle,
response=resp,
username=self.__username
)
self.__first_request = False
return resp, payload
|
Send a HTTP PUT request to the handle server to write either an entire
handle or to some specified values to an handle record, using the
requests module.
:param handle: The handle.
:param list_of_entries: A list of handle record entries to be written,
in the format [{"index":xyz, "type":"xyz", "data":"xyz"}] or similar.
:param indices: Optional. A list of indices to delete. Defaults
to None (i.e. the entire handle is deleted.). The list can
contain integers or strings.
:param overwrite: Optional. Whether the handle should be overwritten
if it exists already.
:return: The server's response.
|
entailment
|
def send_handle_delete_request(self, **args):
'''
Send a HTTP DELETE request to the handle server to delete either an
entire handle or to some specified values from a handle record,
using the requests module.
:param handle: The handle.
:param indices: Optional. A list of indices to delete. Defaults to
None (i.e. the entire handle is deleted.). The list can contain
integers or strings.
:return: The server's response.
'''
# Check if we have write access at all:
if not self.__has_write_access:
raise HandleAuthenticationError(msg=self.__no_auth_message)
# Check args:
mandatory_args = ['handle']
optional_args = ['indices', 'op']
b2handle.util.add_missing_optional_args_with_value_none(args, optional_args)
b2handle.util.check_presence_of_mandatory_args(args, mandatory_args)
handle = args['handle']
indices = args['indices']
op = args['op']
# Make necessary values:
url = self.make_handle_URL(handle, indices)
if indices is not None and len(indices) > 0:
LOGGER.debug('__send_handle_delete_request: Deleting values '+str(indices)+' from handle '+handle+'.')
else:
LOGGER.debug('__send_handle_delete_request: Deleting handle '+handle+'.')
LOGGER.debug('DELETE Request to '+url)
head = self.__get_headers('DELETE')
veri = self.__HTTPS_verify
# Make request:
resp = None
if self.__authentication_method == self.__auth_methods['user_pw']:
resp = self.__session.delete(url, headers=head, verify=veri)
elif self.__authentication_method == self.__auth_methods['cert']:
resp = self.__session.delete(url, headers=head, verify=veri, cert=self.__cert_object)
self.__log_request_response_to_file(
logger=REQUESTLOGGER,
op='DELETE',
handle=handle,
url=url,
headers=head,
verify=veri,
resp=resp
)
# Check response for authentication issues:
if b2handle.hsresponses.not_authenticated(resp):
raise HandleAuthenticationError(
operation=op,
handle=handle,
response=resp,
username=self.__username
)
self.__first_request = False
return resp
|
Send a HTTP DELETE request to the handle server to delete either an
entire handle or to some specified values from a handle record,
using the requests module.
:param handle: The handle.
:param indices: Optional. A list of indices to delete. Defaults to
None (i.e. the entire handle is deleted.). The list can contain
integers or strings.
:return: The server's response.
|
entailment
|
def check_if_username_exists(self, username):
'''
Check if the username handles exists.
:param username: The username, in the form index:prefix/suffix
:raises: :exc:`~b2handle.handleexceptions.HandleNotFoundException`
:raises: :exc:`~b2handle.handleexceptions.GenericHandleError`
:return: True. If it does not exist, an exception is raised.
*Note:* Only the existence of the handle is verified. The existence or
validity of the index is not checked, because entries containing
a key are hidden anyway.
'''
LOGGER.debug('check_if_username_exists...')
_, handle = b2handle.utilhandle.remove_index_from_handle(username)
resp = self.send_handle_get_request(handle)
resp_content = decoded_response(resp)
if b2handle.hsresponses.does_handle_exist(resp):
handlerecord_json = json.loads(resp_content)
if not handlerecord_json['handle'] == handle:
raise GenericHandleError(
operation='Checking if username exists',
handle=handle,
reponse=resp,
msg='The check returned a different handle than was asked for.'
)
return True
elif b2handle.hsresponses.handle_not_found(resp):
msg = 'The username handle does not exist'
raise HandleNotFoundException(handle=handle, msg=msg, response=resp)
else:
op = 'checking if handle exists'
msg = 'Checking if username exists went wrong'
raise GenericHandleError(operation=op, handle=handle, response=resp, msg=msg)
|
Check if the username handles exists.
:param username: The username, in the form index:prefix/suffix
:raises: :exc:`~b2handle.handleexceptions.HandleNotFoundException`
:raises: :exc:`~b2handle.handleexceptions.GenericHandleError`
:return: True. If it does not exist, an exception is raised.
*Note:* Only the existence of the handle is verified. The existence or
validity of the index is not checked, because entries containing
a key are hidden anyway.
|
entailment
|
def __get_headers(self, action):
'''
Create HTTP headers for different HTTP requests. Content-type and
Accept are 'application/json', as the library is interacting with
a REST API.
:param action: Action for which to create the header ('GET', 'PUT',
'DELETE', 'SEARCH').
:return: dict containing key-value pairs, e.g. 'Accept',
'Content-Type', etc. (depening on the action).
'''
header = {}
accept = 'application/json'
content_type = 'application/json'
if action is 'GET':
header['Accept'] = accept
elif action is 'PUT' or action is 'DELETE':
if self.__authentication_method == self.__auth_methods['cert']:
header['Authorization'] = 'Handle clientCert="true"'
elif self.__authentication_method == self.__auth_methods['user_pw']:
header['Authorization'] = 'Basic ' + self.__basic_authentication_string
if action is 'PUT':
header['Content-Type'] = content_type
else:
LOGGER.debug('__getHeader: ACTION is unknown ('+action+')')
return header
|
Create HTTP headers for different HTTP requests. Content-type and
Accept are 'application/json', as the library is interacting with
a REST API.
:param action: Action for which to create the header ('GET', 'PUT',
'DELETE', 'SEARCH').
:return: dict containing key-value pairs, e.g. 'Accept',
'Content-Type', etc. (depening on the action).
|
entailment
|
def make_handle_URL(self, handle, indices=None, overwrite=None, other_url=None):
'''
Create the URL for a HTTP request (URL + query string) to request
a specific handle from the Handle Server.
:param handle: The handle to access.
:param indices: Optional. A list of integers or strings. Indices of
the handle record entries to read or write. Defaults to None.
:param overwrite: Optional. If set, an overwrite flag will be appended
to the URL ({?,&}overwrite=true or {?,&}overwrite=false). If not set, no
flag is set, thus the Handle Server's default behaviour will be
used. Defaults to None.
:param other_url: Optional. If a different Handle Server URL than the
one specified in the constructor should be used. Defaults to None.
If set, it should be set including the URL extension,
e.g. '/api/handles/'.
:return: The complete URL, e.g.
'http://some.handle.server/api/handles/prefix/suffix?index=2&index=6&overwrite=false
'''
LOGGER.debug('make_handle_URL...')
separator = '?'
if other_url is not None:
url = other_url
else:
url = self.__handle_server_url.strip('/') +'/'+\
self.__REST_API_url_extension.strip('/')
url = url.strip('/')+'/'+ handle
if indices is None:
indices = []
if len(indices) > 0:
for index in indices:
url = url+separator+'index='+str(index)
separator = '&'
if overwrite is not None:
if overwrite:
url = url+separator+'overwrite=true'
else:
url = url+separator+'overwrite=false'
return url
|
Create the URL for a HTTP request (URL + query string) to request
a specific handle from the Handle Server.
:param handle: The handle to access.
:param indices: Optional. A list of integers or strings. Indices of
the handle record entries to read or write. Defaults to None.
:param overwrite: Optional. If set, an overwrite flag will be appended
to the URL ({?,&}overwrite=true or {?,&}overwrite=false). If not set, no
flag is set, thus the Handle Server's default behaviour will be
used. Defaults to None.
:param other_url: Optional. If a different Handle Server URL than the
one specified in the constructor should be used. Defaults to None.
If set, it should be set including the URL extension,
e.g. '/api/handles/'.
:return: The complete URL, e.g.
'http://some.handle.server/api/handles/prefix/suffix?index=2&index=6&overwrite=false
|
entailment
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.