repository_name
stringclasses 316
values | func_path_in_repository
stringlengths 6
223
| func_name
stringlengths 1
134
| language
stringclasses 1
value | func_code_string
stringlengths 57
65.5k
| func_documentation_string
stringlengths 1
46.3k
| split_name
stringclasses 1
value | func_code_url
stringlengths 91
315
| called_functions
listlengths 1
156
⌀ | enclosing_scope
stringlengths 2
1.48M
|
|---|---|---|---|---|---|---|---|---|---|
erikvw/django-collect-offline
|
django_collect_offline/offline_model.py
|
OfflineModel.primary_key_field
|
python
|
def primary_key_field(self):
return [field for field in self.instance._meta.fields if field.primary_key][0]
|
Return the primary key field.
Is `id` in most cases. Is `history_id` for Historical models.
|
train
|
https://github.com/erikvw/django-collect-offline/blob/3d5efd66c68e2db4b060a82b070ae490dc399ca7/django_collect_offline/offline_model.py#L103-L108
| null |
class OfflineModel:
"""A wrapper for offline model instances to add methods called in
signals for synchronization.
"""
def __init__(self, instance):
try:
self.is_serialized = settings.ALLOW_MODEL_SERIALIZATION
except AttributeError:
self.is_serialized = True
self.instance = instance
self.has_offline_historical_manager_or_raise()
self.has_natural_key_or_raise()
self.has_get_by_natural_key_or_raise()
self.has_uuid_primary_key_or_raise()
def __repr__(self):
return f"{self.__class__.__name__}({repr(self.instance)})"
def __str__(self):
return f"{self.instance._meta.label_lower}"
def has_natural_key_or_raise(self):
try:
self.instance.natural_key
except AttributeError:
raise OfflineNaturalKeyMissing(
f"Model '{self.instance._meta.app_label}.{self.instance._meta.model_name}' "
"is missing method natural_key "
)
def has_get_by_natural_key_or_raise(self):
try:
self.instance.__class__.objects.get_by_natural_key
except AttributeError:
raise OfflineGetByNaturalKeyMissing(
f"Model '{self.instance._meta.app_label}.{self.instance._meta.model_name}' "
"is missing manager method get_by_natural_key "
)
def has_offline_historical_manager_or_raise(self):
"""Raises an exception if model uses a history manager and
historical model history_id is not a UUIDField.
Note: expected to use edc_model.HistoricalRecords instead of
simple_history.HistoricalRecords.
"""
try:
model = self.instance.__class__.history.model
except AttributeError:
model = self.instance.__class__
field = [field for field in model._meta.fields if field.name == "history_id"]
if field and not isinstance(field[0], UUIDField):
raise OfflineHistoricalManagerError(
f"Field 'history_id' of historical model "
f"'{model._meta.app_label}.{model._meta.model_name}' "
"must be an UUIDfield. "
"For history = HistoricalRecords() use edc_model.HistoricalRecords instead of "
"simple_history.HistoricalRecords(). "
f"See '{self.instance._meta.app_label}.{self.instance._meta.model_name}'."
)
def has_uuid_primary_key_or_raise(self):
if self.primary_key_field.get_internal_type() != "UUIDField":
raise OfflineUuidPrimaryKeyMissing(
f"Expected Model '{self.instance._meta.label_lower}' "
f"primary key {self.primary_key_field} to be a UUIDField "
f"(e.g. AutoUUIDField). "
f"Got {self.primary_key_field.get_internal_type()}."
)
@property
def to_outgoing_transaction(self, using, created=None, deleted=None):
""" Serialize the model instance to an AES encrypted json object
and saves the json object to the OutgoingTransaction model.
"""
OutgoingTransaction = django_apps.get_model(
"django_collect_offline", "OutgoingTransaction"
)
created = True if created is None else created
action = INSERT if created else UPDATE
timestamp_datetime = (
self.instance.created if created else self.instance.modified
)
if not timestamp_datetime:
timestamp_datetime = get_utcnow()
if deleted:
timestamp_datetime = get_utcnow()
action = DELETE
outgoing_transaction = None
if self.is_serialized:
hostname = socket.gethostname()
outgoing_transaction = OutgoingTransaction.objects.using(using).create(
tx_name=self.instance._meta.label_lower,
tx_pk=getattr(self.instance, self.primary_key_field.name),
tx=self.encrypted_json(),
timestamp=timestamp_datetime.strftime("%Y%m%d%H%M%S%f"),
producer=f"{hostname}-{using}",
action=action,
using=using,
)
return outgoing_transaction
def encrypted_json(self):
"""Returns an encrypted json serialized from self.
"""
json = serialize(objects=[self.instance])
encrypted_json = Cryptor().aes_encrypt(json, LOCAL_MODE)
return encrypted_json
|
erikvw/django-collect-offline
|
django_collect_offline/offline_model.py
|
OfflineModel.to_outgoing_transaction
|
python
|
def to_outgoing_transaction(self, using, created=None, deleted=None):
OutgoingTransaction = django_apps.get_model(
"django_collect_offline", "OutgoingTransaction"
)
created = True if created is None else created
action = INSERT if created else UPDATE
timestamp_datetime = (
self.instance.created if created else self.instance.modified
)
if not timestamp_datetime:
timestamp_datetime = get_utcnow()
if deleted:
timestamp_datetime = get_utcnow()
action = DELETE
outgoing_transaction = None
if self.is_serialized:
hostname = socket.gethostname()
outgoing_transaction = OutgoingTransaction.objects.using(using).create(
tx_name=self.instance._meta.label_lower,
tx_pk=getattr(self.instance, self.primary_key_field.name),
tx=self.encrypted_json(),
timestamp=timestamp_datetime.strftime("%Y%m%d%H%M%S%f"),
producer=f"{hostname}-{using}",
action=action,
using=using,
)
return outgoing_transaction
|
Serialize the model instance to an AES encrypted json object
and saves the json object to the OutgoingTransaction model.
|
train
|
https://github.com/erikvw/django-collect-offline/blob/3d5efd66c68e2db4b060a82b070ae490dc399ca7/django_collect_offline/offline_model.py#L110-L139
|
[
"def encrypted_json(self):\n \"\"\"Returns an encrypted json serialized from self.\n \"\"\"\n json = serialize(objects=[self.instance])\n encrypted_json = Cryptor().aes_encrypt(json, LOCAL_MODE)\n return encrypted_json\n"
] |
class OfflineModel:
"""A wrapper for offline model instances to add methods called in
signals for synchronization.
"""
def __init__(self, instance):
try:
self.is_serialized = settings.ALLOW_MODEL_SERIALIZATION
except AttributeError:
self.is_serialized = True
self.instance = instance
self.has_offline_historical_manager_or_raise()
self.has_natural_key_or_raise()
self.has_get_by_natural_key_or_raise()
self.has_uuid_primary_key_or_raise()
def __repr__(self):
return f"{self.__class__.__name__}({repr(self.instance)})"
def __str__(self):
return f"{self.instance._meta.label_lower}"
def has_natural_key_or_raise(self):
try:
self.instance.natural_key
except AttributeError:
raise OfflineNaturalKeyMissing(
f"Model '{self.instance._meta.app_label}.{self.instance._meta.model_name}' "
"is missing method natural_key "
)
def has_get_by_natural_key_or_raise(self):
try:
self.instance.__class__.objects.get_by_natural_key
except AttributeError:
raise OfflineGetByNaturalKeyMissing(
f"Model '{self.instance._meta.app_label}.{self.instance._meta.model_name}' "
"is missing manager method get_by_natural_key "
)
def has_offline_historical_manager_or_raise(self):
"""Raises an exception if model uses a history manager and
historical model history_id is not a UUIDField.
Note: expected to use edc_model.HistoricalRecords instead of
simple_history.HistoricalRecords.
"""
try:
model = self.instance.__class__.history.model
except AttributeError:
model = self.instance.__class__
field = [field for field in model._meta.fields if field.name == "history_id"]
if field and not isinstance(field[0], UUIDField):
raise OfflineHistoricalManagerError(
f"Field 'history_id' of historical model "
f"'{model._meta.app_label}.{model._meta.model_name}' "
"must be an UUIDfield. "
"For history = HistoricalRecords() use edc_model.HistoricalRecords instead of "
"simple_history.HistoricalRecords(). "
f"See '{self.instance._meta.app_label}.{self.instance._meta.model_name}'."
)
def has_uuid_primary_key_or_raise(self):
if self.primary_key_field.get_internal_type() != "UUIDField":
raise OfflineUuidPrimaryKeyMissing(
f"Expected Model '{self.instance._meta.label_lower}' "
f"primary key {self.primary_key_field} to be a UUIDField "
f"(e.g. AutoUUIDField). "
f"Got {self.primary_key_field.get_internal_type()}."
)
@property
def primary_key_field(self):
"""Return the primary key field.
Is `id` in most cases. Is `history_id` for Historical models.
"""
return [field for field in self.instance._meta.fields if field.primary_key][0]
def encrypted_json(self):
"""Returns an encrypted json serialized from self.
"""
json = serialize(objects=[self.instance])
encrypted_json = Cryptor().aes_encrypt(json, LOCAL_MODE)
return encrypted_json
|
erikvw/django-collect-offline
|
django_collect_offline/offline_model.py
|
OfflineModel.encrypted_json
|
python
|
def encrypted_json(self):
json = serialize(objects=[self.instance])
encrypted_json = Cryptor().aes_encrypt(json, LOCAL_MODE)
return encrypted_json
|
Returns an encrypted json serialized from self.
|
train
|
https://github.com/erikvw/django-collect-offline/blob/3d5efd66c68e2db4b060a82b070ae490dc399ca7/django_collect_offline/offline_model.py#L141-L146
|
[
"def serialize(objects=None):\n \"\"\"A simple wrapper of Django's serializer with defaults\n for JSON and natural keys.\n\n Note: use_natural_primary_keys is False as once\n a pk is set, it should not be changed throughout the\n distributed data.\n \"\"\"\n\n return serializers.serialize(\n \"json\",\n objects,\n ensure_ascii=True,\n use_natural_foreign_keys=True,\n use_natural_primary_keys=False,\n )\n"
] |
class OfflineModel:
"""A wrapper for offline model instances to add methods called in
signals for synchronization.
"""
def __init__(self, instance):
try:
self.is_serialized = settings.ALLOW_MODEL_SERIALIZATION
except AttributeError:
self.is_serialized = True
self.instance = instance
self.has_offline_historical_manager_or_raise()
self.has_natural_key_or_raise()
self.has_get_by_natural_key_or_raise()
self.has_uuid_primary_key_or_raise()
def __repr__(self):
return f"{self.__class__.__name__}({repr(self.instance)})"
def __str__(self):
return f"{self.instance._meta.label_lower}"
def has_natural_key_or_raise(self):
try:
self.instance.natural_key
except AttributeError:
raise OfflineNaturalKeyMissing(
f"Model '{self.instance._meta.app_label}.{self.instance._meta.model_name}' "
"is missing method natural_key "
)
def has_get_by_natural_key_or_raise(self):
try:
self.instance.__class__.objects.get_by_natural_key
except AttributeError:
raise OfflineGetByNaturalKeyMissing(
f"Model '{self.instance._meta.app_label}.{self.instance._meta.model_name}' "
"is missing manager method get_by_natural_key "
)
def has_offline_historical_manager_or_raise(self):
"""Raises an exception if model uses a history manager and
historical model history_id is not a UUIDField.
Note: expected to use edc_model.HistoricalRecords instead of
simple_history.HistoricalRecords.
"""
try:
model = self.instance.__class__.history.model
except AttributeError:
model = self.instance.__class__
field = [field for field in model._meta.fields if field.name == "history_id"]
if field and not isinstance(field[0], UUIDField):
raise OfflineHistoricalManagerError(
f"Field 'history_id' of historical model "
f"'{model._meta.app_label}.{model._meta.model_name}' "
"must be an UUIDfield. "
"For history = HistoricalRecords() use edc_model.HistoricalRecords instead of "
"simple_history.HistoricalRecords(). "
f"See '{self.instance._meta.app_label}.{self.instance._meta.model_name}'."
)
def has_uuid_primary_key_or_raise(self):
if self.primary_key_field.get_internal_type() != "UUIDField":
raise OfflineUuidPrimaryKeyMissing(
f"Expected Model '{self.instance._meta.label_lower}' "
f"primary key {self.primary_key_field} to be a UUIDField "
f"(e.g. AutoUUIDField). "
f"Got {self.primary_key_field.get_internal_type()}."
)
@property
def primary_key_field(self):
"""Return the primary key field.
Is `id` in most cases. Is `history_id` for Historical models.
"""
return [field for field in self.instance._meta.fields if field.primary_key][0]
def to_outgoing_transaction(self, using, created=None, deleted=None):
""" Serialize the model instance to an AES encrypted json object
and saves the json object to the OutgoingTransaction model.
"""
OutgoingTransaction = django_apps.get_model(
"django_collect_offline", "OutgoingTransaction"
)
created = True if created is None else created
action = INSERT if created else UPDATE
timestamp_datetime = (
self.instance.created if created else self.instance.modified
)
if not timestamp_datetime:
timestamp_datetime = get_utcnow()
if deleted:
timestamp_datetime = get_utcnow()
action = DELETE
outgoing_transaction = None
if self.is_serialized:
hostname = socket.gethostname()
outgoing_transaction = OutgoingTransaction.objects.using(using).create(
tx_name=self.instance._meta.label_lower,
tx_pk=getattr(self.instance, self.primary_key_field.name),
tx=self.encrypted_json(),
timestamp=timestamp_datetime.strftime("%Y%m%d%H%M%S%f"),
producer=f"{hostname}-{using}",
action=action,
using=using,
)
return outgoing_transaction
|
erikvw/django-collect-offline
|
django_collect_offline/transaction/serialize.py
|
serialize
|
python
|
def serialize(objects=None):
return serializers.serialize(
"json",
objects,
ensure_ascii=True,
use_natural_foreign_keys=True,
use_natural_primary_keys=False,
)
|
A simple wrapper of Django's serializer with defaults
for JSON and natural keys.
Note: use_natural_primary_keys is False as once
a pk is set, it should not be changed throughout the
distributed data.
|
train
|
https://github.com/erikvw/django-collect-offline/blob/3d5efd66c68e2db4b060a82b070ae490dc399ca7/django_collect_offline/transaction/serialize.py#L4-L19
| null |
from django.core import serializers
|
erikvw/django-collect-offline
|
django_collect_offline/transaction/deserialize.py
|
deserialize
|
python
|
def deserialize(json_text=None):
return serializers.deserialize(
"json",
json_text,
ensure_ascii=True,
use_natural_foreign_keys=True,
use_natural_primary_keys=False,
)
|
Returns a generator of deserialized objects.
Wraps django deserialize with defaults for JSON
and natural keys.
See https://docs.djangoproject.com/en/2.1/topics/serialization/
|
train
|
https://github.com/erikvw/django-collect-offline/blob/3d5efd66c68e2db4b060a82b070ae490dc399ca7/django_collect_offline/transaction/deserialize.py#L4-L19
| null |
from django.core import serializers
|
erikvw/django-collect-offline
|
django_collect_offline/signals.py
|
create_auth_token
|
python
|
def create_auth_token(sender, instance, raw, created, **kwargs):
if not raw:
if created:
sender.objects.create(user=instance)
|
Create token when a user is created (from rest_framework).
|
train
|
https://github.com/erikvw/django-collect-offline/blob/3d5efd66c68e2db4b060a82b070ae490dc399ca7/django_collect_offline/signals.py#L10-L15
| null |
from django.db.models.signals import post_save, m2m_changed, post_delete
from django.dispatch import receiver
from rest_framework.authtoken.models import Token
from simple_history.signals import post_create_historical_record
from .site_offline_models import site_offline_models, ModelNotRegistered
@receiver(post_save, sender=Token)
@receiver(m2m_changed, weak=False, dispatch_uid="serialize_m2m_on_save")
def serialize_m2m_on_save(sender, action, instance, using, **kwargs):
""" Part of the serialize transaction process that ensures m2m are
serialized correctly.
Skip those not registered.
"""
if action == "post_add":
try:
wrapped_instance = site_offline_models.get_wrapped_instance(instance)
except ModelNotRegistered:
pass
else:
wrapped_instance.to_outgoing_transaction(using, created=True)
@receiver(post_save, weak=False, dispatch_uid="serialize_on_save")
def serialize_on_save(sender, instance, raw, created, using, **kwargs):
""" Serialize the model instance as an OutgoingTransaction.
Skip those not registered.
"""
if not raw:
if "historical" not in instance._meta.label_lower:
try:
wrapped_instance = site_offline_models.get_wrapped_instance(instance)
except ModelNotRegistered:
pass
else:
wrapped_instance.to_outgoing_transaction(using, created=created)
@receiver(
post_create_historical_record,
weak=False,
dispatch_uid="serialize_history_on_post_create",
)
def serialize_history_on_post_create(history_instance, using, **kwargs):
""" Serialize the history instance as an OutgoingTransaction.
Skip those not registered.
"""
try:
wrapped_instance = site_offline_models.get_wrapped_instance(history_instance)
except ModelNotRegistered:
pass
else:
wrapped_instance.to_outgoing_transaction(using, created=True)
@receiver(post_delete, weak=False, dispatch_uid="serialize_on_post_delete")
def serialize_on_post_delete(sender, instance, using, **kwargs):
"""Creates a serialized OutgoingTransaction when
a model instance is deleted.
Skip those not registered.
"""
try:
wrapped_instance = site_offline_models.get_wrapped_instance(instance)
except ModelNotRegistered:
pass
else:
wrapped_instance.to_outgoing_transaction(using, created=False, deleted=True)
|
erikvw/django-collect-offline
|
django_collect_offline/signals.py
|
serialize_m2m_on_save
|
python
|
def serialize_m2m_on_save(sender, action, instance, using, **kwargs):
if action == "post_add":
try:
wrapped_instance = site_offline_models.get_wrapped_instance(instance)
except ModelNotRegistered:
pass
else:
wrapped_instance.to_outgoing_transaction(using, created=True)
|
Part of the serialize transaction process that ensures m2m are
serialized correctly.
Skip those not registered.
|
train
|
https://github.com/erikvw/django-collect-offline/blob/3d5efd66c68e2db4b060a82b070ae490dc399ca7/django_collect_offline/signals.py#L19-L31
|
[
"def get_wrapped_instance(self, instance=None):\n \"\"\"Returns a wrapped model instance.\n \"\"\"\n if instance._meta.label_lower not in self.registry:\n raise ModelNotRegistered(f\"{repr(instance)} is not registered with {self}.\")\n wrapper_cls = self.registry.get(instance._meta.label_lower) or self.wrapper_cls\n if wrapper_cls:\n return wrapper_cls(instance)\n return instance\n"
] |
from django.db.models.signals import post_save, m2m_changed, post_delete
from django.dispatch import receiver
from rest_framework.authtoken.models import Token
from simple_history.signals import post_create_historical_record
from .site_offline_models import site_offline_models, ModelNotRegistered
@receiver(post_save, sender=Token)
def create_auth_token(sender, instance, raw, created, **kwargs):
"""Create token when a user is created (from rest_framework).
"""
if not raw:
if created:
sender.objects.create(user=instance)
@receiver(m2m_changed, weak=False, dispatch_uid="serialize_m2m_on_save")
@receiver(post_save, weak=False, dispatch_uid="serialize_on_save")
def serialize_on_save(sender, instance, raw, created, using, **kwargs):
""" Serialize the model instance as an OutgoingTransaction.
Skip those not registered.
"""
if not raw:
if "historical" not in instance._meta.label_lower:
try:
wrapped_instance = site_offline_models.get_wrapped_instance(instance)
except ModelNotRegistered:
pass
else:
wrapped_instance.to_outgoing_transaction(using, created=created)
@receiver(
post_create_historical_record,
weak=False,
dispatch_uid="serialize_history_on_post_create",
)
def serialize_history_on_post_create(history_instance, using, **kwargs):
""" Serialize the history instance as an OutgoingTransaction.
Skip those not registered.
"""
try:
wrapped_instance = site_offline_models.get_wrapped_instance(history_instance)
except ModelNotRegistered:
pass
else:
wrapped_instance.to_outgoing_transaction(using, created=True)
@receiver(post_delete, weak=False, dispatch_uid="serialize_on_post_delete")
def serialize_on_post_delete(sender, instance, using, **kwargs):
"""Creates a serialized OutgoingTransaction when
a model instance is deleted.
Skip those not registered.
"""
try:
wrapped_instance = site_offline_models.get_wrapped_instance(instance)
except ModelNotRegistered:
pass
else:
wrapped_instance.to_outgoing_transaction(using, created=False, deleted=True)
|
erikvw/django-collect-offline
|
django_collect_offline/signals.py
|
serialize_on_save
|
python
|
def serialize_on_save(sender, instance, raw, created, using, **kwargs):
if not raw:
if "historical" not in instance._meta.label_lower:
try:
wrapped_instance = site_offline_models.get_wrapped_instance(instance)
except ModelNotRegistered:
pass
else:
wrapped_instance.to_outgoing_transaction(using, created=created)
|
Serialize the model instance as an OutgoingTransaction.
Skip those not registered.
|
train
|
https://github.com/erikvw/django-collect-offline/blob/3d5efd66c68e2db4b060a82b070ae490dc399ca7/django_collect_offline/signals.py#L35-L47
|
[
"def get_wrapped_instance(self, instance=None):\n \"\"\"Returns a wrapped model instance.\n \"\"\"\n if instance._meta.label_lower not in self.registry:\n raise ModelNotRegistered(f\"{repr(instance)} is not registered with {self}.\")\n wrapper_cls = self.registry.get(instance._meta.label_lower) or self.wrapper_cls\n if wrapper_cls:\n return wrapper_cls(instance)\n return instance\n"
] |
from django.db.models.signals import post_save, m2m_changed, post_delete
from django.dispatch import receiver
from rest_framework.authtoken.models import Token
from simple_history.signals import post_create_historical_record
from .site_offline_models import site_offline_models, ModelNotRegistered
@receiver(post_save, sender=Token)
def create_auth_token(sender, instance, raw, created, **kwargs):
"""Create token when a user is created (from rest_framework).
"""
if not raw:
if created:
sender.objects.create(user=instance)
@receiver(m2m_changed, weak=False, dispatch_uid="serialize_m2m_on_save")
def serialize_m2m_on_save(sender, action, instance, using, **kwargs):
""" Part of the serialize transaction process that ensures m2m are
serialized correctly.
Skip those not registered.
"""
if action == "post_add":
try:
wrapped_instance = site_offline_models.get_wrapped_instance(instance)
except ModelNotRegistered:
pass
else:
wrapped_instance.to_outgoing_transaction(using, created=True)
@receiver(post_save, weak=False, dispatch_uid="serialize_on_save")
@receiver(
post_create_historical_record,
weak=False,
dispatch_uid="serialize_history_on_post_create",
)
def serialize_history_on_post_create(history_instance, using, **kwargs):
""" Serialize the history instance as an OutgoingTransaction.
Skip those not registered.
"""
try:
wrapped_instance = site_offline_models.get_wrapped_instance(history_instance)
except ModelNotRegistered:
pass
else:
wrapped_instance.to_outgoing_transaction(using, created=True)
@receiver(post_delete, weak=False, dispatch_uid="serialize_on_post_delete")
def serialize_on_post_delete(sender, instance, using, **kwargs):
"""Creates a serialized OutgoingTransaction when
a model instance is deleted.
Skip those not registered.
"""
try:
wrapped_instance = site_offline_models.get_wrapped_instance(instance)
except ModelNotRegistered:
pass
else:
wrapped_instance.to_outgoing_transaction(using, created=False, deleted=True)
|
erikvw/django-collect-offline
|
django_collect_offline/signals.py
|
serialize_history_on_post_create
|
python
|
def serialize_history_on_post_create(history_instance, using, **kwargs):
try:
wrapped_instance = site_offline_models.get_wrapped_instance(history_instance)
except ModelNotRegistered:
pass
else:
wrapped_instance.to_outgoing_transaction(using, created=True)
|
Serialize the history instance as an OutgoingTransaction.
Skip those not registered.
|
train
|
https://github.com/erikvw/django-collect-offline/blob/3d5efd66c68e2db4b060a82b070ae490dc399ca7/django_collect_offline/signals.py#L55-L65
|
[
"def get_wrapped_instance(self, instance=None):\n \"\"\"Returns a wrapped model instance.\n \"\"\"\n if instance._meta.label_lower not in self.registry:\n raise ModelNotRegistered(f\"{repr(instance)} is not registered with {self}.\")\n wrapper_cls = self.registry.get(instance._meta.label_lower) or self.wrapper_cls\n if wrapper_cls:\n return wrapper_cls(instance)\n return instance\n"
] |
from django.db.models.signals import post_save, m2m_changed, post_delete
from django.dispatch import receiver
from rest_framework.authtoken.models import Token
from simple_history.signals import post_create_historical_record
from .site_offline_models import site_offline_models, ModelNotRegistered
@receiver(post_save, sender=Token)
def create_auth_token(sender, instance, raw, created, **kwargs):
"""Create token when a user is created (from rest_framework).
"""
if not raw:
if created:
sender.objects.create(user=instance)
@receiver(m2m_changed, weak=False, dispatch_uid="serialize_m2m_on_save")
def serialize_m2m_on_save(sender, action, instance, using, **kwargs):
""" Part of the serialize transaction process that ensures m2m are
serialized correctly.
Skip those not registered.
"""
if action == "post_add":
try:
wrapped_instance = site_offline_models.get_wrapped_instance(instance)
except ModelNotRegistered:
pass
else:
wrapped_instance.to_outgoing_transaction(using, created=True)
@receiver(post_save, weak=False, dispatch_uid="serialize_on_save")
def serialize_on_save(sender, instance, raw, created, using, **kwargs):
""" Serialize the model instance as an OutgoingTransaction.
Skip those not registered.
"""
if not raw:
if "historical" not in instance._meta.label_lower:
try:
wrapped_instance = site_offline_models.get_wrapped_instance(instance)
except ModelNotRegistered:
pass
else:
wrapped_instance.to_outgoing_transaction(using, created=created)
@receiver(
post_create_historical_record,
weak=False,
dispatch_uid="serialize_history_on_post_create",
)
@receiver(post_delete, weak=False, dispatch_uid="serialize_on_post_delete")
def serialize_on_post_delete(sender, instance, using, **kwargs):
"""Creates a serialized OutgoingTransaction when
a model instance is deleted.
Skip those not registered.
"""
try:
wrapped_instance = site_offline_models.get_wrapped_instance(instance)
except ModelNotRegistered:
pass
else:
wrapped_instance.to_outgoing_transaction(using, created=False, deleted=True)
|
erikvw/django-collect-offline
|
django_collect_offline/signals.py
|
serialize_on_post_delete
|
python
|
def serialize_on_post_delete(sender, instance, using, **kwargs):
try:
wrapped_instance = site_offline_models.get_wrapped_instance(instance)
except ModelNotRegistered:
pass
else:
wrapped_instance.to_outgoing_transaction(using, created=False, deleted=True)
|
Creates a serialized OutgoingTransaction when
a model instance is deleted.
Skip those not registered.
|
train
|
https://github.com/erikvw/django-collect-offline/blob/3d5efd66c68e2db4b060a82b070ae490dc399ca7/django_collect_offline/signals.py#L69-L80
|
[
"def get_wrapped_instance(self, instance=None):\n \"\"\"Returns a wrapped model instance.\n \"\"\"\n if instance._meta.label_lower not in self.registry:\n raise ModelNotRegistered(f\"{repr(instance)} is not registered with {self}.\")\n wrapper_cls = self.registry.get(instance._meta.label_lower) or self.wrapper_cls\n if wrapper_cls:\n return wrapper_cls(instance)\n return instance\n"
] |
from django.db.models.signals import post_save, m2m_changed, post_delete
from django.dispatch import receiver
from rest_framework.authtoken.models import Token
from simple_history.signals import post_create_historical_record
from .site_offline_models import site_offline_models, ModelNotRegistered
@receiver(post_save, sender=Token)
def create_auth_token(sender, instance, raw, created, **kwargs):
"""Create token when a user is created (from rest_framework).
"""
if not raw:
if created:
sender.objects.create(user=instance)
@receiver(m2m_changed, weak=False, dispatch_uid="serialize_m2m_on_save")
def serialize_m2m_on_save(sender, action, instance, using, **kwargs):
""" Part of the serialize transaction process that ensures m2m are
serialized correctly.
Skip those not registered.
"""
if action == "post_add":
try:
wrapped_instance = site_offline_models.get_wrapped_instance(instance)
except ModelNotRegistered:
pass
else:
wrapped_instance.to_outgoing_transaction(using, created=True)
@receiver(post_save, weak=False, dispatch_uid="serialize_on_save")
def serialize_on_save(sender, instance, raw, created, using, **kwargs):
""" Serialize the model instance as an OutgoingTransaction.
Skip those not registered.
"""
if not raw:
if "historical" not in instance._meta.label_lower:
try:
wrapped_instance = site_offline_models.get_wrapped_instance(instance)
except ModelNotRegistered:
pass
else:
wrapped_instance.to_outgoing_transaction(using, created=created)
@receiver(
post_create_historical_record,
weak=False,
dispatch_uid="serialize_history_on_post_create",
)
def serialize_history_on_post_create(history_instance, using, **kwargs):
""" Serialize the history instance as an OutgoingTransaction.
Skip those not registered.
"""
try:
wrapped_instance = site_offline_models.get_wrapped_instance(history_instance)
except ModelNotRegistered:
pass
else:
wrapped_instance.to_outgoing_transaction(using, created=True)
@receiver(post_delete, weak=False, dispatch_uid="serialize_on_post_delete")
|
mathiasertl/xmpp-backends
|
xmpp_backends/ejabberd_xmlrpc.py
|
EjabberdXMLRPCBackend.rpc
|
python
|
def rpc(self, cmd, **kwargs):
func = getattr(self.client, cmd)
try:
if self.credentials is None:
return func(kwargs)
else:
return func(self.credentials, kwargs)
except socket.error as e:
raise BackendConnectionError(e)
except (xmlrpclib.ProtocolError, BadStatusLine) as e:
log.error(e)
raise BackendError("Error reaching backend.")
|
Generic helper function to call an RPC method.
|
train
|
https://github.com/mathiasertl/xmpp-backends/blob/214ef0664dbf90fa300c2483b9b3416559e5d171/xmpp_backends/ejabberd_xmlrpc.py#L107-L120
| null |
class EjabberdXMLRPCBackend(EjabberdBackendBase):
"""This backend uses the Ejabberd XMLRPC interface.
In addition to an XMLRPC endpoint, this backend requires ``mod_admin_extra`` to be installed.
.. WARNING::
The backend does not handle UTF-8 characters correctly if you use ejabberd <= 14.07 and
Python 3.
**ejabberd configuration:** The ``xmlrpc`` module is included with ejabberd_ since version 13.12. If you
use an earlier version, please get and run the module from the `ejabberd-contrib
<https://github.com/processone/ejabberd-contrib>`_ repository. Configuring the interface is simple::
listen:
- ip: "127.0.0.1"
port: 4560
module: ejabberd_xmlrpc
:param uri: Directly passed to xmlrpclib, defaults to ``"http://127.0.0.1:4560"``.
:param transport: Directly passed to xmlrpclib.
:param encoding: Directly passed to xmlrpclib.
:param verbose: Directly passed to xmlrpclib.
:param allow_none: Directly passed to xmlrpclib.
:param use_datetime: Directly passed to xmlrpclib.
:param context: Directly passed to xmlrpclib. Ignored in in Python3, where the parameter is still
documented but no longer accepted by the ServerProxy constructor.
:param user: Username of the JID used for authentication.
:param server: Server of the JID used for authenticiation.
:param password: The password of the given JID.
:param version: Deprecated, no longer use this parameter.
"""
credentials = None
def __init__(self, uri='http://127.0.0.1:4560', transport=None, encoding=None, verbose=0, allow_none=0,
use_datetime=0, context=None, user=None, server=None, password=None, version=None,
**kwargs):
super(EjabberdXMLRPCBackend, self).__init__(**kwargs)
if version is not None:
warnings.warn("The version parameter is deprecated.", DeprecationWarning)
kwargs = {
'transport': transport,
'encoding': encoding,
'verbose': verbose,
'allow_none': allow_none,
'use_datetime': use_datetime,
}
if six.PY2 and version <= (14, 7, ):
kwargs['utf8_encoding'] = 'php'
kwargs['context'] = context
self.client = xmlrpclib.ServerProxy(uri, **kwargs)
if user is not None:
self.credentials = {
'user': user,
'server': server,
'password': password,
}
def get_api_version(self):
result = self.rpc('status')
if result['res'] == 0:
return self.parse_status_string(result.get('text', ''))
else:
raise BackendError(result.get('text', 'Unknown Error'))
def create_user(self, username, domain, password, email=None):
result = self.rpc('register', user=username, host=domain, password=password)
if result['res'] == 0:
try:
# we ignore errors here because not setting last activity is only a problem in edge-cases.
self.set_last_activity(username, domain, status='Registered')
except BackendError as e:
log.error('Error setting last activity: %s', e)
if email is not None:
self.set_email(username, domain, email)
elif result['res'] == 1:
raise UserExists()
else:
raise BackendError(result.get('text', 'Unknown Error'))
def get_last_activity(self, username, domain):
result = self.rpc('get_last', user=username, host=domain)
if self.api_version < (17, 4):
# ejabberd 17.04 introduced a change:
# https://github.com/processone/ejabberd/issues/1565
activity = result['last_activity']
if activity == 'Online':
return datetime.utcnow()
elif activity == 'Never':
if self.user_exists(username, domain):
return None
raise UserNotFound(username, domain)
else:
return datetime.strptime(activity[:19], '%Y-%m-%d %H:%M:%S')
else:
data = result['last_activity']
if data[1]['status'] == 'NOT FOUND':
raise UserNotFound(username, domain)
timestamp = data[0]['timestamp']
if len(timestamp) == 27:
# NOTE: This format is encountered when the user is not found.
fmt = '%Y-%m-%dT%H:%M:%S.%fZ'
else:
fmt = '%Y-%m-%dT%H:%M:%SZ'
return datetime.strptime(timestamp, fmt)
def set_last_activity(self, username, domain, status='', timestamp=None):
timestamp = self.datetime_to_timestamp(timestamp)
self.rpc('set_last', user=username, host=domain, timestamp=timestamp, status=status)
def user_exists(self, username, domain):
result = self.rpc('check_account', user=username, host=domain)
if result['res'] == 0:
return True
elif result['res'] == 1:
return False
else:
raise BackendError(result.get('text', 'Unknown Error'))
def user_sessions(self, username, domain):
result = self.rpc('user_sessions_info', user=username, host=domain)
raw_sessions = result.get('sessions_info', [])
sessions = set()
for data in raw_sessions:
# The data structure is a bit weird, its a list of one-element dicts. We itemize each dict and
# then flatten the resulting list
session = [d.items() for d in data['session']]
session = dict([item for sublist in session for item in sublist])
started = pytz.utc.localize(datetime.utcnow() - timedelta(seconds=session['uptime']))
typ, encrypted, compressed = self.parse_connection_string(session['connection'])
sessions.add(UserSession(
backend=self,
username=username,
domain=domain,
resource=session['resource'],
priority=session['priority'],
ip_address=self.parse_ip_address(session['ip']),
uptime=started,
status=session['status'],
status_text=session['statustext'],
connection_type=typ, encrypted=encrypted, compressed=compressed
))
if len(sessions) == 0 and self.api_version <= (15, 7):
raise NotSupportedError("ejabberd <= 15.07 always returns an empty list.")
return sessions
def stop_user_session(self, username, domain, resource, reason=''):
result = self.rpc('kick_session', user=username, host=domain, resource=resource,
reason=reason)
return result
def check_password(self, username, domain, password):
result = self.rpc('check_password', user=username, host=domain, password=password)
if result['res'] == 0:
return True
elif result['res'] == 1:
return False
else:
raise BackendError(result.get('text', 'Unknown Error'))
def set_password(self, username, domain, password):
if self.api_version <= (16, 1, ) and not self.user_exists(username, domain):
# 16.01 just creates the user upon change_password!
# NOTE: This may also affect other versions < 16.09.
raise UserNotFound(username, domain)
try:
result = self.rpc('change_password', user=username, host=domain, newpass=password)
except xmlrpclib.Fault as e:
if e.faultCode == -118:
raise UserNotFound(username, domain)
raise BackendError('Unknown Error')
if result['res'] == 0:
return
else:
raise BackendError(result.get('text', 'Unknown Error'))
def block_user(self, username, domain):
try:
result = self.rpc('ban_account', user=username, host=domain, reason='Blocked.')
except BackendError:
if self.api_version == (14, 7):
raise NotSupportedError('ejabberd 14.07 does not support getting all sessions via xmlrpc.')
raise
if result['res'] == 0:
return
else:
raise BackendError(result.get('text', 'Unknown Error'))
def message_user(self, username, domain, subject, message):
"""Currently use send_message_chat and discard subject, because headline messages are not
stored by mod_offline."""
kwargs = {
'body': message,
'from': domain,
'to': '%s@%s' % (username, domain),
}
if self.api_version <= (14, 7):
# TODO: it's unclear when send_message was introduced
command = 'send_message_chat'
else:
command = 'send_message'
kwargs['subject'] = subject
kwargs['type'] = 'normal'
result = self.rpc(command, **kwargs)
if result['res'] == 0:
return
else:
raise BackendError(result.get('text', 'Unknown Error'))
def all_domains(self):
return [d['vhost'] for d in self.rpc('registered_vhosts')['vhosts']]
def all_users(self, domain):
users = self.rpc('registered_users', host=domain)['users']
return set([e['username'] for e in users])
def all_user_sessions(self):
try:
result = self.rpc('connected_users_info')['connected_users_info']
except BackendError:
if self.api_version == (14, 7):
raise NotSupportedError('ejabberd 14.07 does not support getting all sessions via xmlrpc.')
raise
if self.api_version < (18, 6):
# The key used here was silently changed in 18.06.
sessions_key = 'sessions'
else:
sessions_key = 'session'
sessions = set()
for data in result:
# The data structure is a bit weird, its a list of one-element dicts. We itemize each dict and
# then flatten the resulting list
session = [d.items() for d in data[sessions_key]]
session = dict([item for sublist in session for item in sublist])
username, domain = session['jid'].split('@', 1)
domain, resource = domain.split('/', 1)
started = pytz.utc.localize(datetime.utcnow() - timedelta(seconds=session['uptime']))
typ, encrypted, compressed = self.parse_connection_string(session['connection'])
sessions.add(UserSession(
backend=self,
username=username,
domain=domain,
resource=resource,
priority=session['priority'],
ip_address=self.parse_ip_address(session['ip']),
uptime=started,
status=session.get('status', ''), # ejabberd <= 18.04 does not contain this key
status_text=session.get('statustext', ''), # ejabberd <= 18.04 does not contain this key
connection_type=typ, encrypted=encrypted, compressed=compressed
))
if len(sessions) == 0 and self.api_version == (15, 7):
raise NotSupportedError("ejabberd <= 15.07 always returns an empty list.")
return sessions
def remove_user(self, username, domain):
result = self.rpc('unregister', user=username, host=domain)
if result['res'] == 0:
return
else:
raise BackendError(result.get('text', 'Unknown Error'))
def stats(self, stat, domain=None):
if stat == 'registered_users':
stat = 'registeredusers'
elif stat == 'online_users':
stat = 'onlineusers'
else:
raise ValueError("Unknown stat %s" % stat)
if domain is None:
result = self.rpc('stats', name=stat)
else:
result = self.rpc('stats_host', name=stat, host=domain)
try:
return result['stat']
except KeyError:
raise BackendError(result.get('text', 'Unknown Error'))
|
mathiasertl/xmpp-backends
|
xmpp_backends/ejabberd_xmlrpc.py
|
EjabberdXMLRPCBackend.message_user
|
python
|
def message_user(self, username, domain, subject, message):
kwargs = {
'body': message,
'from': domain,
'to': '%s@%s' % (username, domain),
}
if self.api_version <= (14, 7):
# TODO: it's unclear when send_message was introduced
command = 'send_message_chat'
else:
command = 'send_message'
kwargs['subject'] = subject
kwargs['type'] = 'normal'
result = self.rpc(command, **kwargs)
if result['res'] == 0:
return
else:
raise BackendError(result.get('text', 'Unknown Error'))
|
Currently use send_message_chat and discard subject, because headline messages are not
stored by mod_offline.
|
train
|
https://github.com/mathiasertl/xmpp-backends/blob/214ef0664dbf90fa300c2483b9b3416559e5d171/xmpp_backends/ejabberd_xmlrpc.py#L263-L285
|
[
"def rpc(self, cmd, **kwargs):\n \"\"\"Generic helper function to call an RPC method.\"\"\"\n\n func = getattr(self.client, cmd)\n try:\n if self.credentials is None:\n return func(kwargs)\n else:\n return func(self.credentials, kwargs)\n except socket.error as e:\n raise BackendConnectionError(e)\n except (xmlrpclib.ProtocolError, BadStatusLine) as e:\n log.error(e)\n raise BackendError(\"Error reaching backend.\")\n"
] |
class EjabberdXMLRPCBackend(EjabberdBackendBase):
"""This backend uses the Ejabberd XMLRPC interface.
In addition to an XMLRPC endpoint, this backend requires ``mod_admin_extra`` to be installed.
.. WARNING::
The backend does not handle UTF-8 characters correctly if you use ejabberd <= 14.07 and
Python 3.
**ejabberd configuration:** The ``xmlrpc`` module is included with ejabberd_ since version 13.12. If you
use an earlier version, please get and run the module from the `ejabberd-contrib
<https://github.com/processone/ejabberd-contrib>`_ repository. Configuring the interface is simple::
listen:
- ip: "127.0.0.1"
port: 4560
module: ejabberd_xmlrpc
:param uri: Directly passed to xmlrpclib, defaults to ``"http://127.0.0.1:4560"``.
:param transport: Directly passed to xmlrpclib.
:param encoding: Directly passed to xmlrpclib.
:param verbose: Directly passed to xmlrpclib.
:param allow_none: Directly passed to xmlrpclib.
:param use_datetime: Directly passed to xmlrpclib.
:param context: Directly passed to xmlrpclib. Ignored in in Python3, where the parameter is still
documented but no longer accepted by the ServerProxy constructor.
:param user: Username of the JID used for authentication.
:param server: Server of the JID used for authenticiation.
:param password: The password of the given JID.
:param version: Deprecated, no longer use this parameter.
"""
credentials = None
def __init__(self, uri='http://127.0.0.1:4560', transport=None, encoding=None, verbose=0, allow_none=0,
use_datetime=0, context=None, user=None, server=None, password=None, version=None,
**kwargs):
super(EjabberdXMLRPCBackend, self).__init__(**kwargs)
if version is not None:
warnings.warn("The version parameter is deprecated.", DeprecationWarning)
kwargs = {
'transport': transport,
'encoding': encoding,
'verbose': verbose,
'allow_none': allow_none,
'use_datetime': use_datetime,
}
if six.PY2 and version <= (14, 7, ):
kwargs['utf8_encoding'] = 'php'
kwargs['context'] = context
self.client = xmlrpclib.ServerProxy(uri, **kwargs)
if user is not None:
self.credentials = {
'user': user,
'server': server,
'password': password,
}
def rpc(self, cmd, **kwargs):
"""Generic helper function to call an RPC method."""
func = getattr(self.client, cmd)
try:
if self.credentials is None:
return func(kwargs)
else:
return func(self.credentials, kwargs)
except socket.error as e:
raise BackendConnectionError(e)
except (xmlrpclib.ProtocolError, BadStatusLine) as e:
log.error(e)
raise BackendError("Error reaching backend.")
def get_api_version(self):
result = self.rpc('status')
if result['res'] == 0:
return self.parse_status_string(result.get('text', ''))
else:
raise BackendError(result.get('text', 'Unknown Error'))
def create_user(self, username, domain, password, email=None):
result = self.rpc('register', user=username, host=domain, password=password)
if result['res'] == 0:
try:
# we ignore errors here because not setting last activity is only a problem in edge-cases.
self.set_last_activity(username, domain, status='Registered')
except BackendError as e:
log.error('Error setting last activity: %s', e)
if email is not None:
self.set_email(username, domain, email)
elif result['res'] == 1:
raise UserExists()
else:
raise BackendError(result.get('text', 'Unknown Error'))
def get_last_activity(self, username, domain):
result = self.rpc('get_last', user=username, host=domain)
if self.api_version < (17, 4):
# ejabberd 17.04 introduced a change:
# https://github.com/processone/ejabberd/issues/1565
activity = result['last_activity']
if activity == 'Online':
return datetime.utcnow()
elif activity == 'Never':
if self.user_exists(username, domain):
return None
raise UserNotFound(username, domain)
else:
return datetime.strptime(activity[:19], '%Y-%m-%d %H:%M:%S')
else:
data = result['last_activity']
if data[1]['status'] == 'NOT FOUND':
raise UserNotFound(username, domain)
timestamp = data[0]['timestamp']
if len(timestamp) == 27:
# NOTE: This format is encountered when the user is not found.
fmt = '%Y-%m-%dT%H:%M:%S.%fZ'
else:
fmt = '%Y-%m-%dT%H:%M:%SZ'
return datetime.strptime(timestamp, fmt)
def set_last_activity(self, username, domain, status='', timestamp=None):
timestamp = self.datetime_to_timestamp(timestamp)
self.rpc('set_last', user=username, host=domain, timestamp=timestamp, status=status)
def user_exists(self, username, domain):
result = self.rpc('check_account', user=username, host=domain)
if result['res'] == 0:
return True
elif result['res'] == 1:
return False
else:
raise BackendError(result.get('text', 'Unknown Error'))
def user_sessions(self, username, domain):
result = self.rpc('user_sessions_info', user=username, host=domain)
raw_sessions = result.get('sessions_info', [])
sessions = set()
for data in raw_sessions:
# The data structure is a bit weird, its a list of one-element dicts. We itemize each dict and
# then flatten the resulting list
session = [d.items() for d in data['session']]
session = dict([item for sublist in session for item in sublist])
started = pytz.utc.localize(datetime.utcnow() - timedelta(seconds=session['uptime']))
typ, encrypted, compressed = self.parse_connection_string(session['connection'])
sessions.add(UserSession(
backend=self,
username=username,
domain=domain,
resource=session['resource'],
priority=session['priority'],
ip_address=self.parse_ip_address(session['ip']),
uptime=started,
status=session['status'],
status_text=session['statustext'],
connection_type=typ, encrypted=encrypted, compressed=compressed
))
if len(sessions) == 0 and self.api_version <= (15, 7):
raise NotSupportedError("ejabberd <= 15.07 always returns an empty list.")
return sessions
def stop_user_session(self, username, domain, resource, reason=''):
result = self.rpc('kick_session', user=username, host=domain, resource=resource,
reason=reason)
return result
def check_password(self, username, domain, password):
result = self.rpc('check_password', user=username, host=domain, password=password)
if result['res'] == 0:
return True
elif result['res'] == 1:
return False
else:
raise BackendError(result.get('text', 'Unknown Error'))
def set_password(self, username, domain, password):
if self.api_version <= (16, 1, ) and not self.user_exists(username, domain):
# 16.01 just creates the user upon change_password!
# NOTE: This may also affect other versions < 16.09.
raise UserNotFound(username, domain)
try:
result = self.rpc('change_password', user=username, host=domain, newpass=password)
except xmlrpclib.Fault as e:
if e.faultCode == -118:
raise UserNotFound(username, domain)
raise BackendError('Unknown Error')
if result['res'] == 0:
return
else:
raise BackendError(result.get('text', 'Unknown Error'))
def block_user(self, username, domain):
try:
result = self.rpc('ban_account', user=username, host=domain, reason='Blocked.')
except BackendError:
if self.api_version == (14, 7):
raise NotSupportedError('ejabberd 14.07 does not support getting all sessions via xmlrpc.')
raise
if result['res'] == 0:
return
else:
raise BackendError(result.get('text', 'Unknown Error'))
def all_domains(self):
return [d['vhost'] for d in self.rpc('registered_vhosts')['vhosts']]
def all_users(self, domain):
users = self.rpc('registered_users', host=domain)['users']
return set([e['username'] for e in users])
def all_user_sessions(self):
try:
result = self.rpc('connected_users_info')['connected_users_info']
except BackendError:
if self.api_version == (14, 7):
raise NotSupportedError('ejabberd 14.07 does not support getting all sessions via xmlrpc.')
raise
if self.api_version < (18, 6):
# The key used here was silently changed in 18.06.
sessions_key = 'sessions'
else:
sessions_key = 'session'
sessions = set()
for data in result:
# The data structure is a bit weird, its a list of one-element dicts. We itemize each dict and
# then flatten the resulting list
session = [d.items() for d in data[sessions_key]]
session = dict([item for sublist in session for item in sublist])
username, domain = session['jid'].split('@', 1)
domain, resource = domain.split('/', 1)
started = pytz.utc.localize(datetime.utcnow() - timedelta(seconds=session['uptime']))
typ, encrypted, compressed = self.parse_connection_string(session['connection'])
sessions.add(UserSession(
backend=self,
username=username,
domain=domain,
resource=resource,
priority=session['priority'],
ip_address=self.parse_ip_address(session['ip']),
uptime=started,
status=session.get('status', ''), # ejabberd <= 18.04 does not contain this key
status_text=session.get('statustext', ''), # ejabberd <= 18.04 does not contain this key
connection_type=typ, encrypted=encrypted, compressed=compressed
))
if len(sessions) == 0 and self.api_version == (15, 7):
raise NotSupportedError("ejabberd <= 15.07 always returns an empty list.")
return sessions
def remove_user(self, username, domain):
result = self.rpc('unregister', user=username, host=domain)
if result['res'] == 0:
return
else:
raise BackendError(result.get('text', 'Unknown Error'))
def stats(self, stat, domain=None):
if stat == 'registered_users':
stat = 'registeredusers'
elif stat == 'online_users':
stat = 'onlineusers'
else:
raise ValueError("Unknown stat %s" % stat)
if domain is None:
result = self.rpc('stats', name=stat)
else:
result = self.rpc('stats_host', name=stat, host=domain)
try:
return result['stat']
except KeyError:
raise BackendError(result.get('text', 'Unknown Error'))
|
mathiasertl/xmpp-backends
|
xmpp_backends/base.py
|
XmppBackendBase.module
|
python
|
def module(self):
if self._module is None:
if self.library is None:
raise ValueError(
"Backend '%s' doesn't specify a library attribute" % self.__class__)
try:
if '.' in self.library:
mod_path, cls_name = self.library.rsplit('.', 1)
mod = import_module(mod_path)
self._module = getattr(mod, cls_name)
else:
self._module = import_module(self.library)
except (AttributeError, ImportError):
raise ValueError("Couldn't load %s backend library" % cls_name)
return self._module
|
The module specified by the ``library`` attribute.
|
train
|
https://github.com/mathiasertl/xmpp-backends/blob/214ef0664dbf90fa300c2483b9b3416559e5d171/xmpp_backends/base.py#L174-L192
| null |
class XmppBackendBase(object):
"""Base class for all XMPP backends."""
library = None
"""Import-party of any third-party library you need.
Set this attribute to an import path and you will be able to access the module as ``self.module``. This
way you don't have to do a module-level import, which would mean that everyone has to have that library
installed, even if they're not using your backend.
:param version_cache_timeout: How long the API version for this backend will be cached.
:type version_cache_timeout: int or timedelta
"""
_module = None
minimum_version = None
version_cache_timeout = None
version_cache_timestamp = None
version_cache_value = None
def __init__(self, version_cache_timeout=3600):
if isinstance(version_cache_timeout, int):
version_cache_timeout = timedelta(seconds=version_cache_timeout)
self.version_cache_timeout = version_cache_timeout
super(XmppBackendBase, self).__init__()
@property
def datetime_to_timestamp(self, dt):
"""Helper function to convert a datetime object to a timestamp.
If datetime instance ``dt`` is naive, it is assumed that it is in UTC.
In Python 3, this just calls ``datetime.timestamp()``, in Python 2, it substracts any timezone offset
and returns the difference since 1970-01-01 00:00:00.
Note that the function always returns an int, even in Python 3.
>>> XmppBackendBase().datetime_to_timestamp(datetime(2017, 9, 17, 19, 59))
1505678340
>>> XmppBackendBase().datetime_to_timestamp(datetime(1984, 11, 6, 13, 21))
468595260
:param dt: The datetime object to convert. If ``None``, returns the current time.
:type dt: datetime
:return: The seconds in UTC.
:rtype: int
"""
if dt is None:
return int(time.time())
if six.PY3:
if not dt.tzinfo:
dt = pytz.utc.localize(dt)
return int(dt.timestamp())
else:
if dt.tzinfo:
dt = dt.replace(tzinfo=None) - dt.utcoffset()
return int((dt - datetime(1970, 1, 1)).total_seconds())
def get_random_password(self, length=32, chars=None):
"""Helper function that gets a random password.
:param length: The length of the random password.
:type length: int
:param chars: A string with characters to choose from. Defaults to all ASCII letters and digits.
:type chars: str
"""
if chars is None:
chars = string.ascii_letters + string.digits
return ''.join(random.choice(chars) for x in range(length))
@property
def api_version(self):
"""Cached version of :py:func:`~xmpp_backends.base.XmppBackendBase.get_api_version`."""
now = datetime.utcnow()
if self.version_cache_timestamp and self.version_cache_timestamp + self.version_cache_timeout > now:
return self.version_cache_value # we have a cached value
self.version_cache_value = self.get_api_version()
if self.minimum_version and self.version_cache_value < self.minimum_version:
raise NotSupportedError('%s requires ejabberd >= %s' % (self.__class__.__name__,
self.minimum_version))
self.version_cache_timestamp = now
return self.version_cache_value
def get_api_version(self):
"""Get the API version used by this backend.
Note that this function is usually not invoked directly but through
:py:attr:`~xmpp_backends.base.XmppBackendBase.api_version`.
The value returned by this function is used by various backends to determine how to call various API
backends and/or how to parse th data returned by them. Backends generally assume that this function is
always working and return the correct value.
If your backend implementation cannot get this value, it should be passed via the constructor and
statically returned for the livetime of the instance.
"""
raise NotImplementedError
def user_exists(self, username, domain):
"""Verify that the given user exists.
:param username: The username of the user.
:type username: str
:param domain: The domain of the user.
:type domain: str
:return: ``True`` if the user exists, ``False`` if not.
:rtype: bool
"""
raise NotImplementedError
def user_sessions(self, username, domain):
"""Get a list of all current sessions for the given user.
:param username: The username of the user.
:type username: str
:param domain: The domain of the user.
:type domain: str
:return: A list :py:class:`~xmpp_backends.base.UserSession` describing the user sessions.
:rtype: list of :py:class:`~xmpp_backends.base.UserSession`
"""
raise NotImplementedError
def stop_user_session(self, username, domain, resource, reason=''):
"""Stop a specific user session, identified by its resource.
A resource uniquely identifies a connection by a specific client.
:param username: The username of the user.
:type username: str
:param domain: The domain of the user.
:type domain: str
:param resource: The resource of the connection
:type resource: str
"""
raise NotImplementedError
def create_user(self, username, domain, password, email=None):
"""Create a new user.
:param username: The username of the new user.
:type username: str
:param domain: The domain of the new user.
:type domain: str
:param password: The password of the new user.
:param email: The email address provided by the user.
"""
raise NotImplementedError
def create_reservation(self, username, domain, email=None):
"""Reserve a new account.
This method is called when a user account should be reserved, meaning that the account can no longer
be registered by anybody else but the user cannot yet log in either. This is useful if e.g. an email
confirmation is still pending.
The default implementation calls :py:func:`~xmpp_backends.base.XmppBackendBase.create_user` with a
random password.
:param username: The username of the user.
:type username: str
:param domain: The domain of the user.
:type domain: str
:param email: The email address provided by the user. Note that at this point it is not confirmed.
You are free to ignore this parameter.
"""
password = self.get_random_password()
self.create(username=username, domain=domain, password=password, email=email)
def confirm_reservation(self, username, domain, password, email=None):
"""Confirm a reservation for a username.
The default implementation just calls :py:func:`~xmpp_backends.base.XmppBackendBase.set_password` and
optionally :py:func:`~xmpp_backends.base.XmppBackendBase.set_email`.
"""
self.set_password(username=username, domain=domain, password=password)
if email is not None:
self.set_email(username=username, domain=domain, email=email)
def check_password(self, username, domain, password):
"""Check the password of a user.
:param username: The username of the user.
:type username: str
:param domain: The domain of the user.
:type domain: str
:param password: The password to check.
:type password: str
:return: ``True`` if the password is correct, ``False`` if not.
:rtype: bool
"""
raise NotImplementedError
def set_password(self, username, domain, password):
"""Set the password of a user.
:param username: The username of the user.
:type username: str
:param domain: The domain of the user.
:type domain: str
:param password: The password to set.
:type password: str
"""
raise NotImplementedError
def get_last_activity(self, username, domain):
"""Get the last activity of the user.
The datetime object returned should be a naive datetime object representing the time in UTC.
:param username: The username of the user.
:type username: str
:param domain: The domain of the user.
:type domain: str
:return: A naive datetime object in UTC representing the last activity.
:rtype: datetime
"""
raise NotImplementedError
def set_last_activity(self, username, domain, status='', timestamp=None):
"""Set the last activity of the user.
.. NOTE::
If your backend requires a Unix timestamp (seconds since 1970-01-01), you can use the
:py:func:`~xmpp_backends.base.XmppBackendBase.datetime_to_timestamp` convenience function to
convert it to an integer.
:param username: The username of the user.
:type username: str
:param domain: The domain of the user.
:type domain: str
:param status: The status text.
:type status: str
:param timestamp: A datetime object representing the last activity. If the object is not
timezone-aware, assume UTC. If ``timestamp`` is ``None``, assume the current date and time.
:type timestamp: datetime
"""
raise NotImplementedError
def block_user(self, username, domain):
"""Block the specified user.
The default implementation calls :py:func:`~xmpp_backends.base.XmppBackendBase.set_password` with a
random password.
:param username: The username of the user.
:type username: str
:param domain: The domain of the user.
:type domain: str
"""
self.set_password(username, domain, self.get_random_password())
def set_email(self, username, domain, email):
"""Set the email address of a user."""
raise NotImplementedError
def check_email(self, username, domain, email):
"""Check the email address of a user.
**Note:** Most backends don't implement this feature.
:param username: The username of the user.
:type username: str
:param domain: The domain of the user.
:type domain: str
"""
raise NotImplementedError
def expire_reservation(self, username, domain):
"""Expire a username reservation.
This method is called when a reservation expires. The default implementation just calls
:py:func:`~xmpp_backends.base.XmppBackendBase.remove_user`. This is fine if you do not override
:py:func:`~xmpp_backends.base.XmppBackendBase.create_reservation`.
:param username: The username of the user.
:type username: str
:param domain: The domain of the user.
:type domain: str
"""
self.remove_user(username, domain)
def message_user(self, username, domain, subject, message):
"""Send a message to the given user.
:param username: The username of the user.
:type username: str
:param domain: The domain of the user.
:type domain: str
:param subject: The subject of the message.
:param message: The content of the message.
"""
pass
def all_users(self, domain):
"""Get all users for a given domain.
:param domain: The domain of interest.
:type domain: str
:return: A set of all users. The usernames do not include the domain, so ``user@example.com`` will
just be ``"user"``.
:rtype: set of str
"""
raise NotImplementedError
def all_domains(self):
"""List of all domains used by this backend.
:return: List of all domains served by this backend.
:rtype: list of str
"""
raise NotImplementedError
def all_user_sessions(self):
"""List all current user sessions.
:param domain: Optionally only return sessions for the given domain.
:return: A list :py:class:`~xmpp_backends.base.UserSession` for all sessions.
:rtype: list of :py:class:`~xmpp_backends.base.UserSession`
"""
raise NotImplementedError
def remove_user(self, username, domain):
"""Remove a user.
This method is called when the user explicitly wants to remove her/his account.
:param username: The username of the new user.
:type username: str
:param domain: The domain of the user.
:type domain: str
"""
raise NotImplementedError
def stats(self, stat, domain=None):
"""Get statistical value about the XMPP server.
Minimal statistics that should be supported is ``"registered_users"`` and ``"online_users"``. The
specific backend might support additional stats.
:param stat: The value of the statistic.
:type stat: str
:param domain: Limit statistic to the given domain. If not listed, give statistics
about all users.
:type domain: str
:return: The current value of the requested statistic.
:rtype: int
"""
raise NotImplementedError
|
mathiasertl/xmpp-backends
|
xmpp_backends/base.py
|
XmppBackendBase.datetime_to_timestamp
|
python
|
def datetime_to_timestamp(self, dt):
if dt is None:
return int(time.time())
if six.PY3:
if not dt.tzinfo:
dt = pytz.utc.localize(dt)
return int(dt.timestamp())
else:
if dt.tzinfo:
dt = dt.replace(tzinfo=None) - dt.utcoffset()
return int((dt - datetime(1970, 1, 1)).total_seconds())
|
Helper function to convert a datetime object to a timestamp.
If datetime instance ``dt`` is naive, it is assumed that it is in UTC.
In Python 3, this just calls ``datetime.timestamp()``, in Python 2, it substracts any timezone offset
and returns the difference since 1970-01-01 00:00:00.
Note that the function always returns an int, even in Python 3.
>>> XmppBackendBase().datetime_to_timestamp(datetime(2017, 9, 17, 19, 59))
1505678340
>>> XmppBackendBase().datetime_to_timestamp(datetime(1984, 11, 6, 13, 21))
468595260
:param dt: The datetime object to convert. If ``None``, returns the current time.
:type dt: datetime
:return: The seconds in UTC.
:rtype: int
|
train
|
https://github.com/mathiasertl/xmpp-backends/blob/214ef0664dbf90fa300c2483b9b3416559e5d171/xmpp_backends/base.py#L194-L224
| null |
class XmppBackendBase(object):
"""Base class for all XMPP backends."""
library = None
"""Import-party of any third-party library you need.
Set this attribute to an import path and you will be able to access the module as ``self.module``. This
way you don't have to do a module-level import, which would mean that everyone has to have that library
installed, even if they're not using your backend.
:param version_cache_timeout: How long the API version for this backend will be cached.
:type version_cache_timeout: int or timedelta
"""
_module = None
minimum_version = None
version_cache_timeout = None
version_cache_timestamp = None
version_cache_value = None
def __init__(self, version_cache_timeout=3600):
if isinstance(version_cache_timeout, int):
version_cache_timeout = timedelta(seconds=version_cache_timeout)
self.version_cache_timeout = version_cache_timeout
super(XmppBackendBase, self).__init__()
@property
def module(self):
"""The module specified by the ``library`` attribute."""
if self._module is None:
if self.library is None:
raise ValueError(
"Backend '%s' doesn't specify a library attribute" % self.__class__)
try:
if '.' in self.library:
mod_path, cls_name = self.library.rsplit('.', 1)
mod = import_module(mod_path)
self._module = getattr(mod, cls_name)
else:
self._module = import_module(self.library)
except (AttributeError, ImportError):
raise ValueError("Couldn't load %s backend library" % cls_name)
return self._module
def get_random_password(self, length=32, chars=None):
"""Helper function that gets a random password.
:param length: The length of the random password.
:type length: int
:param chars: A string with characters to choose from. Defaults to all ASCII letters and digits.
:type chars: str
"""
if chars is None:
chars = string.ascii_letters + string.digits
return ''.join(random.choice(chars) for x in range(length))
@property
def api_version(self):
"""Cached version of :py:func:`~xmpp_backends.base.XmppBackendBase.get_api_version`."""
now = datetime.utcnow()
if self.version_cache_timestamp and self.version_cache_timestamp + self.version_cache_timeout > now:
return self.version_cache_value # we have a cached value
self.version_cache_value = self.get_api_version()
if self.minimum_version and self.version_cache_value < self.minimum_version:
raise NotSupportedError('%s requires ejabberd >= %s' % (self.__class__.__name__,
self.minimum_version))
self.version_cache_timestamp = now
return self.version_cache_value
def get_api_version(self):
"""Get the API version used by this backend.
Note that this function is usually not invoked directly but through
:py:attr:`~xmpp_backends.base.XmppBackendBase.api_version`.
The value returned by this function is used by various backends to determine how to call various API
backends and/or how to parse th data returned by them. Backends generally assume that this function is
always working and return the correct value.
If your backend implementation cannot get this value, it should be passed via the constructor and
statically returned for the livetime of the instance.
"""
raise NotImplementedError
def user_exists(self, username, domain):
"""Verify that the given user exists.
:param username: The username of the user.
:type username: str
:param domain: The domain of the user.
:type domain: str
:return: ``True`` if the user exists, ``False`` if not.
:rtype: bool
"""
raise NotImplementedError
def user_sessions(self, username, domain):
"""Get a list of all current sessions for the given user.
:param username: The username of the user.
:type username: str
:param domain: The domain of the user.
:type domain: str
:return: A list :py:class:`~xmpp_backends.base.UserSession` describing the user sessions.
:rtype: list of :py:class:`~xmpp_backends.base.UserSession`
"""
raise NotImplementedError
def stop_user_session(self, username, domain, resource, reason=''):
"""Stop a specific user session, identified by its resource.
A resource uniquely identifies a connection by a specific client.
:param username: The username of the user.
:type username: str
:param domain: The domain of the user.
:type domain: str
:param resource: The resource of the connection
:type resource: str
"""
raise NotImplementedError
def create_user(self, username, domain, password, email=None):
"""Create a new user.
:param username: The username of the new user.
:type username: str
:param domain: The domain of the new user.
:type domain: str
:param password: The password of the new user.
:param email: The email address provided by the user.
"""
raise NotImplementedError
def create_reservation(self, username, domain, email=None):
"""Reserve a new account.
This method is called when a user account should be reserved, meaning that the account can no longer
be registered by anybody else but the user cannot yet log in either. This is useful if e.g. an email
confirmation is still pending.
The default implementation calls :py:func:`~xmpp_backends.base.XmppBackendBase.create_user` with a
random password.
:param username: The username of the user.
:type username: str
:param domain: The domain of the user.
:type domain: str
:param email: The email address provided by the user. Note that at this point it is not confirmed.
You are free to ignore this parameter.
"""
password = self.get_random_password()
self.create(username=username, domain=domain, password=password, email=email)
def confirm_reservation(self, username, domain, password, email=None):
"""Confirm a reservation for a username.
The default implementation just calls :py:func:`~xmpp_backends.base.XmppBackendBase.set_password` and
optionally :py:func:`~xmpp_backends.base.XmppBackendBase.set_email`.
"""
self.set_password(username=username, domain=domain, password=password)
if email is not None:
self.set_email(username=username, domain=domain, email=email)
def check_password(self, username, domain, password):
"""Check the password of a user.
:param username: The username of the user.
:type username: str
:param domain: The domain of the user.
:type domain: str
:param password: The password to check.
:type password: str
:return: ``True`` if the password is correct, ``False`` if not.
:rtype: bool
"""
raise NotImplementedError
def set_password(self, username, domain, password):
"""Set the password of a user.
:param username: The username of the user.
:type username: str
:param domain: The domain of the user.
:type domain: str
:param password: The password to set.
:type password: str
"""
raise NotImplementedError
def get_last_activity(self, username, domain):
"""Get the last activity of the user.
The datetime object returned should be a naive datetime object representing the time in UTC.
:param username: The username of the user.
:type username: str
:param domain: The domain of the user.
:type domain: str
:return: A naive datetime object in UTC representing the last activity.
:rtype: datetime
"""
raise NotImplementedError
def set_last_activity(self, username, domain, status='', timestamp=None):
"""Set the last activity of the user.
.. NOTE::
If your backend requires a Unix timestamp (seconds since 1970-01-01), you can use the
:py:func:`~xmpp_backends.base.XmppBackendBase.datetime_to_timestamp` convenience function to
convert it to an integer.
:param username: The username of the user.
:type username: str
:param domain: The domain of the user.
:type domain: str
:param status: The status text.
:type status: str
:param timestamp: A datetime object representing the last activity. If the object is not
timezone-aware, assume UTC. If ``timestamp`` is ``None``, assume the current date and time.
:type timestamp: datetime
"""
raise NotImplementedError
def block_user(self, username, domain):
"""Block the specified user.
The default implementation calls :py:func:`~xmpp_backends.base.XmppBackendBase.set_password` with a
random password.
:param username: The username of the user.
:type username: str
:param domain: The domain of the user.
:type domain: str
"""
self.set_password(username, domain, self.get_random_password())
def set_email(self, username, domain, email):
"""Set the email address of a user."""
raise NotImplementedError
def check_email(self, username, domain, email):
"""Check the email address of a user.
**Note:** Most backends don't implement this feature.
:param username: The username of the user.
:type username: str
:param domain: The domain of the user.
:type domain: str
"""
raise NotImplementedError
def expire_reservation(self, username, domain):
"""Expire a username reservation.
This method is called when a reservation expires. The default implementation just calls
:py:func:`~xmpp_backends.base.XmppBackendBase.remove_user`. This is fine if you do not override
:py:func:`~xmpp_backends.base.XmppBackendBase.create_reservation`.
:param username: The username of the user.
:type username: str
:param domain: The domain of the user.
:type domain: str
"""
self.remove_user(username, domain)
def message_user(self, username, domain, subject, message):
"""Send a message to the given user.
:param username: The username of the user.
:type username: str
:param domain: The domain of the user.
:type domain: str
:param subject: The subject of the message.
:param message: The content of the message.
"""
pass
def all_users(self, domain):
"""Get all users for a given domain.
:param domain: The domain of interest.
:type domain: str
:return: A set of all users. The usernames do not include the domain, so ``user@example.com`` will
just be ``"user"``.
:rtype: set of str
"""
raise NotImplementedError
def all_domains(self):
"""List of all domains used by this backend.
:return: List of all domains served by this backend.
:rtype: list of str
"""
raise NotImplementedError
def all_user_sessions(self):
"""List all current user sessions.
:param domain: Optionally only return sessions for the given domain.
:return: A list :py:class:`~xmpp_backends.base.UserSession` for all sessions.
:rtype: list of :py:class:`~xmpp_backends.base.UserSession`
"""
raise NotImplementedError
def remove_user(self, username, domain):
"""Remove a user.
This method is called when the user explicitly wants to remove her/his account.
:param username: The username of the new user.
:type username: str
:param domain: The domain of the user.
:type domain: str
"""
raise NotImplementedError
def stats(self, stat, domain=None):
"""Get statistical value about the XMPP server.
Minimal statistics that should be supported is ``"registered_users"`` and ``"online_users"``. The
specific backend might support additional stats.
:param stat: The value of the statistic.
:type stat: str
:param domain: Limit statistic to the given domain. If not listed, give statistics
about all users.
:type domain: str
:return: The current value of the requested statistic.
:rtype: int
"""
raise NotImplementedError
|
mathiasertl/xmpp-backends
|
xmpp_backends/base.py
|
XmppBackendBase.get_random_password
|
python
|
def get_random_password(self, length=32, chars=None):
if chars is None:
chars = string.ascii_letters + string.digits
return ''.join(random.choice(chars) for x in range(length))
|
Helper function that gets a random password.
:param length: The length of the random password.
:type length: int
:param chars: A string with characters to choose from. Defaults to all ASCII letters and digits.
:type chars: str
|
train
|
https://github.com/mathiasertl/xmpp-backends/blob/214ef0664dbf90fa300c2483b9b3416559e5d171/xmpp_backends/base.py#L226-L236
| null |
class XmppBackendBase(object):
"""Base class for all XMPP backends."""
library = None
"""Import-party of any third-party library you need.
Set this attribute to an import path and you will be able to access the module as ``self.module``. This
way you don't have to do a module-level import, which would mean that everyone has to have that library
installed, even if they're not using your backend.
:param version_cache_timeout: How long the API version for this backend will be cached.
:type version_cache_timeout: int or timedelta
"""
_module = None
minimum_version = None
version_cache_timeout = None
version_cache_timestamp = None
version_cache_value = None
def __init__(self, version_cache_timeout=3600):
if isinstance(version_cache_timeout, int):
version_cache_timeout = timedelta(seconds=version_cache_timeout)
self.version_cache_timeout = version_cache_timeout
super(XmppBackendBase, self).__init__()
@property
def module(self):
"""The module specified by the ``library`` attribute."""
if self._module is None:
if self.library is None:
raise ValueError(
"Backend '%s' doesn't specify a library attribute" % self.__class__)
try:
if '.' in self.library:
mod_path, cls_name = self.library.rsplit('.', 1)
mod = import_module(mod_path)
self._module = getattr(mod, cls_name)
else:
self._module = import_module(self.library)
except (AttributeError, ImportError):
raise ValueError("Couldn't load %s backend library" % cls_name)
return self._module
def datetime_to_timestamp(self, dt):
"""Helper function to convert a datetime object to a timestamp.
If datetime instance ``dt`` is naive, it is assumed that it is in UTC.
In Python 3, this just calls ``datetime.timestamp()``, in Python 2, it substracts any timezone offset
and returns the difference since 1970-01-01 00:00:00.
Note that the function always returns an int, even in Python 3.
>>> XmppBackendBase().datetime_to_timestamp(datetime(2017, 9, 17, 19, 59))
1505678340
>>> XmppBackendBase().datetime_to_timestamp(datetime(1984, 11, 6, 13, 21))
468595260
:param dt: The datetime object to convert. If ``None``, returns the current time.
:type dt: datetime
:return: The seconds in UTC.
:rtype: int
"""
if dt is None:
return int(time.time())
if six.PY3:
if not dt.tzinfo:
dt = pytz.utc.localize(dt)
return int(dt.timestamp())
else:
if dt.tzinfo:
dt = dt.replace(tzinfo=None) - dt.utcoffset()
return int((dt - datetime(1970, 1, 1)).total_seconds())
@property
def api_version(self):
"""Cached version of :py:func:`~xmpp_backends.base.XmppBackendBase.get_api_version`."""
now = datetime.utcnow()
if self.version_cache_timestamp and self.version_cache_timestamp + self.version_cache_timeout > now:
return self.version_cache_value # we have a cached value
self.version_cache_value = self.get_api_version()
if self.minimum_version and self.version_cache_value < self.minimum_version:
raise NotSupportedError('%s requires ejabberd >= %s' % (self.__class__.__name__,
self.minimum_version))
self.version_cache_timestamp = now
return self.version_cache_value
def get_api_version(self):
"""Get the API version used by this backend.
Note that this function is usually not invoked directly but through
:py:attr:`~xmpp_backends.base.XmppBackendBase.api_version`.
The value returned by this function is used by various backends to determine how to call various API
backends and/or how to parse th data returned by them. Backends generally assume that this function is
always working and return the correct value.
If your backend implementation cannot get this value, it should be passed via the constructor and
statically returned for the livetime of the instance.
"""
raise NotImplementedError
def user_exists(self, username, domain):
"""Verify that the given user exists.
:param username: The username of the user.
:type username: str
:param domain: The domain of the user.
:type domain: str
:return: ``True`` if the user exists, ``False`` if not.
:rtype: bool
"""
raise NotImplementedError
def user_sessions(self, username, domain):
"""Get a list of all current sessions for the given user.
:param username: The username of the user.
:type username: str
:param domain: The domain of the user.
:type domain: str
:return: A list :py:class:`~xmpp_backends.base.UserSession` describing the user sessions.
:rtype: list of :py:class:`~xmpp_backends.base.UserSession`
"""
raise NotImplementedError
def stop_user_session(self, username, domain, resource, reason=''):
"""Stop a specific user session, identified by its resource.
A resource uniquely identifies a connection by a specific client.
:param username: The username of the user.
:type username: str
:param domain: The domain of the user.
:type domain: str
:param resource: The resource of the connection
:type resource: str
"""
raise NotImplementedError
def create_user(self, username, domain, password, email=None):
"""Create a new user.
:param username: The username of the new user.
:type username: str
:param domain: The domain of the new user.
:type domain: str
:param password: The password of the new user.
:param email: The email address provided by the user.
"""
raise NotImplementedError
def create_reservation(self, username, domain, email=None):
"""Reserve a new account.
This method is called when a user account should be reserved, meaning that the account can no longer
be registered by anybody else but the user cannot yet log in either. This is useful if e.g. an email
confirmation is still pending.
The default implementation calls :py:func:`~xmpp_backends.base.XmppBackendBase.create_user` with a
random password.
:param username: The username of the user.
:type username: str
:param domain: The domain of the user.
:type domain: str
:param email: The email address provided by the user. Note that at this point it is not confirmed.
You are free to ignore this parameter.
"""
password = self.get_random_password()
self.create(username=username, domain=domain, password=password, email=email)
def confirm_reservation(self, username, domain, password, email=None):
"""Confirm a reservation for a username.
The default implementation just calls :py:func:`~xmpp_backends.base.XmppBackendBase.set_password` and
optionally :py:func:`~xmpp_backends.base.XmppBackendBase.set_email`.
"""
self.set_password(username=username, domain=domain, password=password)
if email is not None:
self.set_email(username=username, domain=domain, email=email)
def check_password(self, username, domain, password):
"""Check the password of a user.
:param username: The username of the user.
:type username: str
:param domain: The domain of the user.
:type domain: str
:param password: The password to check.
:type password: str
:return: ``True`` if the password is correct, ``False`` if not.
:rtype: bool
"""
raise NotImplementedError
def set_password(self, username, domain, password):
"""Set the password of a user.
:param username: The username of the user.
:type username: str
:param domain: The domain of the user.
:type domain: str
:param password: The password to set.
:type password: str
"""
raise NotImplementedError
def get_last_activity(self, username, domain):
"""Get the last activity of the user.
The datetime object returned should be a naive datetime object representing the time in UTC.
:param username: The username of the user.
:type username: str
:param domain: The domain of the user.
:type domain: str
:return: A naive datetime object in UTC representing the last activity.
:rtype: datetime
"""
raise NotImplementedError
def set_last_activity(self, username, domain, status='', timestamp=None):
"""Set the last activity of the user.
.. NOTE::
If your backend requires a Unix timestamp (seconds since 1970-01-01), you can use the
:py:func:`~xmpp_backends.base.XmppBackendBase.datetime_to_timestamp` convenience function to
convert it to an integer.
:param username: The username of the user.
:type username: str
:param domain: The domain of the user.
:type domain: str
:param status: The status text.
:type status: str
:param timestamp: A datetime object representing the last activity. If the object is not
timezone-aware, assume UTC. If ``timestamp`` is ``None``, assume the current date and time.
:type timestamp: datetime
"""
raise NotImplementedError
def block_user(self, username, domain):
"""Block the specified user.
The default implementation calls :py:func:`~xmpp_backends.base.XmppBackendBase.set_password` with a
random password.
:param username: The username of the user.
:type username: str
:param domain: The domain of the user.
:type domain: str
"""
self.set_password(username, domain, self.get_random_password())
def set_email(self, username, domain, email):
"""Set the email address of a user."""
raise NotImplementedError
def check_email(self, username, domain, email):
"""Check the email address of a user.
**Note:** Most backends don't implement this feature.
:param username: The username of the user.
:type username: str
:param domain: The domain of the user.
:type domain: str
"""
raise NotImplementedError
def expire_reservation(self, username, domain):
"""Expire a username reservation.
This method is called when a reservation expires. The default implementation just calls
:py:func:`~xmpp_backends.base.XmppBackendBase.remove_user`. This is fine if you do not override
:py:func:`~xmpp_backends.base.XmppBackendBase.create_reservation`.
:param username: The username of the user.
:type username: str
:param domain: The domain of the user.
:type domain: str
"""
self.remove_user(username, domain)
def message_user(self, username, domain, subject, message):
"""Send a message to the given user.
:param username: The username of the user.
:type username: str
:param domain: The domain of the user.
:type domain: str
:param subject: The subject of the message.
:param message: The content of the message.
"""
pass
def all_users(self, domain):
"""Get all users for a given domain.
:param domain: The domain of interest.
:type domain: str
:return: A set of all users. The usernames do not include the domain, so ``user@example.com`` will
just be ``"user"``.
:rtype: set of str
"""
raise NotImplementedError
def all_domains(self):
"""List of all domains used by this backend.
:return: List of all domains served by this backend.
:rtype: list of str
"""
raise NotImplementedError
def all_user_sessions(self):
"""List all current user sessions.
:param domain: Optionally only return sessions for the given domain.
:return: A list :py:class:`~xmpp_backends.base.UserSession` for all sessions.
:rtype: list of :py:class:`~xmpp_backends.base.UserSession`
"""
raise NotImplementedError
def remove_user(self, username, domain):
"""Remove a user.
This method is called when the user explicitly wants to remove her/his account.
:param username: The username of the new user.
:type username: str
:param domain: The domain of the user.
:type domain: str
"""
raise NotImplementedError
def stats(self, stat, domain=None):
"""Get statistical value about the XMPP server.
Minimal statistics that should be supported is ``"registered_users"`` and ``"online_users"``. The
specific backend might support additional stats.
:param stat: The value of the statistic.
:type stat: str
:param domain: Limit statistic to the given domain. If not listed, give statistics
about all users.
:type domain: str
:return: The current value of the requested statistic.
:rtype: int
"""
raise NotImplementedError
|
mathiasertl/xmpp-backends
|
xmpp_backends/base.py
|
XmppBackendBase.api_version
|
python
|
def api_version(self):
now = datetime.utcnow()
if self.version_cache_timestamp and self.version_cache_timestamp + self.version_cache_timeout > now:
return self.version_cache_value # we have a cached value
self.version_cache_value = self.get_api_version()
if self.minimum_version and self.version_cache_value < self.minimum_version:
raise NotSupportedError('%s requires ejabberd >= %s' % (self.__class__.__name__,
self.minimum_version))
self.version_cache_timestamp = now
return self.version_cache_value
|
Cached version of :py:func:`~xmpp_backends.base.XmppBackendBase.get_api_version`.
|
train
|
https://github.com/mathiasertl/xmpp-backends/blob/214ef0664dbf90fa300c2483b9b3416559e5d171/xmpp_backends/base.py#L239-L254
|
[
"def get_api_version(self):\n \"\"\"Get the API version used by this backend.\n\n Note that this function is usually not invoked directly but through\n :py:attr:`~xmpp_backends.base.XmppBackendBase.api_version`.\n\n The value returned by this function is used by various backends to determine how to call various API\n backends and/or how to parse th data returned by them. Backends generally assume that this function is\n always working and return the correct value.\n\n If your backend implementation cannot get this value, it should be passed via the constructor and\n statically returned for the livetime of the instance.\n \"\"\"\n\n raise NotImplementedError\n"
] |
class XmppBackendBase(object):
"""Base class for all XMPP backends."""
library = None
"""Import-party of any third-party library you need.
Set this attribute to an import path and you will be able to access the module as ``self.module``. This
way you don't have to do a module-level import, which would mean that everyone has to have that library
installed, even if they're not using your backend.
:param version_cache_timeout: How long the API version for this backend will be cached.
:type version_cache_timeout: int or timedelta
"""
_module = None
minimum_version = None
version_cache_timeout = None
version_cache_timestamp = None
version_cache_value = None
def __init__(self, version_cache_timeout=3600):
if isinstance(version_cache_timeout, int):
version_cache_timeout = timedelta(seconds=version_cache_timeout)
self.version_cache_timeout = version_cache_timeout
super(XmppBackendBase, self).__init__()
@property
def module(self):
"""The module specified by the ``library`` attribute."""
if self._module is None:
if self.library is None:
raise ValueError(
"Backend '%s' doesn't specify a library attribute" % self.__class__)
try:
if '.' in self.library:
mod_path, cls_name = self.library.rsplit('.', 1)
mod = import_module(mod_path)
self._module = getattr(mod, cls_name)
else:
self._module = import_module(self.library)
except (AttributeError, ImportError):
raise ValueError("Couldn't load %s backend library" % cls_name)
return self._module
def datetime_to_timestamp(self, dt):
"""Helper function to convert a datetime object to a timestamp.
If datetime instance ``dt`` is naive, it is assumed that it is in UTC.
In Python 3, this just calls ``datetime.timestamp()``, in Python 2, it substracts any timezone offset
and returns the difference since 1970-01-01 00:00:00.
Note that the function always returns an int, even in Python 3.
>>> XmppBackendBase().datetime_to_timestamp(datetime(2017, 9, 17, 19, 59))
1505678340
>>> XmppBackendBase().datetime_to_timestamp(datetime(1984, 11, 6, 13, 21))
468595260
:param dt: The datetime object to convert. If ``None``, returns the current time.
:type dt: datetime
:return: The seconds in UTC.
:rtype: int
"""
if dt is None:
return int(time.time())
if six.PY3:
if not dt.tzinfo:
dt = pytz.utc.localize(dt)
return int(dt.timestamp())
else:
if dt.tzinfo:
dt = dt.replace(tzinfo=None) - dt.utcoffset()
return int((dt - datetime(1970, 1, 1)).total_seconds())
def get_random_password(self, length=32, chars=None):
"""Helper function that gets a random password.
:param length: The length of the random password.
:type length: int
:param chars: A string with characters to choose from. Defaults to all ASCII letters and digits.
:type chars: str
"""
if chars is None:
chars = string.ascii_letters + string.digits
return ''.join(random.choice(chars) for x in range(length))
@property
def get_api_version(self):
"""Get the API version used by this backend.
Note that this function is usually not invoked directly but through
:py:attr:`~xmpp_backends.base.XmppBackendBase.api_version`.
The value returned by this function is used by various backends to determine how to call various API
backends and/or how to parse th data returned by them. Backends generally assume that this function is
always working and return the correct value.
If your backend implementation cannot get this value, it should be passed via the constructor and
statically returned for the livetime of the instance.
"""
raise NotImplementedError
def user_exists(self, username, domain):
"""Verify that the given user exists.
:param username: The username of the user.
:type username: str
:param domain: The domain of the user.
:type domain: str
:return: ``True`` if the user exists, ``False`` if not.
:rtype: bool
"""
raise NotImplementedError
def user_sessions(self, username, domain):
"""Get a list of all current sessions for the given user.
:param username: The username of the user.
:type username: str
:param domain: The domain of the user.
:type domain: str
:return: A list :py:class:`~xmpp_backends.base.UserSession` describing the user sessions.
:rtype: list of :py:class:`~xmpp_backends.base.UserSession`
"""
raise NotImplementedError
def stop_user_session(self, username, domain, resource, reason=''):
"""Stop a specific user session, identified by its resource.
A resource uniquely identifies a connection by a specific client.
:param username: The username of the user.
:type username: str
:param domain: The domain of the user.
:type domain: str
:param resource: The resource of the connection
:type resource: str
"""
raise NotImplementedError
def create_user(self, username, domain, password, email=None):
"""Create a new user.
:param username: The username of the new user.
:type username: str
:param domain: The domain of the new user.
:type domain: str
:param password: The password of the new user.
:param email: The email address provided by the user.
"""
raise NotImplementedError
def create_reservation(self, username, domain, email=None):
"""Reserve a new account.
This method is called when a user account should be reserved, meaning that the account can no longer
be registered by anybody else but the user cannot yet log in either. This is useful if e.g. an email
confirmation is still pending.
The default implementation calls :py:func:`~xmpp_backends.base.XmppBackendBase.create_user` with a
random password.
:param username: The username of the user.
:type username: str
:param domain: The domain of the user.
:type domain: str
:param email: The email address provided by the user. Note that at this point it is not confirmed.
You are free to ignore this parameter.
"""
password = self.get_random_password()
self.create(username=username, domain=domain, password=password, email=email)
def confirm_reservation(self, username, domain, password, email=None):
"""Confirm a reservation for a username.
The default implementation just calls :py:func:`~xmpp_backends.base.XmppBackendBase.set_password` and
optionally :py:func:`~xmpp_backends.base.XmppBackendBase.set_email`.
"""
self.set_password(username=username, domain=domain, password=password)
if email is not None:
self.set_email(username=username, domain=domain, email=email)
def check_password(self, username, domain, password):
"""Check the password of a user.
:param username: The username of the user.
:type username: str
:param domain: The domain of the user.
:type domain: str
:param password: The password to check.
:type password: str
:return: ``True`` if the password is correct, ``False`` if not.
:rtype: bool
"""
raise NotImplementedError
def set_password(self, username, domain, password):
"""Set the password of a user.
:param username: The username of the user.
:type username: str
:param domain: The domain of the user.
:type domain: str
:param password: The password to set.
:type password: str
"""
raise NotImplementedError
def get_last_activity(self, username, domain):
"""Get the last activity of the user.
The datetime object returned should be a naive datetime object representing the time in UTC.
:param username: The username of the user.
:type username: str
:param domain: The domain of the user.
:type domain: str
:return: A naive datetime object in UTC representing the last activity.
:rtype: datetime
"""
raise NotImplementedError
def set_last_activity(self, username, domain, status='', timestamp=None):
"""Set the last activity of the user.
.. NOTE::
If your backend requires a Unix timestamp (seconds since 1970-01-01), you can use the
:py:func:`~xmpp_backends.base.XmppBackendBase.datetime_to_timestamp` convenience function to
convert it to an integer.
:param username: The username of the user.
:type username: str
:param domain: The domain of the user.
:type domain: str
:param status: The status text.
:type status: str
:param timestamp: A datetime object representing the last activity. If the object is not
timezone-aware, assume UTC. If ``timestamp`` is ``None``, assume the current date and time.
:type timestamp: datetime
"""
raise NotImplementedError
def block_user(self, username, domain):
"""Block the specified user.
The default implementation calls :py:func:`~xmpp_backends.base.XmppBackendBase.set_password` with a
random password.
:param username: The username of the user.
:type username: str
:param domain: The domain of the user.
:type domain: str
"""
self.set_password(username, domain, self.get_random_password())
def set_email(self, username, domain, email):
"""Set the email address of a user."""
raise NotImplementedError
def check_email(self, username, domain, email):
"""Check the email address of a user.
**Note:** Most backends don't implement this feature.
:param username: The username of the user.
:type username: str
:param domain: The domain of the user.
:type domain: str
"""
raise NotImplementedError
def expire_reservation(self, username, domain):
"""Expire a username reservation.
This method is called when a reservation expires. The default implementation just calls
:py:func:`~xmpp_backends.base.XmppBackendBase.remove_user`. This is fine if you do not override
:py:func:`~xmpp_backends.base.XmppBackendBase.create_reservation`.
:param username: The username of the user.
:type username: str
:param domain: The domain of the user.
:type domain: str
"""
self.remove_user(username, domain)
def message_user(self, username, domain, subject, message):
"""Send a message to the given user.
:param username: The username of the user.
:type username: str
:param domain: The domain of the user.
:type domain: str
:param subject: The subject of the message.
:param message: The content of the message.
"""
pass
def all_users(self, domain):
"""Get all users for a given domain.
:param domain: The domain of interest.
:type domain: str
:return: A set of all users. The usernames do not include the domain, so ``user@example.com`` will
just be ``"user"``.
:rtype: set of str
"""
raise NotImplementedError
def all_domains(self):
"""List of all domains used by this backend.
:return: List of all domains served by this backend.
:rtype: list of str
"""
raise NotImplementedError
def all_user_sessions(self):
"""List all current user sessions.
:param domain: Optionally only return sessions for the given domain.
:return: A list :py:class:`~xmpp_backends.base.UserSession` for all sessions.
:rtype: list of :py:class:`~xmpp_backends.base.UserSession`
"""
raise NotImplementedError
def remove_user(self, username, domain):
"""Remove a user.
This method is called when the user explicitly wants to remove her/his account.
:param username: The username of the new user.
:type username: str
:param domain: The domain of the user.
:type domain: str
"""
raise NotImplementedError
def stats(self, stat, domain=None):
"""Get statistical value about the XMPP server.
Minimal statistics that should be supported is ``"registered_users"`` and ``"online_users"``. The
specific backend might support additional stats.
:param stat: The value of the statistic.
:type stat: str
:param domain: Limit statistic to the given domain. If not listed, give statistics
about all users.
:type domain: str
:return: The current value of the requested statistic.
:rtype: int
"""
raise NotImplementedError
|
mathiasertl/xmpp-backends
|
xmpp_backends/base.py
|
XmppBackendBase.create_reservation
|
python
|
def create_reservation(self, username, domain, email=None):
password = self.get_random_password()
self.create(username=username, domain=domain, password=password, email=email)
|
Reserve a new account.
This method is called when a user account should be reserved, meaning that the account can no longer
be registered by anybody else but the user cannot yet log in either. This is useful if e.g. an email
confirmation is still pending.
The default implementation calls :py:func:`~xmpp_backends.base.XmppBackendBase.create_user` with a
random password.
:param username: The username of the user.
:type username: str
:param domain: The domain of the user.
:type domain: str
:param email: The email address provided by the user. Note that at this point it is not confirmed.
You are free to ignore this parameter.
|
train
|
https://github.com/mathiasertl/xmpp-backends/blob/214ef0664dbf90fa300c2483b9b3416559e5d171/xmpp_backends/base.py#L325-L343
|
[
"def get_random_password(self, length=32, chars=None):\n \"\"\"Helper function that gets a random password.\n\n :param length: The length of the random password.\n :type length: int\n :param chars: A string with characters to choose from. Defaults to all ASCII letters and digits.\n :type chars: str\n \"\"\"\n if chars is None:\n chars = string.ascii_letters + string.digits\n return ''.join(random.choice(chars) for x in range(length))\n"
] |
class XmppBackendBase(object):
"""Base class for all XMPP backends."""
library = None
"""Import-party of any third-party library you need.
Set this attribute to an import path and you will be able to access the module as ``self.module``. This
way you don't have to do a module-level import, which would mean that everyone has to have that library
installed, even if they're not using your backend.
:param version_cache_timeout: How long the API version for this backend will be cached.
:type version_cache_timeout: int or timedelta
"""
_module = None
minimum_version = None
version_cache_timeout = None
version_cache_timestamp = None
version_cache_value = None
def __init__(self, version_cache_timeout=3600):
if isinstance(version_cache_timeout, int):
version_cache_timeout = timedelta(seconds=version_cache_timeout)
self.version_cache_timeout = version_cache_timeout
super(XmppBackendBase, self).__init__()
@property
def module(self):
"""The module specified by the ``library`` attribute."""
if self._module is None:
if self.library is None:
raise ValueError(
"Backend '%s' doesn't specify a library attribute" % self.__class__)
try:
if '.' in self.library:
mod_path, cls_name = self.library.rsplit('.', 1)
mod = import_module(mod_path)
self._module = getattr(mod, cls_name)
else:
self._module = import_module(self.library)
except (AttributeError, ImportError):
raise ValueError("Couldn't load %s backend library" % cls_name)
return self._module
def datetime_to_timestamp(self, dt):
"""Helper function to convert a datetime object to a timestamp.
If datetime instance ``dt`` is naive, it is assumed that it is in UTC.
In Python 3, this just calls ``datetime.timestamp()``, in Python 2, it substracts any timezone offset
and returns the difference since 1970-01-01 00:00:00.
Note that the function always returns an int, even in Python 3.
>>> XmppBackendBase().datetime_to_timestamp(datetime(2017, 9, 17, 19, 59))
1505678340
>>> XmppBackendBase().datetime_to_timestamp(datetime(1984, 11, 6, 13, 21))
468595260
:param dt: The datetime object to convert. If ``None``, returns the current time.
:type dt: datetime
:return: The seconds in UTC.
:rtype: int
"""
if dt is None:
return int(time.time())
if six.PY3:
if not dt.tzinfo:
dt = pytz.utc.localize(dt)
return int(dt.timestamp())
else:
if dt.tzinfo:
dt = dt.replace(tzinfo=None) - dt.utcoffset()
return int((dt - datetime(1970, 1, 1)).total_seconds())
def get_random_password(self, length=32, chars=None):
"""Helper function that gets a random password.
:param length: The length of the random password.
:type length: int
:param chars: A string with characters to choose from. Defaults to all ASCII letters and digits.
:type chars: str
"""
if chars is None:
chars = string.ascii_letters + string.digits
return ''.join(random.choice(chars) for x in range(length))
@property
def api_version(self):
"""Cached version of :py:func:`~xmpp_backends.base.XmppBackendBase.get_api_version`."""
now = datetime.utcnow()
if self.version_cache_timestamp and self.version_cache_timestamp + self.version_cache_timeout > now:
return self.version_cache_value # we have a cached value
self.version_cache_value = self.get_api_version()
if self.minimum_version and self.version_cache_value < self.minimum_version:
raise NotSupportedError('%s requires ejabberd >= %s' % (self.__class__.__name__,
self.minimum_version))
self.version_cache_timestamp = now
return self.version_cache_value
def get_api_version(self):
"""Get the API version used by this backend.
Note that this function is usually not invoked directly but through
:py:attr:`~xmpp_backends.base.XmppBackendBase.api_version`.
The value returned by this function is used by various backends to determine how to call various API
backends and/or how to parse th data returned by them. Backends generally assume that this function is
always working and return the correct value.
If your backend implementation cannot get this value, it should be passed via the constructor and
statically returned for the livetime of the instance.
"""
raise NotImplementedError
def user_exists(self, username, domain):
"""Verify that the given user exists.
:param username: The username of the user.
:type username: str
:param domain: The domain of the user.
:type domain: str
:return: ``True`` if the user exists, ``False`` if not.
:rtype: bool
"""
raise NotImplementedError
def user_sessions(self, username, domain):
"""Get a list of all current sessions for the given user.
:param username: The username of the user.
:type username: str
:param domain: The domain of the user.
:type domain: str
:return: A list :py:class:`~xmpp_backends.base.UserSession` describing the user sessions.
:rtype: list of :py:class:`~xmpp_backends.base.UserSession`
"""
raise NotImplementedError
def stop_user_session(self, username, domain, resource, reason=''):
"""Stop a specific user session, identified by its resource.
A resource uniquely identifies a connection by a specific client.
:param username: The username of the user.
:type username: str
:param domain: The domain of the user.
:type domain: str
:param resource: The resource of the connection
:type resource: str
"""
raise NotImplementedError
def create_user(self, username, domain, password, email=None):
"""Create a new user.
:param username: The username of the new user.
:type username: str
:param domain: The domain of the new user.
:type domain: str
:param password: The password of the new user.
:param email: The email address provided by the user.
"""
raise NotImplementedError
def confirm_reservation(self, username, domain, password, email=None):
"""Confirm a reservation for a username.
The default implementation just calls :py:func:`~xmpp_backends.base.XmppBackendBase.set_password` and
optionally :py:func:`~xmpp_backends.base.XmppBackendBase.set_email`.
"""
self.set_password(username=username, domain=domain, password=password)
if email is not None:
self.set_email(username=username, domain=domain, email=email)
def check_password(self, username, domain, password):
"""Check the password of a user.
:param username: The username of the user.
:type username: str
:param domain: The domain of the user.
:type domain: str
:param password: The password to check.
:type password: str
:return: ``True`` if the password is correct, ``False`` if not.
:rtype: bool
"""
raise NotImplementedError
def set_password(self, username, domain, password):
"""Set the password of a user.
:param username: The username of the user.
:type username: str
:param domain: The domain of the user.
:type domain: str
:param password: The password to set.
:type password: str
"""
raise NotImplementedError
def get_last_activity(self, username, domain):
"""Get the last activity of the user.
The datetime object returned should be a naive datetime object representing the time in UTC.
:param username: The username of the user.
:type username: str
:param domain: The domain of the user.
:type domain: str
:return: A naive datetime object in UTC representing the last activity.
:rtype: datetime
"""
raise NotImplementedError
def set_last_activity(self, username, domain, status='', timestamp=None):
"""Set the last activity of the user.
.. NOTE::
If your backend requires a Unix timestamp (seconds since 1970-01-01), you can use the
:py:func:`~xmpp_backends.base.XmppBackendBase.datetime_to_timestamp` convenience function to
convert it to an integer.
:param username: The username of the user.
:type username: str
:param domain: The domain of the user.
:type domain: str
:param status: The status text.
:type status: str
:param timestamp: A datetime object representing the last activity. If the object is not
timezone-aware, assume UTC. If ``timestamp`` is ``None``, assume the current date and time.
:type timestamp: datetime
"""
raise NotImplementedError
def block_user(self, username, domain):
"""Block the specified user.
The default implementation calls :py:func:`~xmpp_backends.base.XmppBackendBase.set_password` with a
random password.
:param username: The username of the user.
:type username: str
:param domain: The domain of the user.
:type domain: str
"""
self.set_password(username, domain, self.get_random_password())
def set_email(self, username, domain, email):
"""Set the email address of a user."""
raise NotImplementedError
def check_email(self, username, domain, email):
"""Check the email address of a user.
**Note:** Most backends don't implement this feature.
:param username: The username of the user.
:type username: str
:param domain: The domain of the user.
:type domain: str
"""
raise NotImplementedError
def expire_reservation(self, username, domain):
"""Expire a username reservation.
This method is called when a reservation expires. The default implementation just calls
:py:func:`~xmpp_backends.base.XmppBackendBase.remove_user`. This is fine if you do not override
:py:func:`~xmpp_backends.base.XmppBackendBase.create_reservation`.
:param username: The username of the user.
:type username: str
:param domain: The domain of the user.
:type domain: str
"""
self.remove_user(username, domain)
def message_user(self, username, domain, subject, message):
"""Send a message to the given user.
:param username: The username of the user.
:type username: str
:param domain: The domain of the user.
:type domain: str
:param subject: The subject of the message.
:param message: The content of the message.
"""
pass
def all_users(self, domain):
"""Get all users for a given domain.
:param domain: The domain of interest.
:type domain: str
:return: A set of all users. The usernames do not include the domain, so ``user@example.com`` will
just be ``"user"``.
:rtype: set of str
"""
raise NotImplementedError
def all_domains(self):
"""List of all domains used by this backend.
:return: List of all domains served by this backend.
:rtype: list of str
"""
raise NotImplementedError
def all_user_sessions(self):
"""List all current user sessions.
:param domain: Optionally only return sessions for the given domain.
:return: A list :py:class:`~xmpp_backends.base.UserSession` for all sessions.
:rtype: list of :py:class:`~xmpp_backends.base.UserSession`
"""
raise NotImplementedError
def remove_user(self, username, domain):
"""Remove a user.
This method is called when the user explicitly wants to remove her/his account.
:param username: The username of the new user.
:type username: str
:param domain: The domain of the user.
:type domain: str
"""
raise NotImplementedError
def stats(self, stat, domain=None):
"""Get statistical value about the XMPP server.
Minimal statistics that should be supported is ``"registered_users"`` and ``"online_users"``. The
specific backend might support additional stats.
:param stat: The value of the statistic.
:type stat: str
:param domain: Limit statistic to the given domain. If not listed, give statistics
about all users.
:type domain: str
:return: The current value of the requested statistic.
:rtype: int
"""
raise NotImplementedError
|
mathiasertl/xmpp-backends
|
xmpp_backends/base.py
|
XmppBackendBase.confirm_reservation
|
python
|
def confirm_reservation(self, username, domain, password, email=None):
self.set_password(username=username, domain=domain, password=password)
if email is not None:
self.set_email(username=username, domain=domain, email=email)
|
Confirm a reservation for a username.
The default implementation just calls :py:func:`~xmpp_backends.base.XmppBackendBase.set_password` and
optionally :py:func:`~xmpp_backends.base.XmppBackendBase.set_email`.
|
train
|
https://github.com/mathiasertl/xmpp-backends/blob/214ef0664dbf90fa300c2483b9b3416559e5d171/xmpp_backends/base.py#L345-L353
|
[
"def set_password(self, username, domain, password):\n \"\"\"Set the password of a user.\n\n :param username: The username of the user.\n :type username: str\n :param domain: The domain of the user.\n :type domain: str\n :param password: The password to set.\n :type password: str\n \"\"\"\n raise NotImplementedError\n",
"def set_email(self, username, domain, email):\n \"\"\"Set the email address of a user.\"\"\"\n raise NotImplementedError\n"
] |
class XmppBackendBase(object):
"""Base class for all XMPP backends."""
library = None
"""Import-party of any third-party library you need.
Set this attribute to an import path and you will be able to access the module as ``self.module``. This
way you don't have to do a module-level import, which would mean that everyone has to have that library
installed, even if they're not using your backend.
:param version_cache_timeout: How long the API version for this backend will be cached.
:type version_cache_timeout: int or timedelta
"""
_module = None
minimum_version = None
version_cache_timeout = None
version_cache_timestamp = None
version_cache_value = None
def __init__(self, version_cache_timeout=3600):
if isinstance(version_cache_timeout, int):
version_cache_timeout = timedelta(seconds=version_cache_timeout)
self.version_cache_timeout = version_cache_timeout
super(XmppBackendBase, self).__init__()
@property
def module(self):
"""The module specified by the ``library`` attribute."""
if self._module is None:
if self.library is None:
raise ValueError(
"Backend '%s' doesn't specify a library attribute" % self.__class__)
try:
if '.' in self.library:
mod_path, cls_name = self.library.rsplit('.', 1)
mod = import_module(mod_path)
self._module = getattr(mod, cls_name)
else:
self._module = import_module(self.library)
except (AttributeError, ImportError):
raise ValueError("Couldn't load %s backend library" % cls_name)
return self._module
def datetime_to_timestamp(self, dt):
"""Helper function to convert a datetime object to a timestamp.
If datetime instance ``dt`` is naive, it is assumed that it is in UTC.
In Python 3, this just calls ``datetime.timestamp()``, in Python 2, it substracts any timezone offset
and returns the difference since 1970-01-01 00:00:00.
Note that the function always returns an int, even in Python 3.
>>> XmppBackendBase().datetime_to_timestamp(datetime(2017, 9, 17, 19, 59))
1505678340
>>> XmppBackendBase().datetime_to_timestamp(datetime(1984, 11, 6, 13, 21))
468595260
:param dt: The datetime object to convert. If ``None``, returns the current time.
:type dt: datetime
:return: The seconds in UTC.
:rtype: int
"""
if dt is None:
return int(time.time())
if six.PY3:
if not dt.tzinfo:
dt = pytz.utc.localize(dt)
return int(dt.timestamp())
else:
if dt.tzinfo:
dt = dt.replace(tzinfo=None) - dt.utcoffset()
return int((dt - datetime(1970, 1, 1)).total_seconds())
def get_random_password(self, length=32, chars=None):
"""Helper function that gets a random password.
:param length: The length of the random password.
:type length: int
:param chars: A string with characters to choose from. Defaults to all ASCII letters and digits.
:type chars: str
"""
if chars is None:
chars = string.ascii_letters + string.digits
return ''.join(random.choice(chars) for x in range(length))
@property
def api_version(self):
"""Cached version of :py:func:`~xmpp_backends.base.XmppBackendBase.get_api_version`."""
now = datetime.utcnow()
if self.version_cache_timestamp and self.version_cache_timestamp + self.version_cache_timeout > now:
return self.version_cache_value # we have a cached value
self.version_cache_value = self.get_api_version()
if self.minimum_version and self.version_cache_value < self.minimum_version:
raise NotSupportedError('%s requires ejabberd >= %s' % (self.__class__.__name__,
self.minimum_version))
self.version_cache_timestamp = now
return self.version_cache_value
def get_api_version(self):
"""Get the API version used by this backend.
Note that this function is usually not invoked directly but through
:py:attr:`~xmpp_backends.base.XmppBackendBase.api_version`.
The value returned by this function is used by various backends to determine how to call various API
backends and/or how to parse th data returned by them. Backends generally assume that this function is
always working and return the correct value.
If your backend implementation cannot get this value, it should be passed via the constructor and
statically returned for the livetime of the instance.
"""
raise NotImplementedError
def user_exists(self, username, domain):
"""Verify that the given user exists.
:param username: The username of the user.
:type username: str
:param domain: The domain of the user.
:type domain: str
:return: ``True`` if the user exists, ``False`` if not.
:rtype: bool
"""
raise NotImplementedError
def user_sessions(self, username, domain):
"""Get a list of all current sessions for the given user.
:param username: The username of the user.
:type username: str
:param domain: The domain of the user.
:type domain: str
:return: A list :py:class:`~xmpp_backends.base.UserSession` describing the user sessions.
:rtype: list of :py:class:`~xmpp_backends.base.UserSession`
"""
raise NotImplementedError
def stop_user_session(self, username, domain, resource, reason=''):
"""Stop a specific user session, identified by its resource.
A resource uniquely identifies a connection by a specific client.
:param username: The username of the user.
:type username: str
:param domain: The domain of the user.
:type domain: str
:param resource: The resource of the connection
:type resource: str
"""
raise NotImplementedError
def create_user(self, username, domain, password, email=None):
"""Create a new user.
:param username: The username of the new user.
:type username: str
:param domain: The domain of the new user.
:type domain: str
:param password: The password of the new user.
:param email: The email address provided by the user.
"""
raise NotImplementedError
def create_reservation(self, username, domain, email=None):
"""Reserve a new account.
This method is called when a user account should be reserved, meaning that the account can no longer
be registered by anybody else but the user cannot yet log in either. This is useful if e.g. an email
confirmation is still pending.
The default implementation calls :py:func:`~xmpp_backends.base.XmppBackendBase.create_user` with a
random password.
:param username: The username of the user.
:type username: str
:param domain: The domain of the user.
:type domain: str
:param email: The email address provided by the user. Note that at this point it is not confirmed.
You are free to ignore this parameter.
"""
password = self.get_random_password()
self.create(username=username, domain=domain, password=password, email=email)
def check_password(self, username, domain, password):
"""Check the password of a user.
:param username: The username of the user.
:type username: str
:param domain: The domain of the user.
:type domain: str
:param password: The password to check.
:type password: str
:return: ``True`` if the password is correct, ``False`` if not.
:rtype: bool
"""
raise NotImplementedError
def set_password(self, username, domain, password):
"""Set the password of a user.
:param username: The username of the user.
:type username: str
:param domain: The domain of the user.
:type domain: str
:param password: The password to set.
:type password: str
"""
raise NotImplementedError
def get_last_activity(self, username, domain):
"""Get the last activity of the user.
The datetime object returned should be a naive datetime object representing the time in UTC.
:param username: The username of the user.
:type username: str
:param domain: The domain of the user.
:type domain: str
:return: A naive datetime object in UTC representing the last activity.
:rtype: datetime
"""
raise NotImplementedError
def set_last_activity(self, username, domain, status='', timestamp=None):
"""Set the last activity of the user.
.. NOTE::
If your backend requires a Unix timestamp (seconds since 1970-01-01), you can use the
:py:func:`~xmpp_backends.base.XmppBackendBase.datetime_to_timestamp` convenience function to
convert it to an integer.
:param username: The username of the user.
:type username: str
:param domain: The domain of the user.
:type domain: str
:param status: The status text.
:type status: str
:param timestamp: A datetime object representing the last activity. If the object is not
timezone-aware, assume UTC. If ``timestamp`` is ``None``, assume the current date and time.
:type timestamp: datetime
"""
raise NotImplementedError
def block_user(self, username, domain):
"""Block the specified user.
The default implementation calls :py:func:`~xmpp_backends.base.XmppBackendBase.set_password` with a
random password.
:param username: The username of the user.
:type username: str
:param domain: The domain of the user.
:type domain: str
"""
self.set_password(username, domain, self.get_random_password())
def set_email(self, username, domain, email):
"""Set the email address of a user."""
raise NotImplementedError
def check_email(self, username, domain, email):
"""Check the email address of a user.
**Note:** Most backends don't implement this feature.
:param username: The username of the user.
:type username: str
:param domain: The domain of the user.
:type domain: str
"""
raise NotImplementedError
def expire_reservation(self, username, domain):
"""Expire a username reservation.
This method is called when a reservation expires. The default implementation just calls
:py:func:`~xmpp_backends.base.XmppBackendBase.remove_user`. This is fine if you do not override
:py:func:`~xmpp_backends.base.XmppBackendBase.create_reservation`.
:param username: The username of the user.
:type username: str
:param domain: The domain of the user.
:type domain: str
"""
self.remove_user(username, domain)
def message_user(self, username, domain, subject, message):
"""Send a message to the given user.
:param username: The username of the user.
:type username: str
:param domain: The domain of the user.
:type domain: str
:param subject: The subject of the message.
:param message: The content of the message.
"""
pass
def all_users(self, domain):
"""Get all users for a given domain.
:param domain: The domain of interest.
:type domain: str
:return: A set of all users. The usernames do not include the domain, so ``user@example.com`` will
just be ``"user"``.
:rtype: set of str
"""
raise NotImplementedError
def all_domains(self):
"""List of all domains used by this backend.
:return: List of all domains served by this backend.
:rtype: list of str
"""
raise NotImplementedError
def all_user_sessions(self):
"""List all current user sessions.
:param domain: Optionally only return sessions for the given domain.
:return: A list :py:class:`~xmpp_backends.base.UserSession` for all sessions.
:rtype: list of :py:class:`~xmpp_backends.base.UserSession`
"""
raise NotImplementedError
def remove_user(self, username, domain):
"""Remove a user.
This method is called when the user explicitly wants to remove her/his account.
:param username: The username of the new user.
:type username: str
:param domain: The domain of the user.
:type domain: str
"""
raise NotImplementedError
def stats(self, stat, domain=None):
"""Get statistical value about the XMPP server.
Minimal statistics that should be supported is ``"registered_users"`` and ``"online_users"``. The
specific backend might support additional stats.
:param stat: The value of the statistic.
:type stat: str
:param domain: Limit statistic to the given domain. If not listed, give statistics
about all users.
:type domain: str
:return: The current value of the requested statistic.
:rtype: int
"""
raise NotImplementedError
|
mathiasertl/xmpp-backends
|
xmpp_backends/base.py
|
XmppBackendBase.block_user
|
python
|
def block_user(self, username, domain):
self.set_password(username, domain, self.get_random_password())
|
Block the specified user.
The default implementation calls :py:func:`~xmpp_backends.base.XmppBackendBase.set_password` with a
random password.
:param username: The username of the user.
:type username: str
:param domain: The domain of the user.
:type domain: str
|
train
|
https://github.com/mathiasertl/xmpp-backends/blob/214ef0664dbf90fa300c2483b9b3416559e5d171/xmpp_backends/base.py#L416-L427
|
[
"def get_random_password(self, length=32, chars=None):\n \"\"\"Helper function that gets a random password.\n\n :param length: The length of the random password.\n :type length: int\n :param chars: A string with characters to choose from. Defaults to all ASCII letters and digits.\n :type chars: str\n \"\"\"\n if chars is None:\n chars = string.ascii_letters + string.digits\n return ''.join(random.choice(chars) for x in range(length))\n",
"def set_password(self, username, domain, password):\n \"\"\"Set the password of a user.\n\n :param username: The username of the user.\n :type username: str\n :param domain: The domain of the user.\n :type domain: str\n :param password: The password to set.\n :type password: str\n \"\"\"\n raise NotImplementedError\n"
] |
class XmppBackendBase(object):
"""Base class for all XMPP backends."""
library = None
"""Import-party of any third-party library you need.
Set this attribute to an import path and you will be able to access the module as ``self.module``. This
way you don't have to do a module-level import, which would mean that everyone has to have that library
installed, even if they're not using your backend.
:param version_cache_timeout: How long the API version for this backend will be cached.
:type version_cache_timeout: int or timedelta
"""
_module = None
minimum_version = None
version_cache_timeout = None
version_cache_timestamp = None
version_cache_value = None
def __init__(self, version_cache_timeout=3600):
if isinstance(version_cache_timeout, int):
version_cache_timeout = timedelta(seconds=version_cache_timeout)
self.version_cache_timeout = version_cache_timeout
super(XmppBackendBase, self).__init__()
@property
def module(self):
"""The module specified by the ``library`` attribute."""
if self._module is None:
if self.library is None:
raise ValueError(
"Backend '%s' doesn't specify a library attribute" % self.__class__)
try:
if '.' in self.library:
mod_path, cls_name = self.library.rsplit('.', 1)
mod = import_module(mod_path)
self._module = getattr(mod, cls_name)
else:
self._module = import_module(self.library)
except (AttributeError, ImportError):
raise ValueError("Couldn't load %s backend library" % cls_name)
return self._module
def datetime_to_timestamp(self, dt):
"""Helper function to convert a datetime object to a timestamp.
If datetime instance ``dt`` is naive, it is assumed that it is in UTC.
In Python 3, this just calls ``datetime.timestamp()``, in Python 2, it substracts any timezone offset
and returns the difference since 1970-01-01 00:00:00.
Note that the function always returns an int, even in Python 3.
>>> XmppBackendBase().datetime_to_timestamp(datetime(2017, 9, 17, 19, 59))
1505678340
>>> XmppBackendBase().datetime_to_timestamp(datetime(1984, 11, 6, 13, 21))
468595260
:param dt: The datetime object to convert. If ``None``, returns the current time.
:type dt: datetime
:return: The seconds in UTC.
:rtype: int
"""
if dt is None:
return int(time.time())
if six.PY3:
if not dt.tzinfo:
dt = pytz.utc.localize(dt)
return int(dt.timestamp())
else:
if dt.tzinfo:
dt = dt.replace(tzinfo=None) - dt.utcoffset()
return int((dt - datetime(1970, 1, 1)).total_seconds())
def get_random_password(self, length=32, chars=None):
"""Helper function that gets a random password.
:param length: The length of the random password.
:type length: int
:param chars: A string with characters to choose from. Defaults to all ASCII letters and digits.
:type chars: str
"""
if chars is None:
chars = string.ascii_letters + string.digits
return ''.join(random.choice(chars) for x in range(length))
@property
def api_version(self):
"""Cached version of :py:func:`~xmpp_backends.base.XmppBackendBase.get_api_version`."""
now = datetime.utcnow()
if self.version_cache_timestamp and self.version_cache_timestamp + self.version_cache_timeout > now:
return self.version_cache_value # we have a cached value
self.version_cache_value = self.get_api_version()
if self.minimum_version and self.version_cache_value < self.minimum_version:
raise NotSupportedError('%s requires ejabberd >= %s' % (self.__class__.__name__,
self.minimum_version))
self.version_cache_timestamp = now
return self.version_cache_value
def get_api_version(self):
"""Get the API version used by this backend.
Note that this function is usually not invoked directly but through
:py:attr:`~xmpp_backends.base.XmppBackendBase.api_version`.
The value returned by this function is used by various backends to determine how to call various API
backends and/or how to parse th data returned by them. Backends generally assume that this function is
always working and return the correct value.
If your backend implementation cannot get this value, it should be passed via the constructor and
statically returned for the livetime of the instance.
"""
raise NotImplementedError
def user_exists(self, username, domain):
"""Verify that the given user exists.
:param username: The username of the user.
:type username: str
:param domain: The domain of the user.
:type domain: str
:return: ``True`` if the user exists, ``False`` if not.
:rtype: bool
"""
raise NotImplementedError
def user_sessions(self, username, domain):
"""Get a list of all current sessions for the given user.
:param username: The username of the user.
:type username: str
:param domain: The domain of the user.
:type domain: str
:return: A list :py:class:`~xmpp_backends.base.UserSession` describing the user sessions.
:rtype: list of :py:class:`~xmpp_backends.base.UserSession`
"""
raise NotImplementedError
def stop_user_session(self, username, domain, resource, reason=''):
"""Stop a specific user session, identified by its resource.
A resource uniquely identifies a connection by a specific client.
:param username: The username of the user.
:type username: str
:param domain: The domain of the user.
:type domain: str
:param resource: The resource of the connection
:type resource: str
"""
raise NotImplementedError
def create_user(self, username, domain, password, email=None):
"""Create a new user.
:param username: The username of the new user.
:type username: str
:param domain: The domain of the new user.
:type domain: str
:param password: The password of the new user.
:param email: The email address provided by the user.
"""
raise NotImplementedError
def create_reservation(self, username, domain, email=None):
"""Reserve a new account.
This method is called when a user account should be reserved, meaning that the account can no longer
be registered by anybody else but the user cannot yet log in either. This is useful if e.g. an email
confirmation is still pending.
The default implementation calls :py:func:`~xmpp_backends.base.XmppBackendBase.create_user` with a
random password.
:param username: The username of the user.
:type username: str
:param domain: The domain of the user.
:type domain: str
:param email: The email address provided by the user. Note that at this point it is not confirmed.
You are free to ignore this parameter.
"""
password = self.get_random_password()
self.create(username=username, domain=domain, password=password, email=email)
def confirm_reservation(self, username, domain, password, email=None):
"""Confirm a reservation for a username.
The default implementation just calls :py:func:`~xmpp_backends.base.XmppBackendBase.set_password` and
optionally :py:func:`~xmpp_backends.base.XmppBackendBase.set_email`.
"""
self.set_password(username=username, domain=domain, password=password)
if email is not None:
self.set_email(username=username, domain=domain, email=email)
def check_password(self, username, domain, password):
"""Check the password of a user.
:param username: The username of the user.
:type username: str
:param domain: The domain of the user.
:type domain: str
:param password: The password to check.
:type password: str
:return: ``True`` if the password is correct, ``False`` if not.
:rtype: bool
"""
raise NotImplementedError
def set_password(self, username, domain, password):
"""Set the password of a user.
:param username: The username of the user.
:type username: str
:param domain: The domain of the user.
:type domain: str
:param password: The password to set.
:type password: str
"""
raise NotImplementedError
def get_last_activity(self, username, domain):
"""Get the last activity of the user.
The datetime object returned should be a naive datetime object representing the time in UTC.
:param username: The username of the user.
:type username: str
:param domain: The domain of the user.
:type domain: str
:return: A naive datetime object in UTC representing the last activity.
:rtype: datetime
"""
raise NotImplementedError
def set_last_activity(self, username, domain, status='', timestamp=None):
"""Set the last activity of the user.
.. NOTE::
If your backend requires a Unix timestamp (seconds since 1970-01-01), you can use the
:py:func:`~xmpp_backends.base.XmppBackendBase.datetime_to_timestamp` convenience function to
convert it to an integer.
:param username: The username of the user.
:type username: str
:param domain: The domain of the user.
:type domain: str
:param status: The status text.
:type status: str
:param timestamp: A datetime object representing the last activity. If the object is not
timezone-aware, assume UTC. If ``timestamp`` is ``None``, assume the current date and time.
:type timestamp: datetime
"""
raise NotImplementedError
def set_email(self, username, domain, email):
"""Set the email address of a user."""
raise NotImplementedError
def check_email(self, username, domain, email):
"""Check the email address of a user.
**Note:** Most backends don't implement this feature.
:param username: The username of the user.
:type username: str
:param domain: The domain of the user.
:type domain: str
"""
raise NotImplementedError
def expire_reservation(self, username, domain):
"""Expire a username reservation.
This method is called when a reservation expires. The default implementation just calls
:py:func:`~xmpp_backends.base.XmppBackendBase.remove_user`. This is fine if you do not override
:py:func:`~xmpp_backends.base.XmppBackendBase.create_reservation`.
:param username: The username of the user.
:type username: str
:param domain: The domain of the user.
:type domain: str
"""
self.remove_user(username, domain)
def message_user(self, username, domain, subject, message):
"""Send a message to the given user.
:param username: The username of the user.
:type username: str
:param domain: The domain of the user.
:type domain: str
:param subject: The subject of the message.
:param message: The content of the message.
"""
pass
def all_users(self, domain):
"""Get all users for a given domain.
:param domain: The domain of interest.
:type domain: str
:return: A set of all users. The usernames do not include the domain, so ``user@example.com`` will
just be ``"user"``.
:rtype: set of str
"""
raise NotImplementedError
def all_domains(self):
"""List of all domains used by this backend.
:return: List of all domains served by this backend.
:rtype: list of str
"""
raise NotImplementedError
def all_user_sessions(self):
"""List all current user sessions.
:param domain: Optionally only return sessions for the given domain.
:return: A list :py:class:`~xmpp_backends.base.UserSession` for all sessions.
:rtype: list of :py:class:`~xmpp_backends.base.UserSession`
"""
raise NotImplementedError
def remove_user(self, username, domain):
"""Remove a user.
This method is called when the user explicitly wants to remove her/his account.
:param username: The username of the new user.
:type username: str
:param domain: The domain of the user.
:type domain: str
"""
raise NotImplementedError
def stats(self, stat, domain=None):
"""Get statistical value about the XMPP server.
Minimal statistics that should be supported is ``"registered_users"`` and ``"online_users"``. The
specific backend might support additional stats.
:param stat: The value of the statistic.
:type stat: str
:param domain: Limit statistic to the given domain. If not listed, give statistics
about all users.
:type domain: str
:return: The current value of the requested statistic.
:rtype: int
"""
raise NotImplementedError
|
mathiasertl/xmpp-backends
|
xmpp_backends/base.py
|
EjabberdBackendBase.parse_connection_string
|
python
|
def parse_connection_string(self, connection):
# TODO: Websockets, HTTP Polling
if connection == 'c2s_tls':
return CONNECTION_XMPP, True, False
elif connection == 'c2s_compressed_tls':
return CONNECTION_XMPP, True, True
elif connection == 'http_bind':
return CONNECTION_HTTP_BINDING, None, None
elif connection == 'c2s':
return CONNECTION_XMPP, False, False
log.warn('Could not parse connection string "%s"', connection)
return CONNECTION_UNKNOWN, True, True
|
Parse string as returned by the ``connected_users_info`` or ``user_sessions_info`` API calls.
>>> EjabberdBackendBase().parse_connection_string('c2s_tls')
(0, True, False)
>>> EjabberdBackendBase().parse_connection_string('c2s_compressed_tls')
(0, True, True)
>>> EjabberdBackendBase().parse_connection_string('http_bind')
(2, None, None)
:param connection: The connection string as returned by the ejabberd APIs.
:type connection: str
:return: A tuple representing the conntion type, if it is encrypted and if it uses XMPP stream
compression.
:rtype: tuple
|
train
|
https://github.com/mathiasertl/xmpp-backends/blob/214ef0664dbf90fa300c2483b9b3416559e5d171/xmpp_backends/base.py#L564-L590
| null |
class EjabberdBackendBase(XmppBackendBase):
"""Base class for ejabberd related backends.
This class overwrites a few methods common to all ejabberd backends.
"""
minimum_version = (14, 7)
def parse_version_string(self, version):
return tuple(int(t) for t in version.split('.'))
def parse_status_string(self, data):
match = re.search(r'([^ ]*) is running in that node', data)
if not match:
raise BackendError('Could not determine API version.')
return self.parse_version_string(match.groups()[0].split('-', 1)[0])
def has_usable_password(self, username, domain):
"""Always return ``True``.
In ejabberd there is no such thing as a "banned" account or an unusable password. Even ejabberd's
``ban_account`` command only sets a random password that the user could theoretically guess.
"""
return True
def set_email(self, username, domain, email):
"""Not yet implemented."""
pass
def check_email(self, username, domain, email):
"""Not yet implemented."""
pass
def parse_ip_address(self, ip_address):
"""Parse an address as returned by the ``connected_users_info`` or ``user_sessions_info`` API calls.
Example::
>>> EjabberdBackendBase().parse_ip_address('192.168.0.1') # doctest: +FORCE_TEXT
IPv4Address('192.168.0.1')
>>> EjabberdBackendBase().parse_ip_address('::FFFF:192.168.0.1') # doctest: +FORCE_TEXT
IPv4Address('192.168.0.1')
>>> EjabberdBackendBase().parse_ip_address('::1') # doctest: +FORCE_TEXT
IPv6Address('::1')
:param ip_address: An IP address.
:type ip_address: str
:return: The parsed IP address.
:rtype: `ipaddress.IPv6Address` or `ipaddress.IPv4Address`.
"""
if ip_address.startswith('::FFFF:'):
ip_address = ip_address[7:]
if six.PY2 and isinstance(ip_address, str):
# ipaddress constructor does not eat str in py2 :-/
ip_address = ip_address.decode('utf-8')
return ipaddress.ip_address(ip_address)
|
mathiasertl/xmpp-backends
|
xmpp_backends/base.py
|
EjabberdBackendBase.parse_ip_address
|
python
|
def parse_ip_address(self, ip_address):
if ip_address.startswith('::FFFF:'):
ip_address = ip_address[7:]
if six.PY2 and isinstance(ip_address, str):
# ipaddress constructor does not eat str in py2 :-/
ip_address = ip_address.decode('utf-8')
return ipaddress.ip_address(ip_address)
|
Parse an address as returned by the ``connected_users_info`` or ``user_sessions_info`` API calls.
Example::
>>> EjabberdBackendBase().parse_ip_address('192.168.0.1') # doctest: +FORCE_TEXT
IPv4Address('192.168.0.1')
>>> EjabberdBackendBase().parse_ip_address('::FFFF:192.168.0.1') # doctest: +FORCE_TEXT
IPv4Address('192.168.0.1')
>>> EjabberdBackendBase().parse_ip_address('::1') # doctest: +FORCE_TEXT
IPv6Address('::1')
:param ip_address: An IP address.
:type ip_address: str
:return: The parsed IP address.
:rtype: `ipaddress.IPv6Address` or `ipaddress.IPv4Address`.
|
train
|
https://github.com/mathiasertl/xmpp-backends/blob/214ef0664dbf90fa300c2483b9b3416559e5d171/xmpp_backends/base.py#L592-L615
| null |
class EjabberdBackendBase(XmppBackendBase):
"""Base class for ejabberd related backends.
This class overwrites a few methods common to all ejabberd backends.
"""
minimum_version = (14, 7)
def parse_version_string(self, version):
return tuple(int(t) for t in version.split('.'))
def parse_status_string(self, data):
match = re.search(r'([^ ]*) is running in that node', data)
if not match:
raise BackendError('Could not determine API version.')
return self.parse_version_string(match.groups()[0].split('-', 1)[0])
def has_usable_password(self, username, domain):
"""Always return ``True``.
In ejabberd there is no such thing as a "banned" account or an unusable password. Even ejabberd's
``ban_account`` command only sets a random password that the user could theoretically guess.
"""
return True
def set_email(self, username, domain, email):
"""Not yet implemented."""
pass
def check_email(self, username, domain, email):
"""Not yet implemented."""
pass
def parse_connection_string(self, connection):
"""Parse string as returned by the ``connected_users_info`` or ``user_sessions_info`` API calls.
>>> EjabberdBackendBase().parse_connection_string('c2s_tls')
(0, True, False)
>>> EjabberdBackendBase().parse_connection_string('c2s_compressed_tls')
(0, True, True)
>>> EjabberdBackendBase().parse_connection_string('http_bind')
(2, None, None)
:param connection: The connection string as returned by the ejabberd APIs.
:type connection: str
:return: A tuple representing the conntion type, if it is encrypted and if it uses XMPP stream
compression.
:rtype: tuple
"""
# TODO: Websockets, HTTP Polling
if connection == 'c2s_tls':
return CONNECTION_XMPP, True, False
elif connection == 'c2s_compressed_tls':
return CONNECTION_XMPP, True, True
elif connection == 'http_bind':
return CONNECTION_HTTP_BINDING, None, None
elif connection == 'c2s':
return CONNECTION_XMPP, False, False
log.warn('Could not parse connection string "%s"', connection)
return CONNECTION_UNKNOWN, True, True
|
mathiasertl/xmpp-backends
|
xmpp_backends/ejabberdctl.py
|
EjabberdctlBackend.message_user
|
python
|
def message_user(self, username, domain, subject, message):
jid = '%s@%s' % (username, domain)
if self.api_version <= (14, 7):
# TODO: it's unclear when send_message was introduced
command = 'send_message_chat'
args = domain, '%s@%s' % (username, domain), message
else:
command = 'send_message'
args = 'chat', domain, jid, subject, message
code, out, err = self.ctl(command, *args)
if code != 0:
raise BackendError(code)
|
Currently use send_message_chat and discard subject, because headline messages are not stored by
mod_offline.
|
train
|
https://github.com/mathiasertl/xmpp-backends/blob/214ef0664dbf90fa300c2483b9b3416559e5d171/xmpp_backends/ejabberdctl.py#L236-L250
|
[
"def ctl(self, *args):\n cmd = self.ejabberdctl + list(args)\n\n p = Popen(cmd, stdout=PIPE, stderr=PIPE)\n stdout, stderr = p.communicate()\n return p.returncode, stdout, stderr\n"
] |
class EjabberdctlBackend(EjabberdBackendBase):
"""This backend uses the ejabberdctl command line utility.
This backend requires ejabberds ``mod_admin_extra`` to be installed.
.. WARNING::
This backend is not very secure because ejabberdctl gets any passwords in clear text via the
commandline. The process list (and thus the passwords) can usually be viewed by anyone that has
shell-access to your machine!
:param path: Optional path to the ``ejabberdctl`` script. The default is ``"/usr/sbin/ejabberdctl"``.
The path can also be a list, e.g. if ejabberd is run inside a Docker image, you could set
``['docker', 'exec', 'ejabberd-container', '/usr/sbin/ejabberdctl']``.
:param version: Deprecated, no longer use this parameter.
"""
def __init__(self, path='/usr/sbin/ejabberdctl', version=None, **kwargs):
super(EjabberdctlBackend, self).__init__(**kwargs)
if version is not None:
warnings.warn("The version parameter is deprecated.", DeprecationWarning)
self.ejabberdctl = path
if isinstance(path, six.string_types):
self.ejabberdctl = [path]
if self.api_version <= (14, 7):
log.warn('ejabberd <= 14.07 is really broken and many calls will not work!')
def ctl(self, *args):
cmd = self.ejabberdctl + list(args)
p = Popen(cmd, stdout=PIPE, stderr=PIPE)
stdout, stderr = p.communicate()
return p.returncode, stdout, stderr
def get_api_version(self):
code, out, err = self.ctl('status')
if code == 0:
return self.parse_status_string(out.decode('utf-8'))
else:
raise BackendError(code)
def user_exists(self, username, domain):
code, out, err = self.ctl('check_account', username, domain)
if code == 0:
return True
elif code == 1:
return False
else:
raise BackendError(code) # TODO: 3 means nodedown.
def user_sessions(self, username, domain):
code, out, err = self.ctl('user_sessions_info', username, domain)
sessions = set()
out = out.decode('utf-8') # bytes -> str in py3, str -> unicode in py2
for line in out.splitlines():
conn, ip, _p, prio, _n, uptime, status, resource, status_text = line.split('\t', 8)
started = pytz.utc.localize(datetime.utcnow() - timedelta(int(uptime)))
if prio == 'undefined':
prio = None
else:
prio = int(prio)
typ, encrypted, compressed = self.parse_connection_string(conn)
sessions.add(UserSession(
backend=self,
username=username,
domain=domain,
resource=resource,
priority=prio,
ip_address=self.parse_ip_address(ip),
uptime=started,
status=status, status_text=status_text,
connection_type=typ, encrypted=encrypted, compressed=compressed
))
if len(sessions) == 0 and self.api_version <= (15, 7):
raise NotSupportedError("ejabberd <= 15.07 always returns an empty list.")
return sessions
def stop_user_session(self, username, domain, resource, reason=''):
self.ctl('kick_session', username, domain, resource, reason)
def create_user(self, username, domain, password, email=None):
code, out, err = self.ctl('register', username, domain, password)
if code == 0:
try:
self.set_last_activity(username, domain, status='Registered')
except BackendError as e:
log.error('Error setting last activity: %s', e)
if email is not None:
self.set_email(username, domain, email)
elif code == 1:
raise UserExists()
else:
raise BackendError(code) # TODO: 3 means nodedown.
def get_last_activity(self, username, domain):
code, out, err = self.ctl('get_last', username, domain)
if code != 0:
raise BackendError(code)
if six.PY3:
out = out.decode('utf-8')
if self.api_version < (17, 4):
out = out.strip()
if out == 'Online':
return datetime.utcnow()
elif out == 'Never':
if self.user_exists(username, domain):
return None
raise UserNotFound(username, domain)
else:
return datetime.strptime(out[:19], '%Y-%m-%d %H:%M:%S')
else:
timestamp, reason = out.strip().split('\t', 1)
if reason == 'NOT FOUND':
raise UserNotFound(username, domain)
if len(timestamp) == 27:
# NOTE: This format is encountered when the user is not found.
fmt = '%Y-%m-%dT%H:%M:%S.%fZ'
else:
fmt = '%Y-%m-%dT%H:%M:%SZ'
return datetime.strptime(timestamp, fmt)
def set_last_activity(self, username, domain, status='', timestamp=None):
timestamp = str(self.datetime_to_timestamp(timestamp))
version = self.api_version
if status == '' and version >= (15, 7) and version < (16, 1):
# ejabberd 15.07 does not allow an empty string as status
# ejabberd 16.01 accepts an empty string as parameter
# NOTE: unclear if 15.09, 15.10, 15.11 require this.
status = 'set by xmpp-backend'
code, out, err = self.ctl('set_last', username, domain, timestamp, status)
if code == 1 and version >= (15, 7):
# ejabberd returns status code 1 at least since 15.07
return
elif code != 0:
if code == 1 and version == (14, 7):
raise NotSupportedError("ejabberd 14.07 does not support setting last activity.")
raise BackendError(code)
def block_user(self, username, domain):
# 14.07 is really broken here. ban_account fails, and we cannot set a random password
# either because user_sessions_info doesn't work either and thus we can't stop existing
# connections. And stopping existing connections doesn't work either.
code, out, err = self.ctl('ban_account', username, domain, 'Blocked')
if code != 0:
if code == 1 and self.api_version == (14, 7):
raise NotSupportedError("ejabberd 14.07 does not support banning accounts.")
raise BackendError(code)
def check_password(self, username, domain, password):
code, out, err = self.ctl('check_password', username, domain, password)
if code == 0:
return True
elif code == 1:
return False
else:
raise BackendError(code)
def set_password(self, username, domain, password):
if self.api_version <= (16, 1, ) and not self.user_exists(username, domain):
# 16.01 just creates the user upon change_password!
# NOTE: This may also affect other versions < 16.09.
raise UserNotFound(username, domain)
code, out, err = self.ctl('change_password', username, domain, password)
if six.PY3:
out = out.decode('utf-8')
if code == 1 and out == '{not_found,"unknown_user"}\n':
raise UserNotFound(username, domain)
elif code != 0: # 0 is also returned if the user doesn't exist.
raise BackendError(code)
def set_unusable_password(self, username, domain):
code, out, err = self.ctl('ban_account', username, domain, 'by xmpp-account')
if code != 0:
raise BackendError(code)
def all_domains(self):
code, out, err = self.ctl('registered_vhosts')
if code != 0:
raise BackendError(code)
if six.PY3:
out = out.decode('utf-8')
return set(out.splitlines())
def all_users(self, domain):
code, out, err = self.ctl('registered_users', domain)
if code != 0:
raise BackendError(code)
if six.PY3:
out = out.decode('utf-8')
return set(out.splitlines())
def all_user_sessions(self):
code, out, err = self.ctl('connected_users_info')
if code != 0:
raise BackendError(code)
out = out.decode('utf-8') # bytes -> str in py3, str -> unicode in py2
sessions = set()
for line in out.splitlines():
if self.api_version < (18, 6):
jid, conn, ip, _p, prio, node, uptime = line.split('\t', 6)
status = ''
statustext = ''
else:
jid, conn, ip, _p, prio, node, uptime, status, resource, statustext = line.split('\t', 9)
username, domain = jid.split('@', 1)
domain, resource = domain.split('/', 1)
if prio == 'nil':
prio = None
else:
prio = int(prio)
started = pytz.utc.localize(datetime.utcnow() - timedelta(int(uptime)))
typ, encrypted, compressed = self.parse_connection_string(conn)
sessions.add(UserSession(
backend=self,
username=username,
domain=domain,
resource=resource,
priority=prio,
ip_address=self.parse_ip_address(ip),
uptime=started,
status=status,
status_text=statustext,
connection_type=typ, encrypted=encrypted, compressed=compressed
))
if len(sessions) == 0 and self.api_version == (15, 7):
# NOTE: 14.07 and 16.01 work, unclear were/when this broke and when it was fixed
raise NotSupportedError("ejabberd = 15.07 always returns an empty list.")
return sessions
def remove_user(self, username, domain):
code, out, err = self.ctl('unregister', username, domain)
if code != 0: # 0 is also returned if the user does not exist
raise BackendError(code)
def stats(self, stat, domain=None):
if stat == 'registered_users':
stat = 'registeredusers'
elif stat == 'online_users':
stat = 'onlineusers'
else:
raise ValueError("Unknown stat %s" % stat)
if domain is None:
code, out, err = self.ctl('stats', stat)
else:
code, out, err = self.ctl('stats_host', stat, domain)
if code == 0:
return int(out)
else:
raise BackendError(code)
|
mathiasertl/xmpp-backends
|
xmpp_backends/django/models.py
|
XmppBackendUser.set_password
|
python
|
def set_password(self, raw_password):
if raw_password is None:
self.set_unusable_password()
else:
xmpp_backend.set_password(self.node, self.domain, raw_password)
|
Calls :py:func:`~xmpp_backends.base.XmppBackendBase.set_password` for the user.
If password is ``None``, calls :py:func:`~xmpp_backends.base.XmppBackendBase.set_unusable_password`.
|
train
|
https://github.com/mathiasertl/xmpp-backends/blob/214ef0664dbf90fa300c2483b9b3416559e5d171/xmpp_backends/django/models.py#L39-L47
| null |
class XmppBackendUser(AbstractBaseUser):
"""An abstract base model using xmpp as backend for various functions.
The model assumes that the username as returned by :py:func:`get_username` is the full JID of the user.
"""
class Meta:
verbose_name = _('user')
verbose_name_plural = _('users')
abstract = True
def exists(self):
return xmpp_backend.user_exists(self.node, self.domain)
def check_password(self, raw_password):
"""Calls :py:func:`~xmpp_backends.base.XmppBackendBase.check_password` for the user."""
return xmpp_backend.check_password(self.node, self.domain, raw_password)
def set_unusable_password(self):
"""Calls :py:func:`~xmpp_backends.base.XmppBackendBase.ban_account` for the user."""
xmpp_backend.block_user(self.node, self.domain)
def get_short_name(self):
"""An alias for ``node``."""
return self.node
@property
def node(self):
"""The node-part of the username.
Example::
>>> u = XmppBackendUser(username='user@example.com')
>>> u.node
'user'
"""
return self.get_username().split('@', 1)[0]
@property
def domain(self):
"""The domain-part of the username.
Example::
>>> u = XmppBackendUser(username='user@example.com')
>>> u.domain
'example.com'
"""
return self.get_username().split('@', 1)[1]
|
mathiasertl/xmpp-backends
|
xmpp_backends/django/models.py
|
XmppBackendUser.check_password
|
python
|
def check_password(self, raw_password):
return xmpp_backend.check_password(self.node, self.domain, raw_password)
|
Calls :py:func:`~xmpp_backends.base.XmppBackendBase.check_password` for the user.
|
train
|
https://github.com/mathiasertl/xmpp-backends/blob/214ef0664dbf90fa300c2483b9b3416559e5d171/xmpp_backends/django/models.py#L49-L51
| null |
class XmppBackendUser(AbstractBaseUser):
"""An abstract base model using xmpp as backend for various functions.
The model assumes that the username as returned by :py:func:`get_username` is the full JID of the user.
"""
class Meta:
verbose_name = _('user')
verbose_name_plural = _('users')
abstract = True
def exists(self):
return xmpp_backend.user_exists(self.node, self.domain)
def set_password(self, raw_password):
"""Calls :py:func:`~xmpp_backends.base.XmppBackendBase.set_password` for the user.
If password is ``None``, calls :py:func:`~xmpp_backends.base.XmppBackendBase.set_unusable_password`.
"""
if raw_password is None:
self.set_unusable_password()
else:
xmpp_backend.set_password(self.node, self.domain, raw_password)
def set_unusable_password(self):
"""Calls :py:func:`~xmpp_backends.base.XmppBackendBase.ban_account` for the user."""
xmpp_backend.block_user(self.node, self.domain)
def get_short_name(self):
"""An alias for ``node``."""
return self.node
@property
def node(self):
"""The node-part of the username.
Example::
>>> u = XmppBackendUser(username='user@example.com')
>>> u.node
'user'
"""
return self.get_username().split('@', 1)[0]
@property
def domain(self):
"""The domain-part of the username.
Example::
>>> u = XmppBackendUser(username='user@example.com')
>>> u.domain
'example.com'
"""
return self.get_username().split('@', 1)[1]
|
mathiasertl/xmpp-backends
|
xmpp_backends/dummy.py
|
DummyBackend.start_user_session
|
python
|
def start_user_session(self, username, domain, resource, **kwargs):
kwargs.setdefault('uptime', pytz.utc.localize(datetime.utcnow()))
kwargs.setdefault('priority', 0)
kwargs.setdefault('status', 'online')
kwargs.setdefault('status_text', '')
kwargs.setdefault('connection_type', CONNECTION_XMPP)
kwargs.setdefault('encrypted', True)
kwargs.setdefault('compressed', False)
kwargs.setdefault('ip_address', '127.0.0.1')
if six.PY2 and isinstance(kwargs['ip_address'], str):
# ipaddress constructor does not eat str in py2 :-/
kwargs['ip_address'] = kwargs['ip_address'].decode('utf-8')
if isinstance(kwargs['ip_address'], six.string_types):
kwargs['ip_address'] = ipaddress.ip_address(kwargs['ip_address'])
user = '%s@%s' % (username, domain)
session = UserSession(self, username, domain, resource, **kwargs)
data = self.module.get(user)
if data is None:
raise UserNotFound(username, domain, resource)
data.setdefault('sessions', set())
if isinstance(data['sessions'], list):
# Cast old data to set
data['sessions'] = set(data['sessions'])
data['sessions'].add(session)
self.module.set(user, data)
all_sessions = self.module.get('all_sessions', set())
all_sessions.add(session)
self.module.set('all_sessions', all_sessions)
|
Method to add a user session for debugging.
Accepted parameters are the same as to the constructor of :py:class:`~xmpp_backends.base.UserSession`.
|
train
|
https://github.com/mathiasertl/xmpp-backends/blob/214ef0664dbf90fa300c2483b9b3416559e5d171/xmpp_backends/dummy.py#L66-L103
| null |
class DummyBackend(XmppBackendBase):
"""A dummy backend for development using Djangos caching framework.
By default, Djangos caching framework uses in-memory data structures, so every registration will be
removed if you restart the development server. You can configure a different cache (e.g. memcached), see
`Django's cache framework <https://docs.djangoproject.com/en/dev/topics/cache/>`_ for details.
:params domains: A list of domains to serve.
"""
library = 'django.core.cache.cache'
def __init__(self, domains):
super(DummyBackend, self).__init__()
self._domains = domains
def get_api_version(self):
return (1, 0)
def user_exists(self, username, domain):
if domain not in self._domains:
return False
user = '%s@%s' % (username, domain)
return self.module.get(user) is not None
def user_sessions(self, username, domain):
user = '%s@%s' % (username, domain)
return self.module.get(user, {}).get('sessions', set())
def stop_user_session(self, username, domain, resource, reason=''):
user = '%s@%s' % (username, domain)
data = self.module.get(user)
if data is None:
raise UserNotFound(username, domain)
data['sessions'] = set([d for d in data.get('sessions', []) if d.resource != resource])
self.module.set(user, data)
all_sessions = self.module.get('all_sessions', set())
all_sessions = set([s for s in all_sessions if s.jid != user])
self.module.set('all_sessions', all_sessions)
def create_user(self, username, domain, password, email=None):
if domain not in self._domains:
raise BackendError('Backend does not serve domain %s.' % domain)
user = '%s@%s' % (username, domain)
log.debug('Create user: %s (%s)', user, password)
data = self.module.get(user)
if data is None:
data = {
'pass': password,
'last_status': (time.time(), 'Registered'),
'sessions': set(),
}
if email is not None:
data['email'] = email
self.module.set(user, data)
# maintain list of users in cache
users = self.module.get('all_users', set())
users.add(user)
self.module.set('all_users', users)
else:
raise UserExists()
def check_password(self, username, domain, password):
user = '%s@%s' % (username, domain)
log.debug('Check pass: %s -> %s', user, password)
data = self.module.get(user)
if data is None:
return False
else:
return data['pass'] == password
def check_email(self, username, domain, email):
user = '%s@%s' % (username, domain)
log.debug('Check email: %s --> %s', user, email)
data = self.module.get(user)
if data is None:
return False
else:
return data['email'] == email
def set_password(self, username, domain, password):
user = '%s@%s' % (username, domain)
log.debug('Set pass: %s -> %s', user, password)
data = self.module.get(user)
if data is None:
raise UserNotFound(username, domain)
else:
data['pass'] = password
self.module.set(user, data)
def set_email(self, username, domain, email):
user = '%s@%s' % (username, domain)
log.debug('Set email: %s --> %s', user, email)
data = self.module.get(user)
if data is None:
raise UserNotFound(username, domain)
else:
data['email'] = email
self.module.set(user, data)
def get_last_activity(self, username, domain):
user = '%s@%s' % (username, domain)
data = self.module.get(user)
if data is None:
raise UserNotFound(username, domain)
else:
return datetime.utcfromtimestamp(data['last_status'][0])
def set_last_activity(self, username, domain, status='', timestamp=None):
user = '%s@%s' % (username, domain)
if timestamp is None:
timestamp = time.time()
else:
timestamp = self.datetime_to_timestamp(timestamp)
data = self.module.get(user)
if data is None:
pass # NOTE: real APIs provide no error either :-/
else:
data['last_status'] = (timestamp, status)
self.module.set(user, data)
def block_user(self, username, domain):
# overwritten so we pass tests
self.set_password(username, domain, self.get_random_password())
def all_domains(self):
"""Just returns the domains passed to the constructor."""
return list(self._domains)
def all_users(self, domain):
return set([u.split('@')[0] for u in self.module.get('all_users', set())
if u.endswith('@%s' % domain)])
def all_user_sessions(self):
return self.module.get('all_sessions', set())
def remove_user(self, username, domain):
user = '%s@%s' % (username, domain)
log.debug('Remove: %s', user)
users = self.module.get('all_users', set())
users.remove(user)
self.module.set('all_users', users)
self.module.delete(user)
def stats(self, stat, domain=None):
"""Always returns 0."""
return 0
def message_user(self, username, domain, subject, message):
user = '%s@%s' % (username, domain)
data = self.module.get(user)
if data is None:
return # user does not exist
data.setdefault('messages', [])
data['messages'].append({
'date': datetime.utcnow(),
'message': message,
'sender': domain,
'subject': subject,
})
self.module.set(user, data)
|
mathiasertl/xmpp-backends
|
xmpp_backends/xmlrpclib.py
|
dumps
|
python
|
def dumps(params, methodname=None, methodresponse=None, encoding=None,
allow_none=0, utf8_encoding='standard'):
assert isinstance(params, TupleType) or isinstance(params, Fault),\
"argument must be tuple or Fault instance"
if isinstance(params, Fault):
methodresponse = 1
elif methodresponse and isinstance(params, TupleType):
assert len(params) == 1, "response tuple must be a singleton"
if not encoding:
encoding = "utf-8"
if FastMarshaller:
m = FastMarshaller(encoding)
else:
m = Marshaller(encoding, allow_none)
data = m.dumps(params)
if encoding != "utf-8":
xmlheader = "<?xml version='1.0' encoding='%s'?>\n" % str(encoding)
else:
xmlheader = "<?xml version='1.0'?>\n" # utf-8 is default
# standard XML-RPC wrappings
if methodname:
# a method call
if not isinstance(methodname, StringType):
methodname = methodname.encode(encoding)
data = (
xmlheader,
"<methodCall>\n"
"<methodName>", methodname, "</methodName>\n",
data,
"</methodCall>\n"
)
elif methodresponse:
# a method response, or a fault structure
data = (
xmlheader,
"<methodResponse>\n",
data,
"</methodResponse>\n"
)
else:
return data # return as is
return string.join(data, "")
|
data [,options] -> marshalled data
Convert an argument tuple or a Fault instance to an XML-RPC
request (or response, if the methodresponse option is used).
In addition to the data object, the following options can be given
as keyword arguments:
methodname: the method name for a methodCall packet
methodresponse: true to create a methodResponse packet.
If this option is used with a tuple, the tuple must be
a singleton (i.e. it can contain only one element).
encoding: the packet encoding (default is UTF-8)
All 8-bit strings in the data structure are assumed to use the
packet encoding. Unicode strings are automatically converted,
where necessary.
|
train
|
https://github.com/mathiasertl/xmpp-backends/blob/214ef0664dbf90fa300c2483b9b3416559e5d171/xmpp_backends/xmlrpclib.py#L1139-L1207
| null |
# -*- coding: utf-8 -*-
#
# XML-RPC CLIENT LIBRARY
# $Id$
#
# This is a copy of the xmlrpclib library shipping with Python 2.7.
# It is modified to encode UTF-8 characters in several different ways.
#
# The problem is that this library does not encode UTF-8 correctly and PHP's
# library doesn't encode them correctly either - but wrong in a differnt way.
# ejabberd <= 14.07 expects unicode in the way PHP encodes them and ejabberd
# versions after that expect unicode to be encoded according to XML standards.
#
# Here is an overview of what different encoding options there are,
# demonstrated by the example letter 'ä'. Use:
# https://en.wikipedia.org/wiki/%C3%84#Computer_encoding
# as reference next to the following examples:
#
# XML standard = what lxml produces and ejabberd > 14.07 accepts:
#
# >>> from lxml import etree
# >>> t = etree.Element('test')
# >>> t.text = u'ä' # note: 'ä' is not accepted
# >>> etree.tostring(t)
# <test>ä</test>
#
# What PHP produces and ejabberd <= 14.07 accepts:
#
# $ php -r 'print xmlrpc_encode("ä");'
# ...
# <string>ä</string>
# ...
#
# No encoding - Conforms to standards and is what Python3 produces
# (unknown if ejabberd accepts it)
#
# >>> import xmlrpclib
# >>> xmlrpclib.escape('ä')
# 'ä'
#
# What xmlrpclib in Python2 produces:
# >>> import xmlrpclib
# >>> xmlrpclib.escape('ä')
# '\xc3\xa4'
# >>> xmlrpclib.escape(u'ä') # unicode is not supported!
# ...
# TypeError: encode() argument 1 must be string, not None
#
# This library differs from the version that ships with Python 2.7.10 in that
# it adds a `utf8_encoding` parameter to support all three different encoding
# options. All changes are marked with a line starting with:
#
# xmpp-backends: ...
#
#
# an XML-RPC client interface for Python.
#
# the marshalling and response parser code can also be used to
# implement XML-RPC servers.
#
# Notes:
# this version is designed to work with Python 2.1 or newer.
#
# History:
# 1999-01-14 fl Created
# 1999-01-15 fl Changed dateTime to use localtime
# 1999-01-16 fl Added Binary/base64 element, default to RPC2 service
# 1999-01-19 fl Fixed array data element (from Skip Montanaro)
# 1999-01-21 fl Fixed dateTime constructor, etc.
# 1999-02-02 fl Added fault handling, handle empty sequences, etc.
# 1999-02-10 fl Fixed problem with empty responses (from Skip Montanaro)
# 1999-06-20 fl Speed improvements, pluggable parsers/transports (0.9.8)
# 2000-11-28 fl Changed boolean to check the truth value of its argument
# 2001-02-24 fl Added encoding/Unicode/SafeTransport patches
# 2001-02-26 fl Added compare support to wrappers (0.9.9/1.0b1)
# 2001-03-28 fl Make sure response tuple is a singleton
# 2001-03-29 fl Don't require empty params element (from Nicholas Riley)
# 2001-06-10 fl Folded in _xmlrpclib accelerator support (1.0b2)
# 2001-08-20 fl Base xmlrpclib.Error on built-in Exception (from Paul Prescod)
# 2001-09-03 fl Allow Transport subclass to override getparser
# 2001-09-10 fl Lazy import of urllib, cgi, xmllib (20x import speedup)
# 2001-10-01 fl Remove containers from memo cache when done with them
# 2001-10-01 fl Use faster escape method (80% dumps speedup)
# 2001-10-02 fl More dumps microtuning
# 2001-10-04 fl Make sure import expat gets a parser (from Guido van Rossum)
# 2001-10-10 sm Allow long ints to be passed as ints if they don't overflow
# 2001-10-17 sm Test for int and long overflow (allows use on 64-bit systems)
# 2001-11-12 fl Use repr() to marshal doubles (from Paul Felix)
# 2002-03-17 fl Avoid buffered read when possible (from James Rucker)
# 2002-04-07 fl Added pythondoc comments
# 2002-04-16 fl Added __str__ methods to datetime/binary wrappers
# 2002-05-15 fl Added error constants (from Andrew Kuchling)
# 2002-06-27 fl Merged with Python CVS version
# 2002-10-22 fl Added basic authentication (based on code from Phillip Eby)
# 2003-01-22 sm Add support for the bool type
# 2003-02-27 gvr Remove apply calls
# 2003-04-24 sm Use cStringIO if available
# 2003-04-25 ak Add support for nil
# 2003-06-15 gn Add support for time.struct_time
# 2003-07-12 gp Correct marshalling of Faults
# 2003-10-31 mvl Add multicall support
# 2004-08-20 mvl Bump minimum supported Python version to 2.1
# 2014-12-02 ch/doko Add workaround for gzip bomb vulnerability
#
# Copyright (c) 1999-2002 by Secret Labs AB.
# Copyright (c) 1999-2002 by Fredrik Lundh.
#
# info@pythonware.com
# http://www.pythonware.com
#
# --------------------------------------------------------------------
# The XML-RPC client interface is
#
# Copyright (c) 1999-2002 by Secret Labs AB
# Copyright (c) 1999-2002 by Fredrik Lundh
#
# By obtaining, using, and/or copying this software and/or its
# associated documentation, you agree that you have read, understood,
# and will comply with the following terms and conditions:
#
# Permission to use, copy, modify, and distribute this software and
# its associated documentation for any purpose and without fee is
# hereby granted, provided that the above copyright notice appears in
# all copies, and that both that copyright notice and this permission
# notice appear in supporting documentation, and that the name of
# Secret Labs AB or the author not be used in advertising or publicity
# pertaining to distribution of the software without specific, written
# prior permission.
#
# SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
# TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANT-
# ABILITY AND FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR
# BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY
# DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
# WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
# ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
# OF THIS SOFTWARE.
# --------------------------------------------------------------------
#
# things to look into some day:
# TODO: sort out True/False/boolean issues for Python 2.3
"""
An XML-RPC client interface for Python.
The marshalling and response parser code can also be used to
implement XML-RPC servers.
Exported exceptions:
Error Base class for client errors
ProtocolError Indicates an HTTP protocol error
ResponseError Indicates a broken response package
Fault Indicates an XML-RPC fault package
Exported classes:
ServerProxy Represents a logical connection to an XML-RPC server
MultiCall Executor of boxcared xmlrpc requests
Boolean boolean wrapper to generate a "boolean" XML-RPC value
DateTime dateTime wrapper for an ISO 8601 string or time tuple or
localtime integer value to generate a "dateTime.iso8601"
XML-RPC value
Binary binary data wrapper
SlowParser Slow but safe standard parser (based on xmllib)
Marshaller Generate an XML-RPC params chunk from a Python data structure
Unmarshaller Unmarshal an XML-RPC response from incoming XML event message
Transport Handles an HTTP transaction to an XML-RPC server
SafeTransport Handles an HTTPS transaction to an XML-RPC server
Exported constants:
True
False
Exported functions:
boolean Convert any Python value to an XML-RPC boolean
getparser Create instance of the fastest available parser & attach
to an unmarshalling object
dumps Convert an argument tuple or a Fault instance to an XML-RPC
request (or response, if the methodresponse option is used).
loads Convert an XML-RPC packet to unmarshalled data plus a method
name (None if not present).
"""
import re, string, time, operator
# xmpp-backends: Do not use wildcard import to improve syntax checkers
from types import (TupleType, StringType, InstanceType, NoneType, IntType,
LongType, FloatType, ListType, DictType, UnicodeType)
import socket
import errno
import httplib
try:
import gzip
except ImportError:
gzip = None #python can be built without zlib/gzip support
# --------------------------------------------------------------------
# Internal stuff
try:
unicode
except NameError:
unicode = None # unicode support not available
try:
import datetime
except ImportError:
datetime = None
try:
_bool_is_builtin = False.__class__.__name__ == "bool"
except NameError:
_bool_is_builtin = 0
def _decode(data, encoding, is8bit=re.compile("[\x80-\xff]").search):
# decode non-ascii string (if possible)
if unicode and encoding and is8bit(data):
data = unicode(data, encoding)
return data
# xmpp-backends: Add the utf8_encoding parameter
def escape(s, replace=string.replace, utf8_encoding='standard'):
s = replace(s, "&", "&")
s = replace(s, "<", "<")
s = replace(s, ">", ">")
if utf8_encoding == 'python2':
return s
elif utf8_encoding == 'none':
if isinstance(s, unicode):
return s
return s.decode('utf-8')
encoded = ''
# xmpp-backends: Handle the utf8_encoding parameter
if utf8_encoding == 'php':
if isinstance(s, unicode): # py2 and unicode
_encode = lambda char: ''.join(['&#%s;' % ord(b) for b in char.encode('utf-8')])
else: # py2 str
_encode = lambda char: ''.join(['&#%s;' % ord(b) for b in char])
elif utf8_encoding == 'standard':
if isinstance(s, str):
s = s.decode('utf-8')
_encode = lambda char: '&#%s;' % ord(char)
else:
raise AttributeError("Unknown utf8_encoding '%s'" % utf8_encoding)
for char in s:
if ord(char) >= 128:
encoded += _encode(char)
else:
encoded += char
return encoded
if unicode:
def _stringify(string):
# convert to 7-bit ascii if possible
try:
return string.encode("ascii")
except UnicodeError:
return string
else:
def _stringify(string):
return string
__version__ = "1.0.1"
# xmlrpc integer limits
MAXINT = 2 **31-1
MININT = -2 **31
# --------------------------------------------------------------------
# Error constants (from Dan Libby's specification at
# http://xmlrpc-epi.sourceforge.net/specs/rfc.fault_codes.php)
# Ranges of errors
PARSE_ERROR = -32700
SERVER_ERROR = -32600
APPLICATION_ERROR = -32500
SYSTEM_ERROR = -32400
TRANSPORT_ERROR = -32300
# Specific errors
NOT_WELLFORMED_ERROR = -32700
UNSUPPORTED_ENCODING = -32701
INVALID_ENCODING_CHAR = -32702
INVALID_XMLRPC = -32600
METHOD_NOT_FOUND = -32601
INVALID_METHOD_PARAMS = -32602
INTERNAL_ERROR = -32603
# --------------------------------------------------------------------
# Exceptions
##
# Base class for all kinds of client-side errors.
class Error(Exception):
"""Base class for client errors."""
def __str__(self):
return repr(self)
##
# Indicates an HTTP-level protocol error. This is raised by the HTTP
# transport layer, if the server returns an error code other than 200
# (OK).
#
# @param url The target URL.
# @param errcode The HTTP error code.
# @param errmsg The HTTP error message.
# @param headers The HTTP header dictionary.
class ProtocolError(Error):
"""Indicates an HTTP protocol error."""
def __init__(self, url, errcode, errmsg, headers):
Error.__init__(self)
self.url = url
self.errcode = errcode
self.errmsg = errmsg
self.headers = headers
def __repr__(self):
return (
"<ProtocolError for %s: %s %s>" %
(self.url, self.errcode, self.errmsg)
)
##
# Indicates a broken XML-RPC response package. This exception is
# raised by the unmarshalling layer, if the XML-RPC response is
# malformed.
class ResponseError(Error):
"""Indicates a broken response package."""
pass
##
# Indicates an XML-RPC fault response package. This exception is
# raised by the unmarshalling layer, if the XML-RPC response contains
# a fault string. This exception can also used as a class, to
# generate a fault XML-RPC message.
#
# @param faultCode The XML-RPC fault code.
# @param faultString The XML-RPC fault string.
class Fault(Error):
"""Indicates an XML-RPC fault package."""
def __init__(self, faultCode, faultString, **extra):
Error.__init__(self)
self.faultCode = faultCode
self.faultString = faultString
def __repr__(self):
return (
"<Fault %s: %s>" %
(self.faultCode, repr(self.faultString))
)
# --------------------------------------------------------------------
# Special values
##
# Wrapper for XML-RPC boolean values. Use the xmlrpclib.True and
# xmlrpclib.False constants, or the xmlrpclib.boolean() function, to
# generate boolean XML-RPC values.
#
# @param value A boolean value. Any true value is interpreted as True,
# all other values are interpreted as False.
from sys import modules
mod_dict = modules[__name__].__dict__
if _bool_is_builtin:
boolean = Boolean = bool
# to avoid breaking code which references xmlrpclib.{True,False}
mod_dict['True'] = True
mod_dict['False'] = False
else:
class Boolean:
"""Boolean-value wrapper.
Use True or False to generate a "boolean" XML-RPC value.
"""
def __init__(self, value = 0):
self.value = operator.truth(value)
def encode(self, out):
out.write("<value><boolean>%d</boolean></value>\n" % self.value)
def __cmp__(self, other):
if isinstance(other, Boolean):
other = other.value
return cmp(self.value, other)
def __repr__(self):
if self.value:
return "<Boolean True at %x>" % id(self)
else:
return "<Boolean False at %x>" % id(self)
def __int__(self):
return self.value
def __nonzero__(self):
return self.value
mod_dict['True'] = Boolean(1)
mod_dict['False'] = Boolean(0)
##
# Map true or false value to XML-RPC boolean values.
#
# @def boolean(value)
# @param value A boolean value. Any true value is mapped to True,
# all other values are mapped to False.
# @return xmlrpclib.True or xmlrpclib.False.
# @see Boolean
# @see True
# @see False
def boolean(value, _truefalse=(False, True)):
"""Convert any Python value to XML-RPC 'boolean'."""
return _truefalse[operator.truth(value)]
del modules, mod_dict
##
# Wrapper for XML-RPC DateTime values. This converts a time value to
# the format used by XML-RPC.
# <p>
# The value can be given as a string in the format
# "yyyymmddThh:mm:ss", as a 9-item time tuple (as returned by
# time.localtime()), or an integer value (as returned by time.time()).
# The wrapper uses time.localtime() to convert an integer to a time
# tuple.
#
# @param value The time, given as an ISO 8601 string, a time
# tuple, or a integer time value.
def _strftime(value):
if datetime:
if isinstance(value, datetime.datetime):
return "%04d%02d%02dT%02d:%02d:%02d" % (
value.year, value.month, value.day,
value.hour, value.minute, value.second)
if not isinstance(value, (TupleType, time.struct_time)):
if value == 0:
value = time.time()
value = time.localtime(value)
return "%04d%02d%02dT%02d:%02d:%02d" % value[:6]
class DateTime:
"""DateTime wrapper for an ISO 8601 string or time tuple or
localtime integer value to generate 'dateTime.iso8601' XML-RPC
value.
"""
def __init__(self, value=0):
if isinstance(value, StringType):
self.value = value
else:
self.value = _strftime(value)
def make_comparable(self, other):
if isinstance(other, DateTime):
s = self.value
o = other.value
elif datetime and isinstance(other, datetime.datetime):
s = self.value
o = other.strftime("%Y%m%dT%H:%M:%S")
elif isinstance(other, (str, unicode)):
s = self.value
o = other
elif hasattr(other, "timetuple"):
s = self.timetuple()
o = other.timetuple()
else:
otype = (hasattr(other, "__class__")
and other.__class__.__name__
or type(other))
raise TypeError("Can't compare %s and %s" %
(self.__class__.__name__, otype))
return s, o
def __lt__(self, other):
s, o = self.make_comparable(other)
return s < o
def __le__(self, other):
s, o = self.make_comparable(other)
return s <= o
def __gt__(self, other):
s, o = self.make_comparable(other)
return s > o
def __ge__(self, other):
s, o = self.make_comparable(other)
return s >= o
def __eq__(self, other):
s, o = self.make_comparable(other)
return s == o
def __ne__(self, other):
s, o = self.make_comparable(other)
return s != o
def timetuple(self):
return time.strptime(self.value, "%Y%m%dT%H:%M:%S")
def __cmp__(self, other):
s, o = self.make_comparable(other)
return cmp(s, o)
##
# Get date/time value.
#
# @return Date/time value, as an ISO 8601 string.
def __str__(self):
return self.value
def __repr__(self):
return "<DateTime %s at %x>" % (repr(self.value), id(self))
def decode(self, data):
data = str(data)
self.value = string.strip(data)
def encode(self, out):
out.write("<value><dateTime.iso8601>")
out.write(self.value)
out.write("</dateTime.iso8601></value>\n")
def _datetime(data):
# decode xml element contents into a DateTime structure.
value = DateTime()
value.decode(data)
return value
def _datetime_type(data):
t = time.strptime(data, "%Y%m%dT%H:%M:%S")
return datetime.datetime(*tuple(t)[:6])
##
# Wrapper for binary data. This can be used to transport any kind
# of binary data over XML-RPC, using BASE64 encoding.
#
# @param data An 8-bit string containing arbitrary data.
import base64
try:
import cStringIO as StringIO
except ImportError:
import StringIO
class Binary:
"""Wrapper for binary data."""
def __init__(self, data=None):
self.data = data
##
# Get buffer contents.
#
# @return Buffer contents, as an 8-bit string.
def __str__(self):
return self.data or ""
def __cmp__(self, other):
if isinstance(other, Binary):
other = other.data
return cmp(self.data, other)
def decode(self, data):
self.data = base64.decodestring(data)
def encode(self, out):
out.write("<value><base64>\n")
base64.encode(StringIO.StringIO(self.data), out)
out.write("</base64></value>\n")
def _binary(data):
# decode xml element contents into a Binary structure
value = Binary()
value.decode(data)
return value
WRAPPERS = (DateTime, Binary)
if not _bool_is_builtin:
WRAPPERS = WRAPPERS + (Boolean,)
# --------------------------------------------------------------------
# XML parsers
try:
# optional xmlrpclib accelerator
import _xmlrpclib
FastParser = _xmlrpclib.Parser
FastUnmarshaller = _xmlrpclib.Unmarshaller
except (AttributeError, ImportError):
FastParser = FastUnmarshaller = None
try:
import _xmlrpclib
FastMarshaller = _xmlrpclib.Marshaller
except (AttributeError, ImportError):
FastMarshaller = None
try:
from xml.parsers import expat
if not hasattr(expat, "ParserCreate"):
raise ImportError
except ImportError:
ExpatParser = None # expat not available
else:
class ExpatParser:
# fast expat parser for Python 2.0 and later.
def __init__(self, target):
self._parser = parser = expat.ParserCreate(None, None)
self._target = target
parser.StartElementHandler = target.start
parser.EndElementHandler = target.end
parser.CharacterDataHandler = target.data
encoding = None
if not parser.returns_unicode:
encoding = "utf-8"
target.xml(encoding, None)
def feed(self, data):
self._parser.Parse(data, 0)
def close(self):
try:
parser = self._parser
except AttributeError:
pass
else:
del self._target, self._parser # get rid of circular references
parser.Parse("", 1) # end of data
class SlowParser:
"""Default XML parser (based on xmllib.XMLParser)."""
# this is the slowest parser.
def __init__(self, target):
import xmllib # lazy subclassing (!)
if xmllib.XMLParser not in SlowParser.__bases__:
SlowParser.__bases__ = (xmllib.XMLParser,)
self.handle_xml = target.xml
self.unknown_starttag = target.start
self.handle_data = target.data
self.handle_cdata = target.data
self.unknown_endtag = target.end
try:
xmllib.XMLParser.__init__(self, accept_utf8=1)
except TypeError:
xmllib.XMLParser.__init__(self) # pre-2.0
# --------------------------------------------------------------------
# XML-RPC marshalling and unmarshalling code
##
# XML-RPC marshaller.
#
# @param encoding Default encoding for 8-bit strings. The default
# value is None (interpreted as UTF-8).
# @see dumps
class Marshaller:
"""Generate an XML-RPC params chunk from a Python data structure.
Create a Marshaller instance for each set of parameters, and use
the "dumps" method to convert your data (represented as a tuple)
to an XML-RPC params chunk. To write a fault response, pass a
Fault instance instead. You may prefer to use the "dumps" module
function for this purpose.
"""
# by the way, if you don't understand what's going on in here,
# that's perfectly ok.
# xmpp-backends: Add the utf8_encoding parameter
def __init__(self, encoding=None, allow_none=0, utf8_encoding='standard'):
self.memo = {}
self.data = None
self.encoding = encoding
self.allow_none = allow_none
# xmpp-backends: Set the self.utf8_encoding property
self.utf8_encoding = utf8_encoding
dispatch = {}
def dumps(self, values):
out = []
write = out.append
dump = self.__dump
if isinstance(values, Fault):
# fault instance
write("<fault>\n")
dump({'faultCode': values.faultCode,
'faultString': values.faultString},
write)
write("</fault>\n")
else:
# parameter block
# FIXME: the xml-rpc specification allows us to leave out
# the entire <params> block if there are no parameters.
# however, changing this may break older code (including
# old versions of xmlrpclib.py), so this is better left as
# is for now. See @XMLRPC3 for more information. /F
write("<params>\n")
for v in values:
write("<param>\n")
dump(v, write)
write("</param>\n")
write("</params>\n")
result = string.join(out, "")
return result
def __dump(self, value, write):
try:
f = self.dispatch[type(value)]
except KeyError:
# check if this object can be marshalled as a structure
try:
value.__dict__
except:
raise TypeError("cannot marshal %s objects" % type(value))
# check if this class is a sub-class of a basic type,
# because we don't know how to marshal these types
# (e.g. a string sub-class)
for type_ in type(value).__mro__:
if type_ in self.dispatch.keys():
raise TypeError("cannot marshal %s objects" % type(value))
f = self.dispatch[InstanceType]
f(self, value, write)
def dump_nil (self, value, write):
if not self.allow_none:
raise TypeError("cannot marshal None unless allow_none is enabled")
write("<value><nil/></value>")
dispatch[NoneType] = dump_nil
def dump_int(self, value, write):
# in case ints are > 32 bits
if value > MAXINT or value < MININT:
raise OverflowError("int exceeds XML-RPC limits")
write("<value><int>")
write(str(value))
write("</int></value>\n")
dispatch[IntType] = dump_int
if _bool_is_builtin:
def dump_bool(self, value, write):
write("<value><boolean>")
write(value and "1" or "0")
write("</boolean></value>\n")
dispatch[bool] = dump_bool
def dump_long(self, value, write):
if value > MAXINT or value < MININT:
raise OverflowError("long int exceeds XML-RPC limits")
write("<value><int>")
write(str(int(value)))
write("</int></value>\n")
dispatch[LongType] = dump_long
def dump_double(self, value, write):
write("<value><double>")
write(repr(value))
write("</double></value>\n")
dispatch[FloatType] = dump_double
def dump_string(self, value, write, escape=escape):
write("<value><string>")
# xmpp-backends: Pass utf8_encoding parameter
write(escape(value, utf8_encoding=self.utf8_encoding))
write("</string></value>\n")
dispatch[StringType] = dump_string
if unicode:
def dump_unicode(self, value, write, escape=escape):
write("<value><string>")
# xmpp-backends: Pass utf8_encoding parameter
write(escape(value, utf8_encoding=self.utf8_encoding))
write("</string></value>\n")
dispatch[UnicodeType] = dump_unicode
def dump_array(self, value, write):
i = id(value)
if i in self.memo:
raise TypeError("cannot marshal recursive sequences")
self.memo[i] = None
dump = self.__dump
write("<value><array><data>\n")
for v in value:
dump(v, write)
write("</data></array></value>\n")
del self.memo[i]
dispatch[TupleType] = dump_array
dispatch[ListType] = dump_array
def dump_struct(self, value, write, escape=escape):
i = id(value)
if i in self.memo:
raise TypeError("cannot marshal recursive dictionaries")
self.memo[i] = None
dump = self.__dump
write("<value><struct>\n")
for k, v in value.items():
write("<member>\n")
if type(k) is not StringType:
if unicode and type(k) is UnicodeType:
k = k.encode(self.encoding)
else:
raise TypeError("dictionary key must be string")
write("<name>%s</name>\n" % escape(k))
dump(v, write)
write("</member>\n")
write("</struct></value>\n")
del self.memo[i]
dispatch[DictType] = dump_struct
if datetime:
def dump_datetime(self, value, write):
write("<value><dateTime.iso8601>")
write(_strftime(value))
write("</dateTime.iso8601></value>\n")
dispatch[datetime.datetime] = dump_datetime
def dump_instance(self, value, write):
# check for special wrappers
if value.__class__ in WRAPPERS:
self.write = write
value.encode(self)
del self.write
else:
# store instance attributes as a struct (really?)
self.dump_struct(value.__dict__, write)
dispatch[InstanceType] = dump_instance
##
# XML-RPC unmarshaller.
#
# @see loads
class Unmarshaller:
"""Unmarshal an XML-RPC response, based on incoming XML event
messages (start, data, end). Call close() to get the resulting
data structure.
Note that this reader is fairly tolerant, and gladly accepts bogus
XML-RPC data without complaining (but not bogus XML).
"""
# and again, if you don't understand what's going on in here,
# that's perfectly ok.
def __init__(self, use_datetime=0):
self._type = None
self._stack = []
self._marks = []
self._data = []
self._methodname = None
self._encoding = "utf-8"
self.append = self._stack.append
self._use_datetime = use_datetime
if use_datetime and not datetime:
raise ValueError("the datetime module is not available")
def close(self):
# return response tuple and target method
if self._type is None or self._marks:
raise ResponseError()
if self._type == "fault":
raise Fault(**self._stack[0])
return tuple(self._stack)
def getmethodname(self):
return self._methodname
#
# event handlers
def xml(self, encoding, standalone):
self._encoding = encoding
# FIXME: assert standalone == 1 ???
def start(self, tag, attrs):
# prepare to handle this element
if tag == "array" or tag == "struct":
self._marks.append(len(self._stack))
self._data = []
self._value = (tag == "value")
def data(self, text):
self._data.append(text)
def end(self, tag, join=string.join):
# call the appropriate end tag handler
try:
f = self.dispatch[tag]
except KeyError:
pass # unknown tag ?
else:
return f(self, join(self._data, ""))
#
# accelerator support
def end_dispatch(self, tag, data):
# dispatch data
try:
f = self.dispatch[tag]
except KeyError:
pass # unknown tag ?
else:
return f(self, data)
#
# element decoders
dispatch = {}
def end_nil (self, data):
self.append(None)
self._value = 0
dispatch["nil"] = end_nil
def end_boolean(self, data):
if data == "0":
self.append(False)
elif data == "1":
self.append(True)
else:
raise TypeError("bad boolean value")
self._value = 0
dispatch["boolean"] = end_boolean
def end_int(self, data):
self.append(int(data))
self._value = 0
dispatch["i4"] = end_int
dispatch["i8"] = end_int
dispatch["int"] = end_int
def end_double(self, data):
self.append(float(data))
self._value = 0
dispatch["double"] = end_double
def end_string(self, data):
if self._encoding:
data = _decode(data, self._encoding)
self.append(_stringify(data))
self._value = 0
dispatch["string"] = end_string
dispatch["name"] = end_string # struct keys are always strings
def end_array(self, data):
mark = self._marks.pop()
# map arrays to Python lists
self._stack[mark:] = [self._stack[mark:]]
self._value = 0
dispatch["array"] = end_array
def end_struct(self, data):
mark = self._marks.pop()
# map structs to Python dictionaries
dict = {}
items = self._stack[mark:]
for i in range(0, len(items), 2):
dict[_stringify(items[i])] = items[i+1]
self._stack[mark:] = [dict]
self._value = 0
dispatch["struct"] = end_struct
def end_base64(self, data):
value = Binary()
value.decode(data)
self.append(value)
self._value = 0
dispatch["base64"] = end_base64
def end_dateTime(self, data):
value = DateTime()
value.decode(data)
if self._use_datetime:
value = _datetime_type(data)
self.append(value)
dispatch["dateTime.iso8601"] = end_dateTime
def end_value(self, data):
# if we stumble upon a value element with no internal
# elements, treat it as a string element
if self._value:
self.end_string(data)
dispatch["value"] = end_value
def end_params(self, data):
self._type = "params"
dispatch["params"] = end_params
def end_fault(self, data):
self._type = "fault"
dispatch["fault"] = end_fault
def end_methodName(self, data):
if self._encoding:
data = _decode(data, self._encoding)
self._methodname = data
self._type = "methodName" # no params
dispatch["methodName"] = end_methodName
## Multicall support
#
class _MultiCallMethod:
# some lesser magic to store calls made to a MultiCall object
# for batch execution
def __init__(self, call_list, name):
self.__call_list = call_list
self.__name = name
def __getattr__(self, name):
return _MultiCallMethod(self.__call_list, "%s.%s" % (self.__name, name))
def __call__(self, *args):
self.__call_list.append((self.__name, args))
class MultiCallIterator:
"""Iterates over the results of a multicall. Exceptions are
raised in response to xmlrpc faults."""
def __init__(self, results):
self.results = results
def __getitem__(self, i):
item = self.results[i]
if type(item) == type({}):
raise Fault(item['faultCode'], item['faultString'])
elif type(item) == type([]):
return item[0]
else:
raise ValueError("unexpected type in multicall result")
class MultiCall:
"""server -> a object used to boxcar method calls
server should be a ServerProxy object.
Methods can be added to the MultiCall using normal
method call syntax e.g.:
multicall = MultiCall(server_proxy)
multicall.add(2,3)
multicall.get_address("Guido")
To execute the multicall, call the MultiCall object e.g.:
add_result, address = multicall()
"""
def __init__(self, server):
self.__server = server
self.__call_list = []
def __repr__(self):
return "<MultiCall at %x>" % id(self)
__str__ = __repr__
def __getattr__(self, name):
return _MultiCallMethod(self.__call_list, name)
def __call__(self):
marshalled_list = []
for name, args in self.__call_list:
marshalled_list.append({'methodName' : name, 'params' : args})
return MultiCallIterator(self.__server.system.multicall(marshalled_list))
# --------------------------------------------------------------------
# convenience functions
##
# Create a parser object, and connect it to an unmarshalling instance.
# This function picks the fastest available XML parser.
#
# return A (parser, unmarshaller) tuple.
def getparser(use_datetime=0):
"""getparser() -> parser, unmarshaller
Create an instance of the fastest available parser, and attach it
to an unmarshalling object. Return both objects.
"""
if use_datetime and not datetime:
raise ValueError("the datetime module is not available")
if FastParser and FastUnmarshaller:
if use_datetime:
mkdatetime = _datetime_type
else:
mkdatetime = _datetime
target = FastUnmarshaller(True, False, _binary, mkdatetime, Fault)
parser = FastParser(target)
else:
target = Unmarshaller(use_datetime=use_datetime)
if FastParser:
parser = FastParser(target)
elif ExpatParser:
parser = ExpatParser(target)
else:
parser = SlowParser(target)
return parser, target
##
# Convert a Python tuple or a Fault instance to an XML-RPC packet.
#
# @def dumps(params, **options)
# @param params A tuple or Fault instance.
# @keyparam methodname If given, create a methodCall request for
# this method name.
# @keyparam methodresponse If given, create a methodResponse packet.
# If used with a tuple, the tuple must be a singleton (that is,
# it must contain exactly one element).
# @keyparam encoding The packet encoding.
# @return A string containing marshalled data.
# xmpp-backends: Add the utf8_encoding parameter
##
# Convert an XML-RPC packet to a Python object. If the XML-RPC packet
# represents a fault condition, this function raises a Fault exception.
#
# @param data An XML-RPC packet, given as an 8-bit string.
# @return A tuple containing the unpacked data, and the method name
# (None if not present).
# @see Fault
def loads(data, use_datetime=0):
"""data -> unmarshalled data, method name
Convert an XML-RPC packet to unmarshalled data plus a method
name (None if not present).
If the XML-RPC packet represents a fault condition, this function
raises a Fault exception.
"""
p, u = getparser(use_datetime=use_datetime)
p.feed(data)
p.close()
return u.close(), u.getmethodname()
##
# Encode a string using the gzip content encoding such as specified by the
# Content-Encoding: gzip
# in the HTTP header, as described in RFC 1952
#
# @param data the unencoded data
# @return the encoded data
def gzip_encode(data):
"""data -> gzip encoded data
Encode data using the gzip content encoding as described in RFC 1952
"""
if not gzip:
raise NotImplementedError
f = StringIO.StringIO()
gzf = gzip.GzipFile(mode="wb", fileobj=f, compresslevel=1)
gzf.write(data)
gzf.close()
encoded = f.getvalue()
f.close()
return encoded
##
# Decode a string using the gzip content encoding such as specified by the
# Content-Encoding: gzip
# in the HTTP header, as described in RFC 1952
#
# @param data The encoded data
# @keyparam max_decode Maximum bytes to decode (20MB default), use negative
# values for unlimited decoding
# @return the unencoded data
# @raises ValueError if data is not correctly coded.
# @raises ValueError if max gzipped payload length exceeded
def gzip_decode(data, max_decode=20971520):
"""gzip encoded data -> unencoded data
Decode data using the gzip content encoding as described in RFC 1952
"""
if not gzip:
raise NotImplementedError
f = StringIO.StringIO(data)
gzf = gzip.GzipFile(mode="rb", fileobj=f)
try:
if max_decode < 0: # no limit
decoded = gzf.read()
else:
decoded = gzf.read(max_decode + 1)
except IOError:
raise ValueError("invalid data")
f.close()
gzf.close()
if max_decode >= 0 and len(decoded) > max_decode:
raise ValueError("max gzipped payload length exceeded")
return decoded
##
# Return a decoded file-like object for the gzip encoding
# as described in RFC 1952.
#
# @param response A stream supporting a read() method
# @return a file-like object that the decoded data can be read() from
class GzipDecodedResponse(gzip.GzipFile if gzip else object):
"""a file-like object to decode a response encoded with the gzip
method, as described in RFC 1952.
"""
def __init__(self, response):
#response doesn't support tell() and read(), required by
#GzipFile
if not gzip:
raise NotImplementedError
self.stringio = StringIO.StringIO(response.read())
gzip.GzipFile.__init__(self, mode="rb", fileobj=self.stringio)
def close(self):
try:
gzip.GzipFile.close(self)
finally:
self.stringio.close()
# --------------------------------------------------------------------
# request dispatcher
class _Method:
# some magic to bind an XML-RPC method to an RPC server.
# supports "nested" methods (e.g. examples.getStateName)
def __init__(self, send, name):
self.__send = send
self.__name = name
def __getattr__(self, name):
return _Method(self.__send, "%s.%s" % (self.__name, name))
def __call__(self, *args):
return self.__send(self.__name, args)
##
# Standard transport class for XML-RPC over HTTP.
# <p>
# You can create custom transports by subclassing this method, and
# overriding selected methods.
class Transport:
"""Handles an HTTP transaction to an XML-RPC server."""
# client identifier (may be overridden)
user_agent = "xmlrpclib.py/%s (by www.pythonware.com)" % __version__
#if true, we'll request gzip encoding
accept_gzip_encoding = True
# if positive, encode request using gzip if it exceeds this threshold
# note that many server will get confused, so only use it if you know
# that they can decode such a request
encode_threshold = None #None = don't encode
def __init__(self, use_datetime=0):
self._use_datetime = use_datetime
self._connection = (None, None)
self._extra_headers = []
##
# Send a complete request, and parse the response.
# Retry request if a cached connection has disconnected.
#
# @param host Target host.
# @param handler Target PRC handler.
# @param request_body XML-RPC request body.
# @param verbose Debugging flag.
# @return Parsed response.
def request(self, host, handler, request_body, verbose=0):
#retry request once if cached connection has gone cold
for i in (0, 1):
try:
return self.single_request(host, handler, request_body, verbose)
except socket.error as e:
if i or e.errno not in (errno.ECONNRESET, errno.ECONNABORTED, errno.EPIPE):
raise
except httplib.BadStatusLine: #close after we sent request
if i:
raise
##
# Send a complete request, and parse the response.
#
# @param host Target host.
# @param handler Target PRC handler.
# @param request_body XML-RPC request body.
# @param verbose Debugging flag.
# @return Parsed response.
def single_request(self, host, handler, request_body, verbose=0):
# issue XML-RPC request
h = self.make_connection(host)
if verbose:
h.set_debuglevel(1)
try:
self.send_request(h, handler, request_body)
self.send_host(h, host)
self.send_user_agent(h)
self.send_content(h, request_body)
response = h.getresponse(buffering=True)
if response.status == 200:
self.verbose = verbose
return self.parse_response(response)
except Fault:
raise
except Exception:
# All unexpected errors leave connection in
# a strange state, so we clear it.
self.close()
raise
#discard any response data and raise exception
if (response.getheader("content-length", 0)):
response.read()
raise ProtocolError(
host + handler,
response.status, response.reason,
response.msg,
)
##
# Create parser.
#
# @return A 2-tuple containing a parser and a unmarshaller.
def getparser(self):
# get parser and unmarshaller
return getparser(use_datetime=self._use_datetime)
##
# Get authorization info from host parameter
# Host may be a string, or a (host, x509-dict) tuple; if a string,
# it is checked for a "user:pw@host" format, and a "Basic
# Authentication" header is added if appropriate.
#
# @param host Host descriptor (URL or (URL, x509 info) tuple).
# @return A 3-tuple containing (actual host, extra headers,
# x509 info). The header and x509 fields may be None.
def get_host_info(self, host):
x509 = {}
if isinstance(host, TupleType):
host, x509 = host
import urllib
auth, host = urllib.splituser(host)
if auth:
import base64
auth = base64.encodestring(urllib.unquote(auth))
auth = string.join(string.split(auth), "") # get rid of whitespace
extra_headers = [
("Authorization", "Basic " + auth)
]
else:
extra_headers = None
return host, extra_headers, x509
##
# Connect to server.
#
# @param host Target host.
# @return A connection handle.
def make_connection(self, host):
#return an existing connection if possible. This allows
#HTTP/1.1 keep-alive.
if self._connection and host == self._connection[0]:
return self._connection[1]
# create a HTTP connection object from a host descriptor
chost, self._extra_headers, x509 = self.get_host_info(host)
#store the host argument along with the connection object
self._connection = host, httplib.HTTPConnection(chost)
return self._connection[1]
##
# Clear any cached connection object.
# Used in the event of socket errors.
#
def close(self):
host, connection = self._connection
if connection:
self._connection = (None, None)
connection.close()
##
# Send request header.
#
# @param connection Connection handle.
# @param handler Target RPC handler.
# @param request_body XML-RPC body.
def send_request(self, connection, handler, request_body):
if (self.accept_gzip_encoding and gzip):
connection.putrequest("POST", handler, skip_accept_encoding=True)
connection.putheader("Accept-Encoding", "gzip")
else:
connection.putrequest("POST", handler)
##
# Send host name.
#
# @param connection Connection handle.
# @param host Host name.
#
# Note: This function doesn't actually add the "Host"
# header anymore, it is done as part of the connection.putrequest() in
# send_request() above.
def send_host(self, connection, host):
extra_headers = self._extra_headers
if extra_headers:
if isinstance(extra_headers, DictType):
extra_headers = extra_headers.items()
for key, value in extra_headers:
connection.putheader(key, value)
##
# Send user-agent identifier.
#
# @param connection Connection handle.
def send_user_agent(self, connection):
connection.putheader("User-Agent", self.user_agent)
##
# Send request body.
#
# @param connection Connection handle.
# @param request_body XML-RPC request body.
def send_content(self, connection, request_body):
connection.putheader("Content-Type", "text/xml")
#optionally encode the request
if (self.encode_threshold is not None and
self.encode_threshold < len(request_body) and
gzip):
connection.putheader("Content-Encoding", "gzip")
request_body = gzip_encode(request_body)
connection.putheader("Content-Length", str(len(request_body)))
connection.endheaders(request_body)
##
# Parse response.
#
# @param file Stream.
# @return Response tuple and target method.
def parse_response(self, response):
# read response data from httpresponse, and parse it
# Check for new http response object, else it is a file object
if hasattr(response,'getheader'):
if response.getheader("Content-Encoding", "") == "gzip":
stream = GzipDecodedResponse(response)
else:
stream = response
else:
stream = response
p, u = self.getparser()
while 1:
data = stream.read(1024)
if not data:
break
if self.verbose:
print("body: %s" % repr(data))
p.feed(data)
if stream is not response:
stream.close()
p.close()
return u.close()
##
# Standard transport class for XML-RPC over HTTPS.
class SafeTransport(Transport):
"""Handles an HTTPS transaction to an XML-RPC server."""
def __init__(self, use_datetime=0, context=None):
Transport.__init__(self, use_datetime=use_datetime)
self.context = context
# FIXME: mostly untested
def make_connection(self, host):
if self._connection and host == self._connection[0]:
return self._connection[1]
# create a HTTPS connection object from a host descriptor
# host may be a string, or a (host, x509-dict) tuple
try:
HTTPS = httplib.HTTPSConnection
except AttributeError:
raise NotImplementedError(
"your version of httplib doesn't support HTTPS"
)
else:
chost, self._extra_headers, x509 = self.get_host_info(host)
self._connection = host, HTTPS(chost, None, context=self.context, **(x509 or {}))
return self._connection[1]
##
# Standard server proxy. This class establishes a virtual connection
# to an XML-RPC server.
# <p>
# This class is available as ServerProxy and Server. New code should
# use ServerProxy, to avoid confusion.
#
# @def ServerProxy(uri, **options)
# @param uri The connection point on the server.
# @keyparam transport A transport factory, compatible with the
# standard transport class.
# @keyparam encoding The default encoding used for 8-bit strings
# (default is UTF-8).
# @keyparam verbose Use a true value to enable debugging output.
# (printed to standard output).
# @keyparam utf8_encoding Way to encode UTF-8 characters. Use
# 'standard' to conform to XML standards (ejabberd > 14.07),
# 'php' to encode like PHP (ejabberd <= 14.07)
# 'python2' to behave in the same way as Python2
# Defaults to 'standard'.
# @see Transport
class ServerProxy:
"""uri [,options] -> a logical connection to an XML-RPC server
uri is the connection point on the server, given as
scheme://host/target.
The standard implementation always supports the "http" scheme. If
SSL socket support is available (Python 2.0), it also supports
"https".
If the target part and the slash preceding it are both omitted,
"/RPC2" is assumed.
The following options can be given as keyword arguments:
transport: a transport factory
encoding: the request encoding (default is UTF-8)
utf8_encoding: Way to encode UTF-8 characters. May currently be either
'standard' or 'php'.
All 8-bit strings passed to the server proxy are assumed to use
the given encoding.
"""
# xmpp-backends: Add the utf8_encoding parameter
def __init__(self, uri, transport=None, encoding=None, verbose=0,
allow_none=0, use_datetime=0, context=None, utf8_encoding='standard'):
# establish a "logical" server connection
if isinstance(uri, unicode):
uri = uri.encode('ISO-8859-1')
# get the url
import urllib
type, uri = urllib.splittype(uri)
if type not in ("http", "https"):
raise IOError("unsupported XML-RPC protocol")
self.__host, self.__handler = urllib.splithost(uri)
if not self.__handler:
self.__handler = "/RPC2"
if transport is None:
if type == "https":
transport = SafeTransport(use_datetime=use_datetime, context=context)
else:
transport = Transport(use_datetime=use_datetime)
self.__transport = transport
self.__encoding = encoding
self.__verbose = verbose
self.__allow_none = allow_none
# xmpp-backends: Set the utf8_encoding parameter
self.__utf8_encoding = utf8_encoding
def __close(self):
self.__transport.close()
def __request(self, methodname, params):
# call a method on the remote server
request = dumps(params, methodname, encoding=self.__encoding,
allow_none=self.__allow_none)
response = self.__transport.request(
self.__host,
self.__handler,
request,
verbose=self.__verbose
)
if len(response) == 1:
response = response[0]
return response
def __repr__(self):
return (
"<ServerProxy for %s%s>" %
(self.__host, self.__handler)
)
__str__ = __repr__
def __getattr__(self, name):
# magic method dispatcher
return _Method(self.__request, name)
# note: to call a remote object with an non-standard name, use
# result getattr(server, "strange-python-name")(args)
def __call__(self, attr):
"""A workaround to get special attributes on the ServerProxy
without interfering with the magic __getattr__
"""
if attr == "close":
return self.__close
elif attr == "transport":
return self.__transport
raise AttributeError("Attribute %r not found" % (attr,))
# compatibility
Server = ServerProxy
# --------------------------------------------------------------------
# test code
if __name__ == "__main__":
server = ServerProxy("http://localhost:8000")
print(server)
multi = MultiCall(server)
multi.pow(2, 9)
multi.add(5, 1)
multi.add(24, 11)
try:
for response in multi():
print(response)
except Error as v:
print("ERROR: %s" % v)
|
mathiasertl/xmpp-backends
|
xmpp_backends/xmlrpclib.py
|
gzip_encode
|
python
|
def gzip_encode(data):
if not gzip:
raise NotImplementedError
f = StringIO.StringIO()
gzf = gzip.GzipFile(mode="wb", fileobj=f, compresslevel=1)
gzf.write(data)
gzf.close()
encoded = f.getvalue()
f.close()
return encoded
|
data -> gzip encoded data
Encode data using the gzip content encoding as described in RFC 1952
|
train
|
https://github.com/mathiasertl/xmpp-backends/blob/214ef0664dbf90fa300c2483b9b3416559e5d171/xmpp_backends/xmlrpclib.py#L1240-L1253
| null |
# -*- coding: utf-8 -*-
#
# XML-RPC CLIENT LIBRARY
# $Id$
#
# This is a copy of the xmlrpclib library shipping with Python 2.7.
# It is modified to encode UTF-8 characters in several different ways.
#
# The problem is that this library does not encode UTF-8 correctly and PHP's
# library doesn't encode them correctly either - but wrong in a differnt way.
# ejabberd <= 14.07 expects unicode in the way PHP encodes them and ejabberd
# versions after that expect unicode to be encoded according to XML standards.
#
# Here is an overview of what different encoding options there are,
# demonstrated by the example letter 'ä'. Use:
# https://en.wikipedia.org/wiki/%C3%84#Computer_encoding
# as reference next to the following examples:
#
# XML standard = what lxml produces and ejabberd > 14.07 accepts:
#
# >>> from lxml import etree
# >>> t = etree.Element('test')
# >>> t.text = u'ä' # note: 'ä' is not accepted
# >>> etree.tostring(t)
# <test>ä</test>
#
# What PHP produces and ejabberd <= 14.07 accepts:
#
# $ php -r 'print xmlrpc_encode("ä");'
# ...
# <string>ä</string>
# ...
#
# No encoding - Conforms to standards and is what Python3 produces
# (unknown if ejabberd accepts it)
#
# >>> import xmlrpclib
# >>> xmlrpclib.escape('ä')
# 'ä'
#
# What xmlrpclib in Python2 produces:
# >>> import xmlrpclib
# >>> xmlrpclib.escape('ä')
# '\xc3\xa4'
# >>> xmlrpclib.escape(u'ä') # unicode is not supported!
# ...
# TypeError: encode() argument 1 must be string, not None
#
# This library differs from the version that ships with Python 2.7.10 in that
# it adds a `utf8_encoding` parameter to support all three different encoding
# options. All changes are marked with a line starting with:
#
# xmpp-backends: ...
#
#
# an XML-RPC client interface for Python.
#
# the marshalling and response parser code can also be used to
# implement XML-RPC servers.
#
# Notes:
# this version is designed to work with Python 2.1 or newer.
#
# History:
# 1999-01-14 fl Created
# 1999-01-15 fl Changed dateTime to use localtime
# 1999-01-16 fl Added Binary/base64 element, default to RPC2 service
# 1999-01-19 fl Fixed array data element (from Skip Montanaro)
# 1999-01-21 fl Fixed dateTime constructor, etc.
# 1999-02-02 fl Added fault handling, handle empty sequences, etc.
# 1999-02-10 fl Fixed problem with empty responses (from Skip Montanaro)
# 1999-06-20 fl Speed improvements, pluggable parsers/transports (0.9.8)
# 2000-11-28 fl Changed boolean to check the truth value of its argument
# 2001-02-24 fl Added encoding/Unicode/SafeTransport patches
# 2001-02-26 fl Added compare support to wrappers (0.9.9/1.0b1)
# 2001-03-28 fl Make sure response tuple is a singleton
# 2001-03-29 fl Don't require empty params element (from Nicholas Riley)
# 2001-06-10 fl Folded in _xmlrpclib accelerator support (1.0b2)
# 2001-08-20 fl Base xmlrpclib.Error on built-in Exception (from Paul Prescod)
# 2001-09-03 fl Allow Transport subclass to override getparser
# 2001-09-10 fl Lazy import of urllib, cgi, xmllib (20x import speedup)
# 2001-10-01 fl Remove containers from memo cache when done with them
# 2001-10-01 fl Use faster escape method (80% dumps speedup)
# 2001-10-02 fl More dumps microtuning
# 2001-10-04 fl Make sure import expat gets a parser (from Guido van Rossum)
# 2001-10-10 sm Allow long ints to be passed as ints if they don't overflow
# 2001-10-17 sm Test for int and long overflow (allows use on 64-bit systems)
# 2001-11-12 fl Use repr() to marshal doubles (from Paul Felix)
# 2002-03-17 fl Avoid buffered read when possible (from James Rucker)
# 2002-04-07 fl Added pythondoc comments
# 2002-04-16 fl Added __str__ methods to datetime/binary wrappers
# 2002-05-15 fl Added error constants (from Andrew Kuchling)
# 2002-06-27 fl Merged with Python CVS version
# 2002-10-22 fl Added basic authentication (based on code from Phillip Eby)
# 2003-01-22 sm Add support for the bool type
# 2003-02-27 gvr Remove apply calls
# 2003-04-24 sm Use cStringIO if available
# 2003-04-25 ak Add support for nil
# 2003-06-15 gn Add support for time.struct_time
# 2003-07-12 gp Correct marshalling of Faults
# 2003-10-31 mvl Add multicall support
# 2004-08-20 mvl Bump minimum supported Python version to 2.1
# 2014-12-02 ch/doko Add workaround for gzip bomb vulnerability
#
# Copyright (c) 1999-2002 by Secret Labs AB.
# Copyright (c) 1999-2002 by Fredrik Lundh.
#
# info@pythonware.com
# http://www.pythonware.com
#
# --------------------------------------------------------------------
# The XML-RPC client interface is
#
# Copyright (c) 1999-2002 by Secret Labs AB
# Copyright (c) 1999-2002 by Fredrik Lundh
#
# By obtaining, using, and/or copying this software and/or its
# associated documentation, you agree that you have read, understood,
# and will comply with the following terms and conditions:
#
# Permission to use, copy, modify, and distribute this software and
# its associated documentation for any purpose and without fee is
# hereby granted, provided that the above copyright notice appears in
# all copies, and that both that copyright notice and this permission
# notice appear in supporting documentation, and that the name of
# Secret Labs AB or the author not be used in advertising or publicity
# pertaining to distribution of the software without specific, written
# prior permission.
#
# SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
# TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANT-
# ABILITY AND FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR
# BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY
# DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
# WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
# ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
# OF THIS SOFTWARE.
# --------------------------------------------------------------------
#
# things to look into some day:
# TODO: sort out True/False/boolean issues for Python 2.3
"""
An XML-RPC client interface for Python.
The marshalling and response parser code can also be used to
implement XML-RPC servers.
Exported exceptions:
Error Base class for client errors
ProtocolError Indicates an HTTP protocol error
ResponseError Indicates a broken response package
Fault Indicates an XML-RPC fault package
Exported classes:
ServerProxy Represents a logical connection to an XML-RPC server
MultiCall Executor of boxcared xmlrpc requests
Boolean boolean wrapper to generate a "boolean" XML-RPC value
DateTime dateTime wrapper for an ISO 8601 string or time tuple or
localtime integer value to generate a "dateTime.iso8601"
XML-RPC value
Binary binary data wrapper
SlowParser Slow but safe standard parser (based on xmllib)
Marshaller Generate an XML-RPC params chunk from a Python data structure
Unmarshaller Unmarshal an XML-RPC response from incoming XML event message
Transport Handles an HTTP transaction to an XML-RPC server
SafeTransport Handles an HTTPS transaction to an XML-RPC server
Exported constants:
True
False
Exported functions:
boolean Convert any Python value to an XML-RPC boolean
getparser Create instance of the fastest available parser & attach
to an unmarshalling object
dumps Convert an argument tuple or a Fault instance to an XML-RPC
request (or response, if the methodresponse option is used).
loads Convert an XML-RPC packet to unmarshalled data plus a method
name (None if not present).
"""
import re, string, time, operator
# xmpp-backends: Do not use wildcard import to improve syntax checkers
from types import (TupleType, StringType, InstanceType, NoneType, IntType,
LongType, FloatType, ListType, DictType, UnicodeType)
import socket
import errno
import httplib
try:
import gzip
except ImportError:
gzip = None #python can be built without zlib/gzip support
# --------------------------------------------------------------------
# Internal stuff
try:
unicode
except NameError:
unicode = None # unicode support not available
try:
import datetime
except ImportError:
datetime = None
try:
_bool_is_builtin = False.__class__.__name__ == "bool"
except NameError:
_bool_is_builtin = 0
def _decode(data, encoding, is8bit=re.compile("[\x80-\xff]").search):
# decode non-ascii string (if possible)
if unicode and encoding and is8bit(data):
data = unicode(data, encoding)
return data
# xmpp-backends: Add the utf8_encoding parameter
def escape(s, replace=string.replace, utf8_encoding='standard'):
s = replace(s, "&", "&")
s = replace(s, "<", "<")
s = replace(s, ">", ">")
if utf8_encoding == 'python2':
return s
elif utf8_encoding == 'none':
if isinstance(s, unicode):
return s
return s.decode('utf-8')
encoded = ''
# xmpp-backends: Handle the utf8_encoding parameter
if utf8_encoding == 'php':
if isinstance(s, unicode): # py2 and unicode
_encode = lambda char: ''.join(['&#%s;' % ord(b) for b in char.encode('utf-8')])
else: # py2 str
_encode = lambda char: ''.join(['&#%s;' % ord(b) for b in char])
elif utf8_encoding == 'standard':
if isinstance(s, str):
s = s.decode('utf-8')
_encode = lambda char: '&#%s;' % ord(char)
else:
raise AttributeError("Unknown utf8_encoding '%s'" % utf8_encoding)
for char in s:
if ord(char) >= 128:
encoded += _encode(char)
else:
encoded += char
return encoded
if unicode:
def _stringify(string):
# convert to 7-bit ascii if possible
try:
return string.encode("ascii")
except UnicodeError:
return string
else:
def _stringify(string):
return string
__version__ = "1.0.1"
# xmlrpc integer limits
MAXINT = 2 **31-1
MININT = -2 **31
# --------------------------------------------------------------------
# Error constants (from Dan Libby's specification at
# http://xmlrpc-epi.sourceforge.net/specs/rfc.fault_codes.php)
# Ranges of errors
PARSE_ERROR = -32700
SERVER_ERROR = -32600
APPLICATION_ERROR = -32500
SYSTEM_ERROR = -32400
TRANSPORT_ERROR = -32300
# Specific errors
NOT_WELLFORMED_ERROR = -32700
UNSUPPORTED_ENCODING = -32701
INVALID_ENCODING_CHAR = -32702
INVALID_XMLRPC = -32600
METHOD_NOT_FOUND = -32601
INVALID_METHOD_PARAMS = -32602
INTERNAL_ERROR = -32603
# --------------------------------------------------------------------
# Exceptions
##
# Base class for all kinds of client-side errors.
class Error(Exception):
"""Base class for client errors."""
def __str__(self):
return repr(self)
##
# Indicates an HTTP-level protocol error. This is raised by the HTTP
# transport layer, if the server returns an error code other than 200
# (OK).
#
# @param url The target URL.
# @param errcode The HTTP error code.
# @param errmsg The HTTP error message.
# @param headers The HTTP header dictionary.
class ProtocolError(Error):
"""Indicates an HTTP protocol error."""
def __init__(self, url, errcode, errmsg, headers):
Error.__init__(self)
self.url = url
self.errcode = errcode
self.errmsg = errmsg
self.headers = headers
def __repr__(self):
return (
"<ProtocolError for %s: %s %s>" %
(self.url, self.errcode, self.errmsg)
)
##
# Indicates a broken XML-RPC response package. This exception is
# raised by the unmarshalling layer, if the XML-RPC response is
# malformed.
class ResponseError(Error):
"""Indicates a broken response package."""
pass
##
# Indicates an XML-RPC fault response package. This exception is
# raised by the unmarshalling layer, if the XML-RPC response contains
# a fault string. This exception can also used as a class, to
# generate a fault XML-RPC message.
#
# @param faultCode The XML-RPC fault code.
# @param faultString The XML-RPC fault string.
class Fault(Error):
"""Indicates an XML-RPC fault package."""
def __init__(self, faultCode, faultString, **extra):
Error.__init__(self)
self.faultCode = faultCode
self.faultString = faultString
def __repr__(self):
return (
"<Fault %s: %s>" %
(self.faultCode, repr(self.faultString))
)
# --------------------------------------------------------------------
# Special values
##
# Wrapper for XML-RPC boolean values. Use the xmlrpclib.True and
# xmlrpclib.False constants, or the xmlrpclib.boolean() function, to
# generate boolean XML-RPC values.
#
# @param value A boolean value. Any true value is interpreted as True,
# all other values are interpreted as False.
from sys import modules
mod_dict = modules[__name__].__dict__
if _bool_is_builtin:
boolean = Boolean = bool
# to avoid breaking code which references xmlrpclib.{True,False}
mod_dict['True'] = True
mod_dict['False'] = False
else:
class Boolean:
"""Boolean-value wrapper.
Use True or False to generate a "boolean" XML-RPC value.
"""
def __init__(self, value = 0):
self.value = operator.truth(value)
def encode(self, out):
out.write("<value><boolean>%d</boolean></value>\n" % self.value)
def __cmp__(self, other):
if isinstance(other, Boolean):
other = other.value
return cmp(self.value, other)
def __repr__(self):
if self.value:
return "<Boolean True at %x>" % id(self)
else:
return "<Boolean False at %x>" % id(self)
def __int__(self):
return self.value
def __nonzero__(self):
return self.value
mod_dict['True'] = Boolean(1)
mod_dict['False'] = Boolean(0)
##
# Map true or false value to XML-RPC boolean values.
#
# @def boolean(value)
# @param value A boolean value. Any true value is mapped to True,
# all other values are mapped to False.
# @return xmlrpclib.True or xmlrpclib.False.
# @see Boolean
# @see True
# @see False
def boolean(value, _truefalse=(False, True)):
"""Convert any Python value to XML-RPC 'boolean'."""
return _truefalse[operator.truth(value)]
del modules, mod_dict
##
# Wrapper for XML-RPC DateTime values. This converts a time value to
# the format used by XML-RPC.
# <p>
# The value can be given as a string in the format
# "yyyymmddThh:mm:ss", as a 9-item time tuple (as returned by
# time.localtime()), or an integer value (as returned by time.time()).
# The wrapper uses time.localtime() to convert an integer to a time
# tuple.
#
# @param value The time, given as an ISO 8601 string, a time
# tuple, or a integer time value.
def _strftime(value):
if datetime:
if isinstance(value, datetime.datetime):
return "%04d%02d%02dT%02d:%02d:%02d" % (
value.year, value.month, value.day,
value.hour, value.minute, value.second)
if not isinstance(value, (TupleType, time.struct_time)):
if value == 0:
value = time.time()
value = time.localtime(value)
return "%04d%02d%02dT%02d:%02d:%02d" % value[:6]
class DateTime:
"""DateTime wrapper for an ISO 8601 string or time tuple or
localtime integer value to generate 'dateTime.iso8601' XML-RPC
value.
"""
def __init__(self, value=0):
if isinstance(value, StringType):
self.value = value
else:
self.value = _strftime(value)
def make_comparable(self, other):
if isinstance(other, DateTime):
s = self.value
o = other.value
elif datetime and isinstance(other, datetime.datetime):
s = self.value
o = other.strftime("%Y%m%dT%H:%M:%S")
elif isinstance(other, (str, unicode)):
s = self.value
o = other
elif hasattr(other, "timetuple"):
s = self.timetuple()
o = other.timetuple()
else:
otype = (hasattr(other, "__class__")
and other.__class__.__name__
or type(other))
raise TypeError("Can't compare %s and %s" %
(self.__class__.__name__, otype))
return s, o
def __lt__(self, other):
s, o = self.make_comparable(other)
return s < o
def __le__(self, other):
s, o = self.make_comparable(other)
return s <= o
def __gt__(self, other):
s, o = self.make_comparable(other)
return s > o
def __ge__(self, other):
s, o = self.make_comparable(other)
return s >= o
def __eq__(self, other):
s, o = self.make_comparable(other)
return s == o
def __ne__(self, other):
s, o = self.make_comparable(other)
return s != o
def timetuple(self):
return time.strptime(self.value, "%Y%m%dT%H:%M:%S")
def __cmp__(self, other):
s, o = self.make_comparable(other)
return cmp(s, o)
##
# Get date/time value.
#
# @return Date/time value, as an ISO 8601 string.
def __str__(self):
return self.value
def __repr__(self):
return "<DateTime %s at %x>" % (repr(self.value), id(self))
def decode(self, data):
data = str(data)
self.value = string.strip(data)
def encode(self, out):
out.write("<value><dateTime.iso8601>")
out.write(self.value)
out.write("</dateTime.iso8601></value>\n")
def _datetime(data):
# decode xml element contents into a DateTime structure.
value = DateTime()
value.decode(data)
return value
def _datetime_type(data):
t = time.strptime(data, "%Y%m%dT%H:%M:%S")
return datetime.datetime(*tuple(t)[:6])
##
# Wrapper for binary data. This can be used to transport any kind
# of binary data over XML-RPC, using BASE64 encoding.
#
# @param data An 8-bit string containing arbitrary data.
import base64
try:
import cStringIO as StringIO
except ImportError:
import StringIO
class Binary:
"""Wrapper for binary data."""
def __init__(self, data=None):
self.data = data
##
# Get buffer contents.
#
# @return Buffer contents, as an 8-bit string.
def __str__(self):
return self.data or ""
def __cmp__(self, other):
if isinstance(other, Binary):
other = other.data
return cmp(self.data, other)
def decode(self, data):
self.data = base64.decodestring(data)
def encode(self, out):
out.write("<value><base64>\n")
base64.encode(StringIO.StringIO(self.data), out)
out.write("</base64></value>\n")
def _binary(data):
# decode xml element contents into a Binary structure
value = Binary()
value.decode(data)
return value
WRAPPERS = (DateTime, Binary)
if not _bool_is_builtin:
WRAPPERS = WRAPPERS + (Boolean,)
# --------------------------------------------------------------------
# XML parsers
try:
# optional xmlrpclib accelerator
import _xmlrpclib
FastParser = _xmlrpclib.Parser
FastUnmarshaller = _xmlrpclib.Unmarshaller
except (AttributeError, ImportError):
FastParser = FastUnmarshaller = None
try:
import _xmlrpclib
FastMarshaller = _xmlrpclib.Marshaller
except (AttributeError, ImportError):
FastMarshaller = None
try:
from xml.parsers import expat
if not hasattr(expat, "ParserCreate"):
raise ImportError
except ImportError:
ExpatParser = None # expat not available
else:
class ExpatParser:
# fast expat parser for Python 2.0 and later.
def __init__(self, target):
self._parser = parser = expat.ParserCreate(None, None)
self._target = target
parser.StartElementHandler = target.start
parser.EndElementHandler = target.end
parser.CharacterDataHandler = target.data
encoding = None
if not parser.returns_unicode:
encoding = "utf-8"
target.xml(encoding, None)
def feed(self, data):
self._parser.Parse(data, 0)
def close(self):
try:
parser = self._parser
except AttributeError:
pass
else:
del self._target, self._parser # get rid of circular references
parser.Parse("", 1) # end of data
class SlowParser:
"""Default XML parser (based on xmllib.XMLParser)."""
# this is the slowest parser.
def __init__(self, target):
import xmllib # lazy subclassing (!)
if xmllib.XMLParser not in SlowParser.__bases__:
SlowParser.__bases__ = (xmllib.XMLParser,)
self.handle_xml = target.xml
self.unknown_starttag = target.start
self.handle_data = target.data
self.handle_cdata = target.data
self.unknown_endtag = target.end
try:
xmllib.XMLParser.__init__(self, accept_utf8=1)
except TypeError:
xmllib.XMLParser.__init__(self) # pre-2.0
# --------------------------------------------------------------------
# XML-RPC marshalling and unmarshalling code
##
# XML-RPC marshaller.
#
# @param encoding Default encoding for 8-bit strings. The default
# value is None (interpreted as UTF-8).
# @see dumps
class Marshaller:
"""Generate an XML-RPC params chunk from a Python data structure.
Create a Marshaller instance for each set of parameters, and use
the "dumps" method to convert your data (represented as a tuple)
to an XML-RPC params chunk. To write a fault response, pass a
Fault instance instead. You may prefer to use the "dumps" module
function for this purpose.
"""
# by the way, if you don't understand what's going on in here,
# that's perfectly ok.
# xmpp-backends: Add the utf8_encoding parameter
def __init__(self, encoding=None, allow_none=0, utf8_encoding='standard'):
self.memo = {}
self.data = None
self.encoding = encoding
self.allow_none = allow_none
# xmpp-backends: Set the self.utf8_encoding property
self.utf8_encoding = utf8_encoding
dispatch = {}
def dumps(self, values):
out = []
write = out.append
dump = self.__dump
if isinstance(values, Fault):
# fault instance
write("<fault>\n")
dump({'faultCode': values.faultCode,
'faultString': values.faultString},
write)
write("</fault>\n")
else:
# parameter block
# FIXME: the xml-rpc specification allows us to leave out
# the entire <params> block if there are no parameters.
# however, changing this may break older code (including
# old versions of xmlrpclib.py), so this is better left as
# is for now. See @XMLRPC3 for more information. /F
write("<params>\n")
for v in values:
write("<param>\n")
dump(v, write)
write("</param>\n")
write("</params>\n")
result = string.join(out, "")
return result
def __dump(self, value, write):
try:
f = self.dispatch[type(value)]
except KeyError:
# check if this object can be marshalled as a structure
try:
value.__dict__
except:
raise TypeError("cannot marshal %s objects" % type(value))
# check if this class is a sub-class of a basic type,
# because we don't know how to marshal these types
# (e.g. a string sub-class)
for type_ in type(value).__mro__:
if type_ in self.dispatch.keys():
raise TypeError("cannot marshal %s objects" % type(value))
f = self.dispatch[InstanceType]
f(self, value, write)
def dump_nil (self, value, write):
if not self.allow_none:
raise TypeError("cannot marshal None unless allow_none is enabled")
write("<value><nil/></value>")
dispatch[NoneType] = dump_nil
def dump_int(self, value, write):
# in case ints are > 32 bits
if value > MAXINT or value < MININT:
raise OverflowError("int exceeds XML-RPC limits")
write("<value><int>")
write(str(value))
write("</int></value>\n")
dispatch[IntType] = dump_int
if _bool_is_builtin:
def dump_bool(self, value, write):
write("<value><boolean>")
write(value and "1" or "0")
write("</boolean></value>\n")
dispatch[bool] = dump_bool
def dump_long(self, value, write):
if value > MAXINT or value < MININT:
raise OverflowError("long int exceeds XML-RPC limits")
write("<value><int>")
write(str(int(value)))
write("</int></value>\n")
dispatch[LongType] = dump_long
def dump_double(self, value, write):
write("<value><double>")
write(repr(value))
write("</double></value>\n")
dispatch[FloatType] = dump_double
def dump_string(self, value, write, escape=escape):
write("<value><string>")
# xmpp-backends: Pass utf8_encoding parameter
write(escape(value, utf8_encoding=self.utf8_encoding))
write("</string></value>\n")
dispatch[StringType] = dump_string
if unicode:
def dump_unicode(self, value, write, escape=escape):
write("<value><string>")
# xmpp-backends: Pass utf8_encoding parameter
write(escape(value, utf8_encoding=self.utf8_encoding))
write("</string></value>\n")
dispatch[UnicodeType] = dump_unicode
def dump_array(self, value, write):
i = id(value)
if i in self.memo:
raise TypeError("cannot marshal recursive sequences")
self.memo[i] = None
dump = self.__dump
write("<value><array><data>\n")
for v in value:
dump(v, write)
write("</data></array></value>\n")
del self.memo[i]
dispatch[TupleType] = dump_array
dispatch[ListType] = dump_array
def dump_struct(self, value, write, escape=escape):
i = id(value)
if i in self.memo:
raise TypeError("cannot marshal recursive dictionaries")
self.memo[i] = None
dump = self.__dump
write("<value><struct>\n")
for k, v in value.items():
write("<member>\n")
if type(k) is not StringType:
if unicode and type(k) is UnicodeType:
k = k.encode(self.encoding)
else:
raise TypeError("dictionary key must be string")
write("<name>%s</name>\n" % escape(k))
dump(v, write)
write("</member>\n")
write("</struct></value>\n")
del self.memo[i]
dispatch[DictType] = dump_struct
if datetime:
def dump_datetime(self, value, write):
write("<value><dateTime.iso8601>")
write(_strftime(value))
write("</dateTime.iso8601></value>\n")
dispatch[datetime.datetime] = dump_datetime
def dump_instance(self, value, write):
# check for special wrappers
if value.__class__ in WRAPPERS:
self.write = write
value.encode(self)
del self.write
else:
# store instance attributes as a struct (really?)
self.dump_struct(value.__dict__, write)
dispatch[InstanceType] = dump_instance
##
# XML-RPC unmarshaller.
#
# @see loads
class Unmarshaller:
"""Unmarshal an XML-RPC response, based on incoming XML event
messages (start, data, end). Call close() to get the resulting
data structure.
Note that this reader is fairly tolerant, and gladly accepts bogus
XML-RPC data without complaining (but not bogus XML).
"""
# and again, if you don't understand what's going on in here,
# that's perfectly ok.
def __init__(self, use_datetime=0):
self._type = None
self._stack = []
self._marks = []
self._data = []
self._methodname = None
self._encoding = "utf-8"
self.append = self._stack.append
self._use_datetime = use_datetime
if use_datetime and not datetime:
raise ValueError("the datetime module is not available")
def close(self):
# return response tuple and target method
if self._type is None or self._marks:
raise ResponseError()
if self._type == "fault":
raise Fault(**self._stack[0])
return tuple(self._stack)
def getmethodname(self):
return self._methodname
#
# event handlers
def xml(self, encoding, standalone):
self._encoding = encoding
# FIXME: assert standalone == 1 ???
def start(self, tag, attrs):
# prepare to handle this element
if tag == "array" or tag == "struct":
self._marks.append(len(self._stack))
self._data = []
self._value = (tag == "value")
def data(self, text):
self._data.append(text)
def end(self, tag, join=string.join):
# call the appropriate end tag handler
try:
f = self.dispatch[tag]
except KeyError:
pass # unknown tag ?
else:
return f(self, join(self._data, ""))
#
# accelerator support
def end_dispatch(self, tag, data):
# dispatch data
try:
f = self.dispatch[tag]
except KeyError:
pass # unknown tag ?
else:
return f(self, data)
#
# element decoders
dispatch = {}
def end_nil (self, data):
self.append(None)
self._value = 0
dispatch["nil"] = end_nil
def end_boolean(self, data):
if data == "0":
self.append(False)
elif data == "1":
self.append(True)
else:
raise TypeError("bad boolean value")
self._value = 0
dispatch["boolean"] = end_boolean
def end_int(self, data):
self.append(int(data))
self._value = 0
dispatch["i4"] = end_int
dispatch["i8"] = end_int
dispatch["int"] = end_int
def end_double(self, data):
self.append(float(data))
self._value = 0
dispatch["double"] = end_double
def end_string(self, data):
if self._encoding:
data = _decode(data, self._encoding)
self.append(_stringify(data))
self._value = 0
dispatch["string"] = end_string
dispatch["name"] = end_string # struct keys are always strings
def end_array(self, data):
mark = self._marks.pop()
# map arrays to Python lists
self._stack[mark:] = [self._stack[mark:]]
self._value = 0
dispatch["array"] = end_array
def end_struct(self, data):
mark = self._marks.pop()
# map structs to Python dictionaries
dict = {}
items = self._stack[mark:]
for i in range(0, len(items), 2):
dict[_stringify(items[i])] = items[i+1]
self._stack[mark:] = [dict]
self._value = 0
dispatch["struct"] = end_struct
def end_base64(self, data):
value = Binary()
value.decode(data)
self.append(value)
self._value = 0
dispatch["base64"] = end_base64
def end_dateTime(self, data):
value = DateTime()
value.decode(data)
if self._use_datetime:
value = _datetime_type(data)
self.append(value)
dispatch["dateTime.iso8601"] = end_dateTime
def end_value(self, data):
# if we stumble upon a value element with no internal
# elements, treat it as a string element
if self._value:
self.end_string(data)
dispatch["value"] = end_value
def end_params(self, data):
self._type = "params"
dispatch["params"] = end_params
def end_fault(self, data):
self._type = "fault"
dispatch["fault"] = end_fault
def end_methodName(self, data):
if self._encoding:
data = _decode(data, self._encoding)
self._methodname = data
self._type = "methodName" # no params
dispatch["methodName"] = end_methodName
## Multicall support
#
class _MultiCallMethod:
# some lesser magic to store calls made to a MultiCall object
# for batch execution
def __init__(self, call_list, name):
self.__call_list = call_list
self.__name = name
def __getattr__(self, name):
return _MultiCallMethod(self.__call_list, "%s.%s" % (self.__name, name))
def __call__(self, *args):
self.__call_list.append((self.__name, args))
class MultiCallIterator:
"""Iterates over the results of a multicall. Exceptions are
raised in response to xmlrpc faults."""
def __init__(self, results):
self.results = results
def __getitem__(self, i):
item = self.results[i]
if type(item) == type({}):
raise Fault(item['faultCode'], item['faultString'])
elif type(item) == type([]):
return item[0]
else:
raise ValueError("unexpected type in multicall result")
class MultiCall:
"""server -> a object used to boxcar method calls
server should be a ServerProxy object.
Methods can be added to the MultiCall using normal
method call syntax e.g.:
multicall = MultiCall(server_proxy)
multicall.add(2,3)
multicall.get_address("Guido")
To execute the multicall, call the MultiCall object e.g.:
add_result, address = multicall()
"""
def __init__(self, server):
self.__server = server
self.__call_list = []
def __repr__(self):
return "<MultiCall at %x>" % id(self)
__str__ = __repr__
def __getattr__(self, name):
return _MultiCallMethod(self.__call_list, name)
def __call__(self):
marshalled_list = []
for name, args in self.__call_list:
marshalled_list.append({'methodName' : name, 'params' : args})
return MultiCallIterator(self.__server.system.multicall(marshalled_list))
# --------------------------------------------------------------------
# convenience functions
##
# Create a parser object, and connect it to an unmarshalling instance.
# This function picks the fastest available XML parser.
#
# return A (parser, unmarshaller) tuple.
def getparser(use_datetime=0):
"""getparser() -> parser, unmarshaller
Create an instance of the fastest available parser, and attach it
to an unmarshalling object. Return both objects.
"""
if use_datetime and not datetime:
raise ValueError("the datetime module is not available")
if FastParser and FastUnmarshaller:
if use_datetime:
mkdatetime = _datetime_type
else:
mkdatetime = _datetime
target = FastUnmarshaller(True, False, _binary, mkdatetime, Fault)
parser = FastParser(target)
else:
target = Unmarshaller(use_datetime=use_datetime)
if FastParser:
parser = FastParser(target)
elif ExpatParser:
parser = ExpatParser(target)
else:
parser = SlowParser(target)
return parser, target
##
# Convert a Python tuple or a Fault instance to an XML-RPC packet.
#
# @def dumps(params, **options)
# @param params A tuple or Fault instance.
# @keyparam methodname If given, create a methodCall request for
# this method name.
# @keyparam methodresponse If given, create a methodResponse packet.
# If used with a tuple, the tuple must be a singleton (that is,
# it must contain exactly one element).
# @keyparam encoding The packet encoding.
# @return A string containing marshalled data.
# xmpp-backends: Add the utf8_encoding parameter
def dumps(params, methodname=None, methodresponse=None, encoding=None,
allow_none=0, utf8_encoding='standard'):
"""data [,options] -> marshalled data
Convert an argument tuple or a Fault instance to an XML-RPC
request (or response, if the methodresponse option is used).
In addition to the data object, the following options can be given
as keyword arguments:
methodname: the method name for a methodCall packet
methodresponse: true to create a methodResponse packet.
If this option is used with a tuple, the tuple must be
a singleton (i.e. it can contain only one element).
encoding: the packet encoding (default is UTF-8)
All 8-bit strings in the data structure are assumed to use the
packet encoding. Unicode strings are automatically converted,
where necessary.
"""
assert isinstance(params, TupleType) or isinstance(params, Fault),\
"argument must be tuple or Fault instance"
if isinstance(params, Fault):
methodresponse = 1
elif methodresponse and isinstance(params, TupleType):
assert len(params) == 1, "response tuple must be a singleton"
if not encoding:
encoding = "utf-8"
if FastMarshaller:
m = FastMarshaller(encoding)
else:
m = Marshaller(encoding, allow_none)
data = m.dumps(params)
if encoding != "utf-8":
xmlheader = "<?xml version='1.0' encoding='%s'?>\n" % str(encoding)
else:
xmlheader = "<?xml version='1.0'?>\n" # utf-8 is default
# standard XML-RPC wrappings
if methodname:
# a method call
if not isinstance(methodname, StringType):
methodname = methodname.encode(encoding)
data = (
xmlheader,
"<methodCall>\n"
"<methodName>", methodname, "</methodName>\n",
data,
"</methodCall>\n"
)
elif methodresponse:
# a method response, or a fault structure
data = (
xmlheader,
"<methodResponse>\n",
data,
"</methodResponse>\n"
)
else:
return data # return as is
return string.join(data, "")
##
# Convert an XML-RPC packet to a Python object. If the XML-RPC packet
# represents a fault condition, this function raises a Fault exception.
#
# @param data An XML-RPC packet, given as an 8-bit string.
# @return A tuple containing the unpacked data, and the method name
# (None if not present).
# @see Fault
def loads(data, use_datetime=0):
"""data -> unmarshalled data, method name
Convert an XML-RPC packet to unmarshalled data plus a method
name (None if not present).
If the XML-RPC packet represents a fault condition, this function
raises a Fault exception.
"""
p, u = getparser(use_datetime=use_datetime)
p.feed(data)
p.close()
return u.close(), u.getmethodname()
##
# Encode a string using the gzip content encoding such as specified by the
# Content-Encoding: gzip
# in the HTTP header, as described in RFC 1952
#
# @param data the unencoded data
# @return the encoded data
##
# Decode a string using the gzip content encoding such as specified by the
# Content-Encoding: gzip
# in the HTTP header, as described in RFC 1952
#
# @param data The encoded data
# @keyparam max_decode Maximum bytes to decode (20MB default), use negative
# values for unlimited decoding
# @return the unencoded data
# @raises ValueError if data is not correctly coded.
# @raises ValueError if max gzipped payload length exceeded
def gzip_decode(data, max_decode=20971520):
"""gzip encoded data -> unencoded data
Decode data using the gzip content encoding as described in RFC 1952
"""
if not gzip:
raise NotImplementedError
f = StringIO.StringIO(data)
gzf = gzip.GzipFile(mode="rb", fileobj=f)
try:
if max_decode < 0: # no limit
decoded = gzf.read()
else:
decoded = gzf.read(max_decode + 1)
except IOError:
raise ValueError("invalid data")
f.close()
gzf.close()
if max_decode >= 0 and len(decoded) > max_decode:
raise ValueError("max gzipped payload length exceeded")
return decoded
##
# Return a decoded file-like object for the gzip encoding
# as described in RFC 1952.
#
# @param response A stream supporting a read() method
# @return a file-like object that the decoded data can be read() from
class GzipDecodedResponse(gzip.GzipFile if gzip else object):
"""a file-like object to decode a response encoded with the gzip
method, as described in RFC 1952.
"""
def __init__(self, response):
#response doesn't support tell() and read(), required by
#GzipFile
if not gzip:
raise NotImplementedError
self.stringio = StringIO.StringIO(response.read())
gzip.GzipFile.__init__(self, mode="rb", fileobj=self.stringio)
def close(self):
try:
gzip.GzipFile.close(self)
finally:
self.stringio.close()
# --------------------------------------------------------------------
# request dispatcher
class _Method:
# some magic to bind an XML-RPC method to an RPC server.
# supports "nested" methods (e.g. examples.getStateName)
def __init__(self, send, name):
self.__send = send
self.__name = name
def __getattr__(self, name):
return _Method(self.__send, "%s.%s" % (self.__name, name))
def __call__(self, *args):
return self.__send(self.__name, args)
##
# Standard transport class for XML-RPC over HTTP.
# <p>
# You can create custom transports by subclassing this method, and
# overriding selected methods.
class Transport:
"""Handles an HTTP transaction to an XML-RPC server."""
# client identifier (may be overridden)
user_agent = "xmlrpclib.py/%s (by www.pythonware.com)" % __version__
#if true, we'll request gzip encoding
accept_gzip_encoding = True
# if positive, encode request using gzip if it exceeds this threshold
# note that many server will get confused, so only use it if you know
# that they can decode such a request
encode_threshold = None #None = don't encode
def __init__(self, use_datetime=0):
self._use_datetime = use_datetime
self._connection = (None, None)
self._extra_headers = []
##
# Send a complete request, and parse the response.
# Retry request if a cached connection has disconnected.
#
# @param host Target host.
# @param handler Target PRC handler.
# @param request_body XML-RPC request body.
# @param verbose Debugging flag.
# @return Parsed response.
def request(self, host, handler, request_body, verbose=0):
#retry request once if cached connection has gone cold
for i in (0, 1):
try:
return self.single_request(host, handler, request_body, verbose)
except socket.error as e:
if i or e.errno not in (errno.ECONNRESET, errno.ECONNABORTED, errno.EPIPE):
raise
except httplib.BadStatusLine: #close after we sent request
if i:
raise
##
# Send a complete request, and parse the response.
#
# @param host Target host.
# @param handler Target PRC handler.
# @param request_body XML-RPC request body.
# @param verbose Debugging flag.
# @return Parsed response.
def single_request(self, host, handler, request_body, verbose=0):
# issue XML-RPC request
h = self.make_connection(host)
if verbose:
h.set_debuglevel(1)
try:
self.send_request(h, handler, request_body)
self.send_host(h, host)
self.send_user_agent(h)
self.send_content(h, request_body)
response = h.getresponse(buffering=True)
if response.status == 200:
self.verbose = verbose
return self.parse_response(response)
except Fault:
raise
except Exception:
# All unexpected errors leave connection in
# a strange state, so we clear it.
self.close()
raise
#discard any response data and raise exception
if (response.getheader("content-length", 0)):
response.read()
raise ProtocolError(
host + handler,
response.status, response.reason,
response.msg,
)
##
# Create parser.
#
# @return A 2-tuple containing a parser and a unmarshaller.
def getparser(self):
# get parser and unmarshaller
return getparser(use_datetime=self._use_datetime)
##
# Get authorization info from host parameter
# Host may be a string, or a (host, x509-dict) tuple; if a string,
# it is checked for a "user:pw@host" format, and a "Basic
# Authentication" header is added if appropriate.
#
# @param host Host descriptor (URL or (URL, x509 info) tuple).
# @return A 3-tuple containing (actual host, extra headers,
# x509 info). The header and x509 fields may be None.
def get_host_info(self, host):
x509 = {}
if isinstance(host, TupleType):
host, x509 = host
import urllib
auth, host = urllib.splituser(host)
if auth:
import base64
auth = base64.encodestring(urllib.unquote(auth))
auth = string.join(string.split(auth), "") # get rid of whitespace
extra_headers = [
("Authorization", "Basic " + auth)
]
else:
extra_headers = None
return host, extra_headers, x509
##
# Connect to server.
#
# @param host Target host.
# @return A connection handle.
def make_connection(self, host):
#return an existing connection if possible. This allows
#HTTP/1.1 keep-alive.
if self._connection and host == self._connection[0]:
return self._connection[1]
# create a HTTP connection object from a host descriptor
chost, self._extra_headers, x509 = self.get_host_info(host)
#store the host argument along with the connection object
self._connection = host, httplib.HTTPConnection(chost)
return self._connection[1]
##
# Clear any cached connection object.
# Used in the event of socket errors.
#
def close(self):
host, connection = self._connection
if connection:
self._connection = (None, None)
connection.close()
##
# Send request header.
#
# @param connection Connection handle.
# @param handler Target RPC handler.
# @param request_body XML-RPC body.
def send_request(self, connection, handler, request_body):
if (self.accept_gzip_encoding and gzip):
connection.putrequest("POST", handler, skip_accept_encoding=True)
connection.putheader("Accept-Encoding", "gzip")
else:
connection.putrequest("POST", handler)
##
# Send host name.
#
# @param connection Connection handle.
# @param host Host name.
#
# Note: This function doesn't actually add the "Host"
# header anymore, it is done as part of the connection.putrequest() in
# send_request() above.
def send_host(self, connection, host):
extra_headers = self._extra_headers
if extra_headers:
if isinstance(extra_headers, DictType):
extra_headers = extra_headers.items()
for key, value in extra_headers:
connection.putheader(key, value)
##
# Send user-agent identifier.
#
# @param connection Connection handle.
def send_user_agent(self, connection):
connection.putheader("User-Agent", self.user_agent)
##
# Send request body.
#
# @param connection Connection handle.
# @param request_body XML-RPC request body.
def send_content(self, connection, request_body):
connection.putheader("Content-Type", "text/xml")
#optionally encode the request
if (self.encode_threshold is not None and
self.encode_threshold < len(request_body) and
gzip):
connection.putheader("Content-Encoding", "gzip")
request_body = gzip_encode(request_body)
connection.putheader("Content-Length", str(len(request_body)))
connection.endheaders(request_body)
##
# Parse response.
#
# @param file Stream.
# @return Response tuple and target method.
def parse_response(self, response):
# read response data from httpresponse, and parse it
# Check for new http response object, else it is a file object
if hasattr(response,'getheader'):
if response.getheader("Content-Encoding", "") == "gzip":
stream = GzipDecodedResponse(response)
else:
stream = response
else:
stream = response
p, u = self.getparser()
while 1:
data = stream.read(1024)
if not data:
break
if self.verbose:
print("body: %s" % repr(data))
p.feed(data)
if stream is not response:
stream.close()
p.close()
return u.close()
##
# Standard transport class for XML-RPC over HTTPS.
class SafeTransport(Transport):
"""Handles an HTTPS transaction to an XML-RPC server."""
def __init__(self, use_datetime=0, context=None):
Transport.__init__(self, use_datetime=use_datetime)
self.context = context
# FIXME: mostly untested
def make_connection(self, host):
if self._connection and host == self._connection[0]:
return self._connection[1]
# create a HTTPS connection object from a host descriptor
# host may be a string, or a (host, x509-dict) tuple
try:
HTTPS = httplib.HTTPSConnection
except AttributeError:
raise NotImplementedError(
"your version of httplib doesn't support HTTPS"
)
else:
chost, self._extra_headers, x509 = self.get_host_info(host)
self._connection = host, HTTPS(chost, None, context=self.context, **(x509 or {}))
return self._connection[1]
##
# Standard server proxy. This class establishes a virtual connection
# to an XML-RPC server.
# <p>
# This class is available as ServerProxy and Server. New code should
# use ServerProxy, to avoid confusion.
#
# @def ServerProxy(uri, **options)
# @param uri The connection point on the server.
# @keyparam transport A transport factory, compatible with the
# standard transport class.
# @keyparam encoding The default encoding used for 8-bit strings
# (default is UTF-8).
# @keyparam verbose Use a true value to enable debugging output.
# (printed to standard output).
# @keyparam utf8_encoding Way to encode UTF-8 characters. Use
# 'standard' to conform to XML standards (ejabberd > 14.07),
# 'php' to encode like PHP (ejabberd <= 14.07)
# 'python2' to behave in the same way as Python2
# Defaults to 'standard'.
# @see Transport
class ServerProxy:
"""uri [,options] -> a logical connection to an XML-RPC server
uri is the connection point on the server, given as
scheme://host/target.
The standard implementation always supports the "http" scheme. If
SSL socket support is available (Python 2.0), it also supports
"https".
If the target part and the slash preceding it are both omitted,
"/RPC2" is assumed.
The following options can be given as keyword arguments:
transport: a transport factory
encoding: the request encoding (default is UTF-8)
utf8_encoding: Way to encode UTF-8 characters. May currently be either
'standard' or 'php'.
All 8-bit strings passed to the server proxy are assumed to use
the given encoding.
"""
# xmpp-backends: Add the utf8_encoding parameter
def __init__(self, uri, transport=None, encoding=None, verbose=0,
allow_none=0, use_datetime=0, context=None, utf8_encoding='standard'):
# establish a "logical" server connection
if isinstance(uri, unicode):
uri = uri.encode('ISO-8859-1')
# get the url
import urllib
type, uri = urllib.splittype(uri)
if type not in ("http", "https"):
raise IOError("unsupported XML-RPC protocol")
self.__host, self.__handler = urllib.splithost(uri)
if not self.__handler:
self.__handler = "/RPC2"
if transport is None:
if type == "https":
transport = SafeTransport(use_datetime=use_datetime, context=context)
else:
transport = Transport(use_datetime=use_datetime)
self.__transport = transport
self.__encoding = encoding
self.__verbose = verbose
self.__allow_none = allow_none
# xmpp-backends: Set the utf8_encoding parameter
self.__utf8_encoding = utf8_encoding
def __close(self):
self.__transport.close()
def __request(self, methodname, params):
# call a method on the remote server
request = dumps(params, methodname, encoding=self.__encoding,
allow_none=self.__allow_none)
response = self.__transport.request(
self.__host,
self.__handler,
request,
verbose=self.__verbose
)
if len(response) == 1:
response = response[0]
return response
def __repr__(self):
return (
"<ServerProxy for %s%s>" %
(self.__host, self.__handler)
)
__str__ = __repr__
def __getattr__(self, name):
# magic method dispatcher
return _Method(self.__request, name)
# note: to call a remote object with an non-standard name, use
# result getattr(server, "strange-python-name")(args)
def __call__(self, attr):
"""A workaround to get special attributes on the ServerProxy
without interfering with the magic __getattr__
"""
if attr == "close":
return self.__close
elif attr == "transport":
return self.__transport
raise AttributeError("Attribute %r not found" % (attr,))
# compatibility
Server = ServerProxy
# --------------------------------------------------------------------
# test code
if __name__ == "__main__":
server = ServerProxy("http://localhost:8000")
print(server)
multi = MultiCall(server)
multi.pow(2, 9)
multi.add(5, 1)
multi.add(24, 11)
try:
for response in multi():
print(response)
except Error as v:
print("ERROR: %s" % v)
|
mathiasertl/xmpp-backends
|
xmpp_backends/xmlrpclib.py
|
gzip_decode
|
python
|
def gzip_decode(data, max_decode=20971520):
if not gzip:
raise NotImplementedError
f = StringIO.StringIO(data)
gzf = gzip.GzipFile(mode="rb", fileobj=f)
try:
if max_decode < 0: # no limit
decoded = gzf.read()
else:
decoded = gzf.read(max_decode + 1)
except IOError:
raise ValueError("invalid data")
f.close()
gzf.close()
if max_decode >= 0 and len(decoded) > max_decode:
raise ValueError("max gzipped payload length exceeded")
return decoded
|
gzip encoded data -> unencoded data
Decode data using the gzip content encoding as described in RFC 1952
|
train
|
https://github.com/mathiasertl/xmpp-backends/blob/214ef0664dbf90fa300c2483b9b3416559e5d171/xmpp_backends/xmlrpclib.py#L1267-L1287
| null |
# -*- coding: utf-8 -*-
#
# XML-RPC CLIENT LIBRARY
# $Id$
#
# This is a copy of the xmlrpclib library shipping with Python 2.7.
# It is modified to encode UTF-8 characters in several different ways.
#
# The problem is that this library does not encode UTF-8 correctly and PHP's
# library doesn't encode them correctly either - but wrong in a differnt way.
# ejabberd <= 14.07 expects unicode in the way PHP encodes them and ejabberd
# versions after that expect unicode to be encoded according to XML standards.
#
# Here is an overview of what different encoding options there are,
# demonstrated by the example letter 'ä'. Use:
# https://en.wikipedia.org/wiki/%C3%84#Computer_encoding
# as reference next to the following examples:
#
# XML standard = what lxml produces and ejabberd > 14.07 accepts:
#
# >>> from lxml import etree
# >>> t = etree.Element('test')
# >>> t.text = u'ä' # note: 'ä' is not accepted
# >>> etree.tostring(t)
# <test>ä</test>
#
# What PHP produces and ejabberd <= 14.07 accepts:
#
# $ php -r 'print xmlrpc_encode("ä");'
# ...
# <string>ä</string>
# ...
#
# No encoding - Conforms to standards and is what Python3 produces
# (unknown if ejabberd accepts it)
#
# >>> import xmlrpclib
# >>> xmlrpclib.escape('ä')
# 'ä'
#
# What xmlrpclib in Python2 produces:
# >>> import xmlrpclib
# >>> xmlrpclib.escape('ä')
# '\xc3\xa4'
# >>> xmlrpclib.escape(u'ä') # unicode is not supported!
# ...
# TypeError: encode() argument 1 must be string, not None
#
# This library differs from the version that ships with Python 2.7.10 in that
# it adds a `utf8_encoding` parameter to support all three different encoding
# options. All changes are marked with a line starting with:
#
# xmpp-backends: ...
#
#
# an XML-RPC client interface for Python.
#
# the marshalling and response parser code can also be used to
# implement XML-RPC servers.
#
# Notes:
# this version is designed to work with Python 2.1 or newer.
#
# History:
# 1999-01-14 fl Created
# 1999-01-15 fl Changed dateTime to use localtime
# 1999-01-16 fl Added Binary/base64 element, default to RPC2 service
# 1999-01-19 fl Fixed array data element (from Skip Montanaro)
# 1999-01-21 fl Fixed dateTime constructor, etc.
# 1999-02-02 fl Added fault handling, handle empty sequences, etc.
# 1999-02-10 fl Fixed problem with empty responses (from Skip Montanaro)
# 1999-06-20 fl Speed improvements, pluggable parsers/transports (0.9.8)
# 2000-11-28 fl Changed boolean to check the truth value of its argument
# 2001-02-24 fl Added encoding/Unicode/SafeTransport patches
# 2001-02-26 fl Added compare support to wrappers (0.9.9/1.0b1)
# 2001-03-28 fl Make sure response tuple is a singleton
# 2001-03-29 fl Don't require empty params element (from Nicholas Riley)
# 2001-06-10 fl Folded in _xmlrpclib accelerator support (1.0b2)
# 2001-08-20 fl Base xmlrpclib.Error on built-in Exception (from Paul Prescod)
# 2001-09-03 fl Allow Transport subclass to override getparser
# 2001-09-10 fl Lazy import of urllib, cgi, xmllib (20x import speedup)
# 2001-10-01 fl Remove containers from memo cache when done with them
# 2001-10-01 fl Use faster escape method (80% dumps speedup)
# 2001-10-02 fl More dumps microtuning
# 2001-10-04 fl Make sure import expat gets a parser (from Guido van Rossum)
# 2001-10-10 sm Allow long ints to be passed as ints if they don't overflow
# 2001-10-17 sm Test for int and long overflow (allows use on 64-bit systems)
# 2001-11-12 fl Use repr() to marshal doubles (from Paul Felix)
# 2002-03-17 fl Avoid buffered read when possible (from James Rucker)
# 2002-04-07 fl Added pythondoc comments
# 2002-04-16 fl Added __str__ methods to datetime/binary wrappers
# 2002-05-15 fl Added error constants (from Andrew Kuchling)
# 2002-06-27 fl Merged with Python CVS version
# 2002-10-22 fl Added basic authentication (based on code from Phillip Eby)
# 2003-01-22 sm Add support for the bool type
# 2003-02-27 gvr Remove apply calls
# 2003-04-24 sm Use cStringIO if available
# 2003-04-25 ak Add support for nil
# 2003-06-15 gn Add support for time.struct_time
# 2003-07-12 gp Correct marshalling of Faults
# 2003-10-31 mvl Add multicall support
# 2004-08-20 mvl Bump minimum supported Python version to 2.1
# 2014-12-02 ch/doko Add workaround for gzip bomb vulnerability
#
# Copyright (c) 1999-2002 by Secret Labs AB.
# Copyright (c) 1999-2002 by Fredrik Lundh.
#
# info@pythonware.com
# http://www.pythonware.com
#
# --------------------------------------------------------------------
# The XML-RPC client interface is
#
# Copyright (c) 1999-2002 by Secret Labs AB
# Copyright (c) 1999-2002 by Fredrik Lundh
#
# By obtaining, using, and/or copying this software and/or its
# associated documentation, you agree that you have read, understood,
# and will comply with the following terms and conditions:
#
# Permission to use, copy, modify, and distribute this software and
# its associated documentation for any purpose and without fee is
# hereby granted, provided that the above copyright notice appears in
# all copies, and that both that copyright notice and this permission
# notice appear in supporting documentation, and that the name of
# Secret Labs AB or the author not be used in advertising or publicity
# pertaining to distribution of the software without specific, written
# prior permission.
#
# SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
# TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANT-
# ABILITY AND FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR
# BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY
# DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
# WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
# ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
# OF THIS SOFTWARE.
# --------------------------------------------------------------------
#
# things to look into some day:
# TODO: sort out True/False/boolean issues for Python 2.3
"""
An XML-RPC client interface for Python.
The marshalling and response parser code can also be used to
implement XML-RPC servers.
Exported exceptions:
Error Base class for client errors
ProtocolError Indicates an HTTP protocol error
ResponseError Indicates a broken response package
Fault Indicates an XML-RPC fault package
Exported classes:
ServerProxy Represents a logical connection to an XML-RPC server
MultiCall Executor of boxcared xmlrpc requests
Boolean boolean wrapper to generate a "boolean" XML-RPC value
DateTime dateTime wrapper for an ISO 8601 string or time tuple or
localtime integer value to generate a "dateTime.iso8601"
XML-RPC value
Binary binary data wrapper
SlowParser Slow but safe standard parser (based on xmllib)
Marshaller Generate an XML-RPC params chunk from a Python data structure
Unmarshaller Unmarshal an XML-RPC response from incoming XML event message
Transport Handles an HTTP transaction to an XML-RPC server
SafeTransport Handles an HTTPS transaction to an XML-RPC server
Exported constants:
True
False
Exported functions:
boolean Convert any Python value to an XML-RPC boolean
getparser Create instance of the fastest available parser & attach
to an unmarshalling object
dumps Convert an argument tuple or a Fault instance to an XML-RPC
request (or response, if the methodresponse option is used).
loads Convert an XML-RPC packet to unmarshalled data plus a method
name (None if not present).
"""
import re, string, time, operator
# xmpp-backends: Do not use wildcard import to improve syntax checkers
from types import (TupleType, StringType, InstanceType, NoneType, IntType,
LongType, FloatType, ListType, DictType, UnicodeType)
import socket
import errno
import httplib
try:
import gzip
except ImportError:
gzip = None #python can be built without zlib/gzip support
# --------------------------------------------------------------------
# Internal stuff
try:
unicode
except NameError:
unicode = None # unicode support not available
try:
import datetime
except ImportError:
datetime = None
try:
_bool_is_builtin = False.__class__.__name__ == "bool"
except NameError:
_bool_is_builtin = 0
def _decode(data, encoding, is8bit=re.compile("[\x80-\xff]").search):
# decode non-ascii string (if possible)
if unicode and encoding and is8bit(data):
data = unicode(data, encoding)
return data
# xmpp-backends: Add the utf8_encoding parameter
def escape(s, replace=string.replace, utf8_encoding='standard'):
s = replace(s, "&", "&")
s = replace(s, "<", "<")
s = replace(s, ">", ">")
if utf8_encoding == 'python2':
return s
elif utf8_encoding == 'none':
if isinstance(s, unicode):
return s
return s.decode('utf-8')
encoded = ''
# xmpp-backends: Handle the utf8_encoding parameter
if utf8_encoding == 'php':
if isinstance(s, unicode): # py2 and unicode
_encode = lambda char: ''.join(['&#%s;' % ord(b) for b in char.encode('utf-8')])
else: # py2 str
_encode = lambda char: ''.join(['&#%s;' % ord(b) for b in char])
elif utf8_encoding == 'standard':
if isinstance(s, str):
s = s.decode('utf-8')
_encode = lambda char: '&#%s;' % ord(char)
else:
raise AttributeError("Unknown utf8_encoding '%s'" % utf8_encoding)
for char in s:
if ord(char) >= 128:
encoded += _encode(char)
else:
encoded += char
return encoded
if unicode:
def _stringify(string):
# convert to 7-bit ascii if possible
try:
return string.encode("ascii")
except UnicodeError:
return string
else:
def _stringify(string):
return string
__version__ = "1.0.1"
# xmlrpc integer limits
MAXINT = 2 **31-1
MININT = -2 **31
# --------------------------------------------------------------------
# Error constants (from Dan Libby's specification at
# http://xmlrpc-epi.sourceforge.net/specs/rfc.fault_codes.php)
# Ranges of errors
PARSE_ERROR = -32700
SERVER_ERROR = -32600
APPLICATION_ERROR = -32500
SYSTEM_ERROR = -32400
TRANSPORT_ERROR = -32300
# Specific errors
NOT_WELLFORMED_ERROR = -32700
UNSUPPORTED_ENCODING = -32701
INVALID_ENCODING_CHAR = -32702
INVALID_XMLRPC = -32600
METHOD_NOT_FOUND = -32601
INVALID_METHOD_PARAMS = -32602
INTERNAL_ERROR = -32603
# --------------------------------------------------------------------
# Exceptions
##
# Base class for all kinds of client-side errors.
class Error(Exception):
"""Base class for client errors."""
def __str__(self):
return repr(self)
##
# Indicates an HTTP-level protocol error. This is raised by the HTTP
# transport layer, if the server returns an error code other than 200
# (OK).
#
# @param url The target URL.
# @param errcode The HTTP error code.
# @param errmsg The HTTP error message.
# @param headers The HTTP header dictionary.
class ProtocolError(Error):
"""Indicates an HTTP protocol error."""
def __init__(self, url, errcode, errmsg, headers):
Error.__init__(self)
self.url = url
self.errcode = errcode
self.errmsg = errmsg
self.headers = headers
def __repr__(self):
return (
"<ProtocolError for %s: %s %s>" %
(self.url, self.errcode, self.errmsg)
)
##
# Indicates a broken XML-RPC response package. This exception is
# raised by the unmarshalling layer, if the XML-RPC response is
# malformed.
class ResponseError(Error):
"""Indicates a broken response package."""
pass
##
# Indicates an XML-RPC fault response package. This exception is
# raised by the unmarshalling layer, if the XML-RPC response contains
# a fault string. This exception can also used as a class, to
# generate a fault XML-RPC message.
#
# @param faultCode The XML-RPC fault code.
# @param faultString The XML-RPC fault string.
class Fault(Error):
"""Indicates an XML-RPC fault package."""
def __init__(self, faultCode, faultString, **extra):
Error.__init__(self)
self.faultCode = faultCode
self.faultString = faultString
def __repr__(self):
return (
"<Fault %s: %s>" %
(self.faultCode, repr(self.faultString))
)
# --------------------------------------------------------------------
# Special values
##
# Wrapper for XML-RPC boolean values. Use the xmlrpclib.True and
# xmlrpclib.False constants, or the xmlrpclib.boolean() function, to
# generate boolean XML-RPC values.
#
# @param value A boolean value. Any true value is interpreted as True,
# all other values are interpreted as False.
from sys import modules
mod_dict = modules[__name__].__dict__
if _bool_is_builtin:
boolean = Boolean = bool
# to avoid breaking code which references xmlrpclib.{True,False}
mod_dict['True'] = True
mod_dict['False'] = False
else:
class Boolean:
"""Boolean-value wrapper.
Use True or False to generate a "boolean" XML-RPC value.
"""
def __init__(self, value = 0):
self.value = operator.truth(value)
def encode(self, out):
out.write("<value><boolean>%d</boolean></value>\n" % self.value)
def __cmp__(self, other):
if isinstance(other, Boolean):
other = other.value
return cmp(self.value, other)
def __repr__(self):
if self.value:
return "<Boolean True at %x>" % id(self)
else:
return "<Boolean False at %x>" % id(self)
def __int__(self):
return self.value
def __nonzero__(self):
return self.value
mod_dict['True'] = Boolean(1)
mod_dict['False'] = Boolean(0)
##
# Map true or false value to XML-RPC boolean values.
#
# @def boolean(value)
# @param value A boolean value. Any true value is mapped to True,
# all other values are mapped to False.
# @return xmlrpclib.True or xmlrpclib.False.
# @see Boolean
# @see True
# @see False
def boolean(value, _truefalse=(False, True)):
"""Convert any Python value to XML-RPC 'boolean'."""
return _truefalse[operator.truth(value)]
del modules, mod_dict
##
# Wrapper for XML-RPC DateTime values. This converts a time value to
# the format used by XML-RPC.
# <p>
# The value can be given as a string in the format
# "yyyymmddThh:mm:ss", as a 9-item time tuple (as returned by
# time.localtime()), or an integer value (as returned by time.time()).
# The wrapper uses time.localtime() to convert an integer to a time
# tuple.
#
# @param value The time, given as an ISO 8601 string, a time
# tuple, or a integer time value.
def _strftime(value):
if datetime:
if isinstance(value, datetime.datetime):
return "%04d%02d%02dT%02d:%02d:%02d" % (
value.year, value.month, value.day,
value.hour, value.minute, value.second)
if not isinstance(value, (TupleType, time.struct_time)):
if value == 0:
value = time.time()
value = time.localtime(value)
return "%04d%02d%02dT%02d:%02d:%02d" % value[:6]
class DateTime:
"""DateTime wrapper for an ISO 8601 string or time tuple or
localtime integer value to generate 'dateTime.iso8601' XML-RPC
value.
"""
def __init__(self, value=0):
if isinstance(value, StringType):
self.value = value
else:
self.value = _strftime(value)
def make_comparable(self, other):
if isinstance(other, DateTime):
s = self.value
o = other.value
elif datetime and isinstance(other, datetime.datetime):
s = self.value
o = other.strftime("%Y%m%dT%H:%M:%S")
elif isinstance(other, (str, unicode)):
s = self.value
o = other
elif hasattr(other, "timetuple"):
s = self.timetuple()
o = other.timetuple()
else:
otype = (hasattr(other, "__class__")
and other.__class__.__name__
or type(other))
raise TypeError("Can't compare %s and %s" %
(self.__class__.__name__, otype))
return s, o
def __lt__(self, other):
s, o = self.make_comparable(other)
return s < o
def __le__(self, other):
s, o = self.make_comparable(other)
return s <= o
def __gt__(self, other):
s, o = self.make_comparable(other)
return s > o
def __ge__(self, other):
s, o = self.make_comparable(other)
return s >= o
def __eq__(self, other):
s, o = self.make_comparable(other)
return s == o
def __ne__(self, other):
s, o = self.make_comparable(other)
return s != o
def timetuple(self):
return time.strptime(self.value, "%Y%m%dT%H:%M:%S")
def __cmp__(self, other):
s, o = self.make_comparable(other)
return cmp(s, o)
##
# Get date/time value.
#
# @return Date/time value, as an ISO 8601 string.
def __str__(self):
return self.value
def __repr__(self):
return "<DateTime %s at %x>" % (repr(self.value), id(self))
def decode(self, data):
data = str(data)
self.value = string.strip(data)
def encode(self, out):
out.write("<value><dateTime.iso8601>")
out.write(self.value)
out.write("</dateTime.iso8601></value>\n")
def _datetime(data):
# decode xml element contents into a DateTime structure.
value = DateTime()
value.decode(data)
return value
def _datetime_type(data):
t = time.strptime(data, "%Y%m%dT%H:%M:%S")
return datetime.datetime(*tuple(t)[:6])
##
# Wrapper for binary data. This can be used to transport any kind
# of binary data over XML-RPC, using BASE64 encoding.
#
# @param data An 8-bit string containing arbitrary data.
import base64
try:
import cStringIO as StringIO
except ImportError:
import StringIO
class Binary:
"""Wrapper for binary data."""
def __init__(self, data=None):
self.data = data
##
# Get buffer contents.
#
# @return Buffer contents, as an 8-bit string.
def __str__(self):
return self.data or ""
def __cmp__(self, other):
if isinstance(other, Binary):
other = other.data
return cmp(self.data, other)
def decode(self, data):
self.data = base64.decodestring(data)
def encode(self, out):
out.write("<value><base64>\n")
base64.encode(StringIO.StringIO(self.data), out)
out.write("</base64></value>\n")
def _binary(data):
# decode xml element contents into a Binary structure
value = Binary()
value.decode(data)
return value
WRAPPERS = (DateTime, Binary)
if not _bool_is_builtin:
WRAPPERS = WRAPPERS + (Boolean,)
# --------------------------------------------------------------------
# XML parsers
try:
# optional xmlrpclib accelerator
import _xmlrpclib
FastParser = _xmlrpclib.Parser
FastUnmarshaller = _xmlrpclib.Unmarshaller
except (AttributeError, ImportError):
FastParser = FastUnmarshaller = None
try:
import _xmlrpclib
FastMarshaller = _xmlrpclib.Marshaller
except (AttributeError, ImportError):
FastMarshaller = None
try:
from xml.parsers import expat
if not hasattr(expat, "ParserCreate"):
raise ImportError
except ImportError:
ExpatParser = None # expat not available
else:
class ExpatParser:
# fast expat parser for Python 2.0 and later.
def __init__(self, target):
self._parser = parser = expat.ParserCreate(None, None)
self._target = target
parser.StartElementHandler = target.start
parser.EndElementHandler = target.end
parser.CharacterDataHandler = target.data
encoding = None
if not parser.returns_unicode:
encoding = "utf-8"
target.xml(encoding, None)
def feed(self, data):
self._parser.Parse(data, 0)
def close(self):
try:
parser = self._parser
except AttributeError:
pass
else:
del self._target, self._parser # get rid of circular references
parser.Parse("", 1) # end of data
class SlowParser:
"""Default XML parser (based on xmllib.XMLParser)."""
# this is the slowest parser.
def __init__(self, target):
import xmllib # lazy subclassing (!)
if xmllib.XMLParser not in SlowParser.__bases__:
SlowParser.__bases__ = (xmllib.XMLParser,)
self.handle_xml = target.xml
self.unknown_starttag = target.start
self.handle_data = target.data
self.handle_cdata = target.data
self.unknown_endtag = target.end
try:
xmllib.XMLParser.__init__(self, accept_utf8=1)
except TypeError:
xmllib.XMLParser.__init__(self) # pre-2.0
# --------------------------------------------------------------------
# XML-RPC marshalling and unmarshalling code
##
# XML-RPC marshaller.
#
# @param encoding Default encoding for 8-bit strings. The default
# value is None (interpreted as UTF-8).
# @see dumps
class Marshaller:
"""Generate an XML-RPC params chunk from a Python data structure.
Create a Marshaller instance for each set of parameters, and use
the "dumps" method to convert your data (represented as a tuple)
to an XML-RPC params chunk. To write a fault response, pass a
Fault instance instead. You may prefer to use the "dumps" module
function for this purpose.
"""
# by the way, if you don't understand what's going on in here,
# that's perfectly ok.
# xmpp-backends: Add the utf8_encoding parameter
def __init__(self, encoding=None, allow_none=0, utf8_encoding='standard'):
self.memo = {}
self.data = None
self.encoding = encoding
self.allow_none = allow_none
# xmpp-backends: Set the self.utf8_encoding property
self.utf8_encoding = utf8_encoding
dispatch = {}
def dumps(self, values):
out = []
write = out.append
dump = self.__dump
if isinstance(values, Fault):
# fault instance
write("<fault>\n")
dump({'faultCode': values.faultCode,
'faultString': values.faultString},
write)
write("</fault>\n")
else:
# parameter block
# FIXME: the xml-rpc specification allows us to leave out
# the entire <params> block if there are no parameters.
# however, changing this may break older code (including
# old versions of xmlrpclib.py), so this is better left as
# is for now. See @XMLRPC3 for more information. /F
write("<params>\n")
for v in values:
write("<param>\n")
dump(v, write)
write("</param>\n")
write("</params>\n")
result = string.join(out, "")
return result
def __dump(self, value, write):
try:
f = self.dispatch[type(value)]
except KeyError:
# check if this object can be marshalled as a structure
try:
value.__dict__
except:
raise TypeError("cannot marshal %s objects" % type(value))
# check if this class is a sub-class of a basic type,
# because we don't know how to marshal these types
# (e.g. a string sub-class)
for type_ in type(value).__mro__:
if type_ in self.dispatch.keys():
raise TypeError("cannot marshal %s objects" % type(value))
f = self.dispatch[InstanceType]
f(self, value, write)
def dump_nil (self, value, write):
if not self.allow_none:
raise TypeError("cannot marshal None unless allow_none is enabled")
write("<value><nil/></value>")
dispatch[NoneType] = dump_nil
def dump_int(self, value, write):
# in case ints are > 32 bits
if value > MAXINT or value < MININT:
raise OverflowError("int exceeds XML-RPC limits")
write("<value><int>")
write(str(value))
write("</int></value>\n")
dispatch[IntType] = dump_int
if _bool_is_builtin:
def dump_bool(self, value, write):
write("<value><boolean>")
write(value and "1" or "0")
write("</boolean></value>\n")
dispatch[bool] = dump_bool
def dump_long(self, value, write):
if value > MAXINT or value < MININT:
raise OverflowError("long int exceeds XML-RPC limits")
write("<value><int>")
write(str(int(value)))
write("</int></value>\n")
dispatch[LongType] = dump_long
def dump_double(self, value, write):
write("<value><double>")
write(repr(value))
write("</double></value>\n")
dispatch[FloatType] = dump_double
def dump_string(self, value, write, escape=escape):
write("<value><string>")
# xmpp-backends: Pass utf8_encoding parameter
write(escape(value, utf8_encoding=self.utf8_encoding))
write("</string></value>\n")
dispatch[StringType] = dump_string
if unicode:
def dump_unicode(self, value, write, escape=escape):
write("<value><string>")
# xmpp-backends: Pass utf8_encoding parameter
write(escape(value, utf8_encoding=self.utf8_encoding))
write("</string></value>\n")
dispatch[UnicodeType] = dump_unicode
def dump_array(self, value, write):
i = id(value)
if i in self.memo:
raise TypeError("cannot marshal recursive sequences")
self.memo[i] = None
dump = self.__dump
write("<value><array><data>\n")
for v in value:
dump(v, write)
write("</data></array></value>\n")
del self.memo[i]
dispatch[TupleType] = dump_array
dispatch[ListType] = dump_array
def dump_struct(self, value, write, escape=escape):
i = id(value)
if i in self.memo:
raise TypeError("cannot marshal recursive dictionaries")
self.memo[i] = None
dump = self.__dump
write("<value><struct>\n")
for k, v in value.items():
write("<member>\n")
if type(k) is not StringType:
if unicode and type(k) is UnicodeType:
k = k.encode(self.encoding)
else:
raise TypeError("dictionary key must be string")
write("<name>%s</name>\n" % escape(k))
dump(v, write)
write("</member>\n")
write("</struct></value>\n")
del self.memo[i]
dispatch[DictType] = dump_struct
if datetime:
def dump_datetime(self, value, write):
write("<value><dateTime.iso8601>")
write(_strftime(value))
write("</dateTime.iso8601></value>\n")
dispatch[datetime.datetime] = dump_datetime
def dump_instance(self, value, write):
# check for special wrappers
if value.__class__ in WRAPPERS:
self.write = write
value.encode(self)
del self.write
else:
# store instance attributes as a struct (really?)
self.dump_struct(value.__dict__, write)
dispatch[InstanceType] = dump_instance
##
# XML-RPC unmarshaller.
#
# @see loads
class Unmarshaller:
"""Unmarshal an XML-RPC response, based on incoming XML event
messages (start, data, end). Call close() to get the resulting
data structure.
Note that this reader is fairly tolerant, and gladly accepts bogus
XML-RPC data without complaining (but not bogus XML).
"""
# and again, if you don't understand what's going on in here,
# that's perfectly ok.
def __init__(self, use_datetime=0):
self._type = None
self._stack = []
self._marks = []
self._data = []
self._methodname = None
self._encoding = "utf-8"
self.append = self._stack.append
self._use_datetime = use_datetime
if use_datetime and not datetime:
raise ValueError("the datetime module is not available")
def close(self):
# return response tuple and target method
if self._type is None or self._marks:
raise ResponseError()
if self._type == "fault":
raise Fault(**self._stack[0])
return tuple(self._stack)
def getmethodname(self):
return self._methodname
#
# event handlers
def xml(self, encoding, standalone):
self._encoding = encoding
# FIXME: assert standalone == 1 ???
def start(self, tag, attrs):
# prepare to handle this element
if tag == "array" or tag == "struct":
self._marks.append(len(self._stack))
self._data = []
self._value = (tag == "value")
def data(self, text):
self._data.append(text)
def end(self, tag, join=string.join):
# call the appropriate end tag handler
try:
f = self.dispatch[tag]
except KeyError:
pass # unknown tag ?
else:
return f(self, join(self._data, ""))
#
# accelerator support
def end_dispatch(self, tag, data):
# dispatch data
try:
f = self.dispatch[tag]
except KeyError:
pass # unknown tag ?
else:
return f(self, data)
#
# element decoders
dispatch = {}
def end_nil (self, data):
self.append(None)
self._value = 0
dispatch["nil"] = end_nil
def end_boolean(self, data):
if data == "0":
self.append(False)
elif data == "1":
self.append(True)
else:
raise TypeError("bad boolean value")
self._value = 0
dispatch["boolean"] = end_boolean
def end_int(self, data):
self.append(int(data))
self._value = 0
dispatch["i4"] = end_int
dispatch["i8"] = end_int
dispatch["int"] = end_int
def end_double(self, data):
self.append(float(data))
self._value = 0
dispatch["double"] = end_double
def end_string(self, data):
if self._encoding:
data = _decode(data, self._encoding)
self.append(_stringify(data))
self._value = 0
dispatch["string"] = end_string
dispatch["name"] = end_string # struct keys are always strings
def end_array(self, data):
mark = self._marks.pop()
# map arrays to Python lists
self._stack[mark:] = [self._stack[mark:]]
self._value = 0
dispatch["array"] = end_array
def end_struct(self, data):
mark = self._marks.pop()
# map structs to Python dictionaries
dict = {}
items = self._stack[mark:]
for i in range(0, len(items), 2):
dict[_stringify(items[i])] = items[i+1]
self._stack[mark:] = [dict]
self._value = 0
dispatch["struct"] = end_struct
def end_base64(self, data):
value = Binary()
value.decode(data)
self.append(value)
self._value = 0
dispatch["base64"] = end_base64
def end_dateTime(self, data):
value = DateTime()
value.decode(data)
if self._use_datetime:
value = _datetime_type(data)
self.append(value)
dispatch["dateTime.iso8601"] = end_dateTime
def end_value(self, data):
# if we stumble upon a value element with no internal
# elements, treat it as a string element
if self._value:
self.end_string(data)
dispatch["value"] = end_value
def end_params(self, data):
self._type = "params"
dispatch["params"] = end_params
def end_fault(self, data):
self._type = "fault"
dispatch["fault"] = end_fault
def end_methodName(self, data):
if self._encoding:
data = _decode(data, self._encoding)
self._methodname = data
self._type = "methodName" # no params
dispatch["methodName"] = end_methodName
## Multicall support
#
class _MultiCallMethod:
# some lesser magic to store calls made to a MultiCall object
# for batch execution
def __init__(self, call_list, name):
self.__call_list = call_list
self.__name = name
def __getattr__(self, name):
return _MultiCallMethod(self.__call_list, "%s.%s" % (self.__name, name))
def __call__(self, *args):
self.__call_list.append((self.__name, args))
class MultiCallIterator:
"""Iterates over the results of a multicall. Exceptions are
raised in response to xmlrpc faults."""
def __init__(self, results):
self.results = results
def __getitem__(self, i):
item = self.results[i]
if type(item) == type({}):
raise Fault(item['faultCode'], item['faultString'])
elif type(item) == type([]):
return item[0]
else:
raise ValueError("unexpected type in multicall result")
class MultiCall:
"""server -> a object used to boxcar method calls
server should be a ServerProxy object.
Methods can be added to the MultiCall using normal
method call syntax e.g.:
multicall = MultiCall(server_proxy)
multicall.add(2,3)
multicall.get_address("Guido")
To execute the multicall, call the MultiCall object e.g.:
add_result, address = multicall()
"""
def __init__(self, server):
self.__server = server
self.__call_list = []
def __repr__(self):
return "<MultiCall at %x>" % id(self)
__str__ = __repr__
def __getattr__(self, name):
return _MultiCallMethod(self.__call_list, name)
def __call__(self):
marshalled_list = []
for name, args in self.__call_list:
marshalled_list.append({'methodName' : name, 'params' : args})
return MultiCallIterator(self.__server.system.multicall(marshalled_list))
# --------------------------------------------------------------------
# convenience functions
##
# Create a parser object, and connect it to an unmarshalling instance.
# This function picks the fastest available XML parser.
#
# return A (parser, unmarshaller) tuple.
def getparser(use_datetime=0):
"""getparser() -> parser, unmarshaller
Create an instance of the fastest available parser, and attach it
to an unmarshalling object. Return both objects.
"""
if use_datetime and not datetime:
raise ValueError("the datetime module is not available")
if FastParser and FastUnmarshaller:
if use_datetime:
mkdatetime = _datetime_type
else:
mkdatetime = _datetime
target = FastUnmarshaller(True, False, _binary, mkdatetime, Fault)
parser = FastParser(target)
else:
target = Unmarshaller(use_datetime=use_datetime)
if FastParser:
parser = FastParser(target)
elif ExpatParser:
parser = ExpatParser(target)
else:
parser = SlowParser(target)
return parser, target
##
# Convert a Python tuple or a Fault instance to an XML-RPC packet.
#
# @def dumps(params, **options)
# @param params A tuple or Fault instance.
# @keyparam methodname If given, create a methodCall request for
# this method name.
# @keyparam methodresponse If given, create a methodResponse packet.
# If used with a tuple, the tuple must be a singleton (that is,
# it must contain exactly one element).
# @keyparam encoding The packet encoding.
# @return A string containing marshalled data.
# xmpp-backends: Add the utf8_encoding parameter
def dumps(params, methodname=None, methodresponse=None, encoding=None,
allow_none=0, utf8_encoding='standard'):
"""data [,options] -> marshalled data
Convert an argument tuple or a Fault instance to an XML-RPC
request (or response, if the methodresponse option is used).
In addition to the data object, the following options can be given
as keyword arguments:
methodname: the method name for a methodCall packet
methodresponse: true to create a methodResponse packet.
If this option is used with a tuple, the tuple must be
a singleton (i.e. it can contain only one element).
encoding: the packet encoding (default is UTF-8)
All 8-bit strings in the data structure are assumed to use the
packet encoding. Unicode strings are automatically converted,
where necessary.
"""
assert isinstance(params, TupleType) or isinstance(params, Fault),\
"argument must be tuple or Fault instance"
if isinstance(params, Fault):
methodresponse = 1
elif methodresponse and isinstance(params, TupleType):
assert len(params) == 1, "response tuple must be a singleton"
if not encoding:
encoding = "utf-8"
if FastMarshaller:
m = FastMarshaller(encoding)
else:
m = Marshaller(encoding, allow_none)
data = m.dumps(params)
if encoding != "utf-8":
xmlheader = "<?xml version='1.0' encoding='%s'?>\n" % str(encoding)
else:
xmlheader = "<?xml version='1.0'?>\n" # utf-8 is default
# standard XML-RPC wrappings
if methodname:
# a method call
if not isinstance(methodname, StringType):
methodname = methodname.encode(encoding)
data = (
xmlheader,
"<methodCall>\n"
"<methodName>", methodname, "</methodName>\n",
data,
"</methodCall>\n"
)
elif methodresponse:
# a method response, or a fault structure
data = (
xmlheader,
"<methodResponse>\n",
data,
"</methodResponse>\n"
)
else:
return data # return as is
return string.join(data, "")
##
# Convert an XML-RPC packet to a Python object. If the XML-RPC packet
# represents a fault condition, this function raises a Fault exception.
#
# @param data An XML-RPC packet, given as an 8-bit string.
# @return A tuple containing the unpacked data, and the method name
# (None if not present).
# @see Fault
def loads(data, use_datetime=0):
"""data -> unmarshalled data, method name
Convert an XML-RPC packet to unmarshalled data plus a method
name (None if not present).
If the XML-RPC packet represents a fault condition, this function
raises a Fault exception.
"""
p, u = getparser(use_datetime=use_datetime)
p.feed(data)
p.close()
return u.close(), u.getmethodname()
##
# Encode a string using the gzip content encoding such as specified by the
# Content-Encoding: gzip
# in the HTTP header, as described in RFC 1952
#
# @param data the unencoded data
# @return the encoded data
def gzip_encode(data):
"""data -> gzip encoded data
Encode data using the gzip content encoding as described in RFC 1952
"""
if not gzip:
raise NotImplementedError
f = StringIO.StringIO()
gzf = gzip.GzipFile(mode="wb", fileobj=f, compresslevel=1)
gzf.write(data)
gzf.close()
encoded = f.getvalue()
f.close()
return encoded
##
# Decode a string using the gzip content encoding such as specified by the
# Content-Encoding: gzip
# in the HTTP header, as described in RFC 1952
#
# @param data The encoded data
# @keyparam max_decode Maximum bytes to decode (20MB default), use negative
# values for unlimited decoding
# @return the unencoded data
# @raises ValueError if data is not correctly coded.
# @raises ValueError if max gzipped payload length exceeded
##
# Return a decoded file-like object for the gzip encoding
# as described in RFC 1952.
#
# @param response A stream supporting a read() method
# @return a file-like object that the decoded data can be read() from
class GzipDecodedResponse(gzip.GzipFile if gzip else object):
"""a file-like object to decode a response encoded with the gzip
method, as described in RFC 1952.
"""
def __init__(self, response):
#response doesn't support tell() and read(), required by
#GzipFile
if not gzip:
raise NotImplementedError
self.stringio = StringIO.StringIO(response.read())
gzip.GzipFile.__init__(self, mode="rb", fileobj=self.stringio)
def close(self):
try:
gzip.GzipFile.close(self)
finally:
self.stringio.close()
# --------------------------------------------------------------------
# request dispatcher
class _Method:
# some magic to bind an XML-RPC method to an RPC server.
# supports "nested" methods (e.g. examples.getStateName)
def __init__(self, send, name):
self.__send = send
self.__name = name
def __getattr__(self, name):
return _Method(self.__send, "%s.%s" % (self.__name, name))
def __call__(self, *args):
return self.__send(self.__name, args)
##
# Standard transport class for XML-RPC over HTTP.
# <p>
# You can create custom transports by subclassing this method, and
# overriding selected methods.
class Transport:
"""Handles an HTTP transaction to an XML-RPC server."""
# client identifier (may be overridden)
user_agent = "xmlrpclib.py/%s (by www.pythonware.com)" % __version__
#if true, we'll request gzip encoding
accept_gzip_encoding = True
# if positive, encode request using gzip if it exceeds this threshold
# note that many server will get confused, so only use it if you know
# that they can decode such a request
encode_threshold = None #None = don't encode
def __init__(self, use_datetime=0):
self._use_datetime = use_datetime
self._connection = (None, None)
self._extra_headers = []
##
# Send a complete request, and parse the response.
# Retry request if a cached connection has disconnected.
#
# @param host Target host.
# @param handler Target PRC handler.
# @param request_body XML-RPC request body.
# @param verbose Debugging flag.
# @return Parsed response.
def request(self, host, handler, request_body, verbose=0):
#retry request once if cached connection has gone cold
for i in (0, 1):
try:
return self.single_request(host, handler, request_body, verbose)
except socket.error as e:
if i or e.errno not in (errno.ECONNRESET, errno.ECONNABORTED, errno.EPIPE):
raise
except httplib.BadStatusLine: #close after we sent request
if i:
raise
##
# Send a complete request, and parse the response.
#
# @param host Target host.
# @param handler Target PRC handler.
# @param request_body XML-RPC request body.
# @param verbose Debugging flag.
# @return Parsed response.
def single_request(self, host, handler, request_body, verbose=0):
# issue XML-RPC request
h = self.make_connection(host)
if verbose:
h.set_debuglevel(1)
try:
self.send_request(h, handler, request_body)
self.send_host(h, host)
self.send_user_agent(h)
self.send_content(h, request_body)
response = h.getresponse(buffering=True)
if response.status == 200:
self.verbose = verbose
return self.parse_response(response)
except Fault:
raise
except Exception:
# All unexpected errors leave connection in
# a strange state, so we clear it.
self.close()
raise
#discard any response data and raise exception
if (response.getheader("content-length", 0)):
response.read()
raise ProtocolError(
host + handler,
response.status, response.reason,
response.msg,
)
##
# Create parser.
#
# @return A 2-tuple containing a parser and a unmarshaller.
def getparser(self):
# get parser and unmarshaller
return getparser(use_datetime=self._use_datetime)
##
# Get authorization info from host parameter
# Host may be a string, or a (host, x509-dict) tuple; if a string,
# it is checked for a "user:pw@host" format, and a "Basic
# Authentication" header is added if appropriate.
#
# @param host Host descriptor (URL or (URL, x509 info) tuple).
# @return A 3-tuple containing (actual host, extra headers,
# x509 info). The header and x509 fields may be None.
def get_host_info(self, host):
x509 = {}
if isinstance(host, TupleType):
host, x509 = host
import urllib
auth, host = urllib.splituser(host)
if auth:
import base64
auth = base64.encodestring(urllib.unquote(auth))
auth = string.join(string.split(auth), "") # get rid of whitespace
extra_headers = [
("Authorization", "Basic " + auth)
]
else:
extra_headers = None
return host, extra_headers, x509
##
# Connect to server.
#
# @param host Target host.
# @return A connection handle.
def make_connection(self, host):
#return an existing connection if possible. This allows
#HTTP/1.1 keep-alive.
if self._connection and host == self._connection[0]:
return self._connection[1]
# create a HTTP connection object from a host descriptor
chost, self._extra_headers, x509 = self.get_host_info(host)
#store the host argument along with the connection object
self._connection = host, httplib.HTTPConnection(chost)
return self._connection[1]
##
# Clear any cached connection object.
# Used in the event of socket errors.
#
def close(self):
host, connection = self._connection
if connection:
self._connection = (None, None)
connection.close()
##
# Send request header.
#
# @param connection Connection handle.
# @param handler Target RPC handler.
# @param request_body XML-RPC body.
def send_request(self, connection, handler, request_body):
if (self.accept_gzip_encoding and gzip):
connection.putrequest("POST", handler, skip_accept_encoding=True)
connection.putheader("Accept-Encoding", "gzip")
else:
connection.putrequest("POST", handler)
##
# Send host name.
#
# @param connection Connection handle.
# @param host Host name.
#
# Note: This function doesn't actually add the "Host"
# header anymore, it is done as part of the connection.putrequest() in
# send_request() above.
def send_host(self, connection, host):
extra_headers = self._extra_headers
if extra_headers:
if isinstance(extra_headers, DictType):
extra_headers = extra_headers.items()
for key, value in extra_headers:
connection.putheader(key, value)
##
# Send user-agent identifier.
#
# @param connection Connection handle.
def send_user_agent(self, connection):
connection.putheader("User-Agent", self.user_agent)
##
# Send request body.
#
# @param connection Connection handle.
# @param request_body XML-RPC request body.
def send_content(self, connection, request_body):
connection.putheader("Content-Type", "text/xml")
#optionally encode the request
if (self.encode_threshold is not None and
self.encode_threshold < len(request_body) and
gzip):
connection.putheader("Content-Encoding", "gzip")
request_body = gzip_encode(request_body)
connection.putheader("Content-Length", str(len(request_body)))
connection.endheaders(request_body)
##
# Parse response.
#
# @param file Stream.
# @return Response tuple and target method.
def parse_response(self, response):
# read response data from httpresponse, and parse it
# Check for new http response object, else it is a file object
if hasattr(response,'getheader'):
if response.getheader("Content-Encoding", "") == "gzip":
stream = GzipDecodedResponse(response)
else:
stream = response
else:
stream = response
p, u = self.getparser()
while 1:
data = stream.read(1024)
if not data:
break
if self.verbose:
print("body: %s" % repr(data))
p.feed(data)
if stream is not response:
stream.close()
p.close()
return u.close()
##
# Standard transport class for XML-RPC over HTTPS.
class SafeTransport(Transport):
"""Handles an HTTPS transaction to an XML-RPC server."""
def __init__(self, use_datetime=0, context=None):
Transport.__init__(self, use_datetime=use_datetime)
self.context = context
# FIXME: mostly untested
def make_connection(self, host):
if self._connection and host == self._connection[0]:
return self._connection[1]
# create a HTTPS connection object from a host descriptor
# host may be a string, or a (host, x509-dict) tuple
try:
HTTPS = httplib.HTTPSConnection
except AttributeError:
raise NotImplementedError(
"your version of httplib doesn't support HTTPS"
)
else:
chost, self._extra_headers, x509 = self.get_host_info(host)
self._connection = host, HTTPS(chost, None, context=self.context, **(x509 or {}))
return self._connection[1]
##
# Standard server proxy. This class establishes a virtual connection
# to an XML-RPC server.
# <p>
# This class is available as ServerProxy and Server. New code should
# use ServerProxy, to avoid confusion.
#
# @def ServerProxy(uri, **options)
# @param uri The connection point on the server.
# @keyparam transport A transport factory, compatible with the
# standard transport class.
# @keyparam encoding The default encoding used for 8-bit strings
# (default is UTF-8).
# @keyparam verbose Use a true value to enable debugging output.
# (printed to standard output).
# @keyparam utf8_encoding Way to encode UTF-8 characters. Use
# 'standard' to conform to XML standards (ejabberd > 14.07),
# 'php' to encode like PHP (ejabberd <= 14.07)
# 'python2' to behave in the same way as Python2
# Defaults to 'standard'.
# @see Transport
class ServerProxy:
"""uri [,options] -> a logical connection to an XML-RPC server
uri is the connection point on the server, given as
scheme://host/target.
The standard implementation always supports the "http" scheme. If
SSL socket support is available (Python 2.0), it also supports
"https".
If the target part and the slash preceding it are both omitted,
"/RPC2" is assumed.
The following options can be given as keyword arguments:
transport: a transport factory
encoding: the request encoding (default is UTF-8)
utf8_encoding: Way to encode UTF-8 characters. May currently be either
'standard' or 'php'.
All 8-bit strings passed to the server proxy are assumed to use
the given encoding.
"""
# xmpp-backends: Add the utf8_encoding parameter
def __init__(self, uri, transport=None, encoding=None, verbose=0,
allow_none=0, use_datetime=0, context=None, utf8_encoding='standard'):
# establish a "logical" server connection
if isinstance(uri, unicode):
uri = uri.encode('ISO-8859-1')
# get the url
import urllib
type, uri = urllib.splittype(uri)
if type not in ("http", "https"):
raise IOError("unsupported XML-RPC protocol")
self.__host, self.__handler = urllib.splithost(uri)
if not self.__handler:
self.__handler = "/RPC2"
if transport is None:
if type == "https":
transport = SafeTransport(use_datetime=use_datetime, context=context)
else:
transport = Transport(use_datetime=use_datetime)
self.__transport = transport
self.__encoding = encoding
self.__verbose = verbose
self.__allow_none = allow_none
# xmpp-backends: Set the utf8_encoding parameter
self.__utf8_encoding = utf8_encoding
def __close(self):
self.__transport.close()
def __request(self, methodname, params):
# call a method on the remote server
request = dumps(params, methodname, encoding=self.__encoding,
allow_none=self.__allow_none)
response = self.__transport.request(
self.__host,
self.__handler,
request,
verbose=self.__verbose
)
if len(response) == 1:
response = response[0]
return response
def __repr__(self):
return (
"<ServerProxy for %s%s>" %
(self.__host, self.__handler)
)
__str__ = __repr__
def __getattr__(self, name):
# magic method dispatcher
return _Method(self.__request, name)
# note: to call a remote object with an non-standard name, use
# result getattr(server, "strange-python-name")(args)
def __call__(self, attr):
"""A workaround to get special attributes on the ServerProxy
without interfering with the magic __getattr__
"""
if attr == "close":
return self.__close
elif attr == "transport":
return self.__transport
raise AttributeError("Attribute %r not found" % (attr,))
# compatibility
Server = ServerProxy
# --------------------------------------------------------------------
# test code
if __name__ == "__main__":
server = ServerProxy("http://localhost:8000")
print(server)
multi = MultiCall(server)
multi.pow(2, 9)
multi.add(5, 1)
multi.add(24, 11)
try:
for response in multi():
print(response)
except Error as v:
print("ERROR: %s" % v)
|
radzak/rtv-downloader
|
rtv/utils.py
|
suppress_stdout
|
python
|
def suppress_stdout():
save_stdout = sys.stdout
sys.stdout = DevNull()
yield
sys.stdout = save_stdout
|
Context manager that suppresses stdout.
Examples:
>>> with suppress_stdout():
... print('Test print')
>>> print('test')
test
|
train
|
https://github.com/radzak/rtv-downloader/blob/b9114b7f4c35fabe6ec9ad1764a65858667a866e/rtv/utils.py#L25-L40
| null |
import contextlib
import os
import re
import sys
import urllib.parse
import tldextract
import validators
from rtv.exceptions import WrongUrlError
class DevNull:
"""
DevNull class that has a no-op write and flush method.
"""
def write(self, *args, **kwargs):
pass
def flush(self):
pass
@contextlib.contextmanager
def validate_url(url):
"""
Validate url using validators package.
Args:
url (str): Url.
Returns:
bool: True if valid, False otherwise.
Examples:
>>> validate_url('http://google.com')
True
>>> validate_url('http://google') # doctest: +ELLIPSIS
ValidationFailure(...)
>>> if not validate_url('http://google'):
... print('not valid')
not valid
"""
return validators.url(url)
def get_domain_name(url):
"""
Extract a domain name from the url (without subdomain).
Args:
url (str): Url.
Returns:
str: Domain name.
Raises:
DomainNotMatchedError: If url is wrong.
Examples:
>>> get_domain_name('https://vod.tvp.pl/video/')
'tvp.pl'
>>> get_domain_name('https://vod')
Traceback (most recent call last):
...
rtv.exceptions.WrongUrlError: Couldn't match domain name of this url: https://vod
"""
if not validate_url(url):
raise WrongUrlError(f'Couldn\'t match domain name of this url: {url}')
ext = tldextract.extract(url)
return f'{ext.domain}.{ext.suffix}'
def clean_video_data(_data):
"""
Clean video data:
-> cleans title
-> ...
Args:
_data (dict): Information about the video.
Returns:
dict: Refined video data.
"""
data = _data.copy()
# TODO: fix this ugliness
title = data.get('title')
if title:
data['title'] = clean_title(title)
return data
def clean_title(title):
"""
Clean title -> remove dates, remove duplicated spaces and strip title.
Args:
title (str): Title.
Returns:
str: Clean title without dates, duplicated, trailing and leading spaces.
"""
date_pattern = re.compile(r'\W*'
r'\d{1,2}'
r'[/\-.]'
r'\d{1,2}'
r'[/\-.]'
r'(?=\d*)(?:.{4}|.{2})'
r'\W*')
title = date_pattern.sub(' ', title)
title = re.sub(r'\s{2,}', ' ', title)
title = title.strip()
return title
def clean_filename(filename):
"""
Remove unsupported filename characters.
On Windows file names cannot contain any of \/:*?"<>| characters.
Effectively remove all characters except alphanumeric, -_#.,() and spaces.
Args:
filename (str): Name of a file.
Returns:
str: Filename without unsupported characters.
"""
return re.sub('[^\w\-_#.,() ]', '', filename)
def file_exists(path):
"""
Check whether a file exists.
Args:
path (str): Path to a file.
Returns:
bool: True if exists, False otherwise.
"""
return os.path.exists(path)
def get_ext(url):
"""
Extract an extension from the url.
Args:
url (str): String representation of a url.
Returns:
str: Filename extension from a url (without a dot), '' if extension is not present.
"""
parsed = urllib.parse.urlparse(url)
root, ext = os.path.splitext(parsed.path)
return ext.lstrip('.')
def delete_duplicates(seq):
"""
Remove duplicates from an iterable, preserving the order.
Args:
seq: Iterable of various type.
Returns:
list: List of unique objects.
"""
seen = set()
seen_add = seen.add
return [x for x in seq if not (x in seen or seen_add(x))]
|
radzak/rtv-downloader
|
rtv/utils.py
|
get_domain_name
|
python
|
def get_domain_name(url):
if not validate_url(url):
raise WrongUrlError(f'Couldn\'t match domain name of this url: {url}')
ext = tldextract.extract(url)
return f'{ext.domain}.{ext.suffix}'
|
Extract a domain name from the url (without subdomain).
Args:
url (str): Url.
Returns:
str: Domain name.
Raises:
DomainNotMatchedError: If url is wrong.
Examples:
>>> get_domain_name('https://vod.tvp.pl/video/')
'tvp.pl'
>>> get_domain_name('https://vod')
Traceback (most recent call last):
...
rtv.exceptions.WrongUrlError: Couldn't match domain name of this url: https://vod
|
train
|
https://github.com/radzak/rtv-downloader/blob/b9114b7f4c35fabe6ec9ad1764a65858667a866e/rtv/utils.py#L68-L95
|
[
"def validate_url(url):\n \"\"\"\n Validate url using validators package.\n\n Args:\n url (str): Url.\n\n Returns:\n bool: True if valid, False otherwise.\n\n Examples:\n >>> validate_url('http://google.com')\n True\n\n >>> validate_url('http://google') # doctest: +ELLIPSIS\n ValidationFailure(...)\n\n >>> if not validate_url('http://google'):\n ... print('not valid')\n not valid\n\n \"\"\"\n return validators.url(url)\n"
] |
import contextlib
import os
import re
import sys
import urllib.parse
import tldextract
import validators
from rtv.exceptions import WrongUrlError
class DevNull:
"""
DevNull class that has a no-op write and flush method.
"""
def write(self, *args, **kwargs):
pass
def flush(self):
pass
@contextlib.contextmanager
def suppress_stdout():
"""
Context manager that suppresses stdout.
Examples:
>>> with suppress_stdout():
... print('Test print')
>>> print('test')
test
"""
save_stdout = sys.stdout
sys.stdout = DevNull()
yield
sys.stdout = save_stdout
def validate_url(url):
"""
Validate url using validators package.
Args:
url (str): Url.
Returns:
bool: True if valid, False otherwise.
Examples:
>>> validate_url('http://google.com')
True
>>> validate_url('http://google') # doctest: +ELLIPSIS
ValidationFailure(...)
>>> if not validate_url('http://google'):
... print('not valid')
not valid
"""
return validators.url(url)
def clean_video_data(_data):
"""
Clean video data:
-> cleans title
-> ...
Args:
_data (dict): Information about the video.
Returns:
dict: Refined video data.
"""
data = _data.copy()
# TODO: fix this ugliness
title = data.get('title')
if title:
data['title'] = clean_title(title)
return data
def clean_title(title):
"""
Clean title -> remove dates, remove duplicated spaces and strip title.
Args:
title (str): Title.
Returns:
str: Clean title without dates, duplicated, trailing and leading spaces.
"""
date_pattern = re.compile(r'\W*'
r'\d{1,2}'
r'[/\-.]'
r'\d{1,2}'
r'[/\-.]'
r'(?=\d*)(?:.{4}|.{2})'
r'\W*')
title = date_pattern.sub(' ', title)
title = re.sub(r'\s{2,}', ' ', title)
title = title.strip()
return title
def clean_filename(filename):
"""
Remove unsupported filename characters.
On Windows file names cannot contain any of \/:*?"<>| characters.
Effectively remove all characters except alphanumeric, -_#.,() and spaces.
Args:
filename (str): Name of a file.
Returns:
str: Filename without unsupported characters.
"""
return re.sub('[^\w\-_#.,() ]', '', filename)
def file_exists(path):
"""
Check whether a file exists.
Args:
path (str): Path to a file.
Returns:
bool: True if exists, False otherwise.
"""
return os.path.exists(path)
def get_ext(url):
"""
Extract an extension from the url.
Args:
url (str): String representation of a url.
Returns:
str: Filename extension from a url (without a dot), '' if extension is not present.
"""
parsed = urllib.parse.urlparse(url)
root, ext = os.path.splitext(parsed.path)
return ext.lstrip('.')
def delete_duplicates(seq):
"""
Remove duplicates from an iterable, preserving the order.
Args:
seq: Iterable of various type.
Returns:
list: List of unique objects.
"""
seen = set()
seen_add = seen.add
return [x for x in seq if not (x in seen or seen_add(x))]
|
radzak/rtv-downloader
|
rtv/utils.py
|
clean_video_data
|
python
|
def clean_video_data(_data):
data = _data.copy()
# TODO: fix this ugliness
title = data.get('title')
if title:
data['title'] = clean_title(title)
return data
|
Clean video data:
-> cleans title
-> ...
Args:
_data (dict): Information about the video.
Returns:
dict: Refined video data.
|
train
|
https://github.com/radzak/rtv-downloader/blob/b9114b7f4c35fabe6ec9ad1764a65858667a866e/rtv/utils.py#L98-L119
|
[
"def clean_title(title):\n \"\"\"\n Clean title -> remove dates, remove duplicated spaces and strip title.\n\n Args:\n title (str): Title.\n\n Returns:\n str: Clean title without dates, duplicated, trailing and leading spaces.\n\n \"\"\"\n date_pattern = re.compile(r'\\W*'\n r'\\d{1,2}'\n r'[/\\-.]'\n r'\\d{1,2}'\n r'[/\\-.]'\n r'(?=\\d*)(?:.{4}|.{2})'\n r'\\W*')\n title = date_pattern.sub(' ', title)\n title = re.sub(r'\\s{2,}', ' ', title)\n title = title.strip()\n return title\n"
] |
import contextlib
import os
import re
import sys
import urllib.parse
import tldextract
import validators
from rtv.exceptions import WrongUrlError
class DevNull:
"""
DevNull class that has a no-op write and flush method.
"""
def write(self, *args, **kwargs):
pass
def flush(self):
pass
@contextlib.contextmanager
def suppress_stdout():
"""
Context manager that suppresses stdout.
Examples:
>>> with suppress_stdout():
... print('Test print')
>>> print('test')
test
"""
save_stdout = sys.stdout
sys.stdout = DevNull()
yield
sys.stdout = save_stdout
def validate_url(url):
"""
Validate url using validators package.
Args:
url (str): Url.
Returns:
bool: True if valid, False otherwise.
Examples:
>>> validate_url('http://google.com')
True
>>> validate_url('http://google') # doctest: +ELLIPSIS
ValidationFailure(...)
>>> if not validate_url('http://google'):
... print('not valid')
not valid
"""
return validators.url(url)
def get_domain_name(url):
"""
Extract a domain name from the url (without subdomain).
Args:
url (str): Url.
Returns:
str: Domain name.
Raises:
DomainNotMatchedError: If url is wrong.
Examples:
>>> get_domain_name('https://vod.tvp.pl/video/')
'tvp.pl'
>>> get_domain_name('https://vod')
Traceback (most recent call last):
...
rtv.exceptions.WrongUrlError: Couldn't match domain name of this url: https://vod
"""
if not validate_url(url):
raise WrongUrlError(f'Couldn\'t match domain name of this url: {url}')
ext = tldextract.extract(url)
return f'{ext.domain}.{ext.suffix}'
def clean_title(title):
"""
Clean title -> remove dates, remove duplicated spaces and strip title.
Args:
title (str): Title.
Returns:
str: Clean title without dates, duplicated, trailing and leading spaces.
"""
date_pattern = re.compile(r'\W*'
r'\d{1,2}'
r'[/\-.]'
r'\d{1,2}'
r'[/\-.]'
r'(?=\d*)(?:.{4}|.{2})'
r'\W*')
title = date_pattern.sub(' ', title)
title = re.sub(r'\s{2,}', ' ', title)
title = title.strip()
return title
def clean_filename(filename):
"""
Remove unsupported filename characters.
On Windows file names cannot contain any of \/:*?"<>| characters.
Effectively remove all characters except alphanumeric, -_#.,() and spaces.
Args:
filename (str): Name of a file.
Returns:
str: Filename without unsupported characters.
"""
return re.sub('[^\w\-_#.,() ]', '', filename)
def file_exists(path):
"""
Check whether a file exists.
Args:
path (str): Path to a file.
Returns:
bool: True if exists, False otherwise.
"""
return os.path.exists(path)
def get_ext(url):
"""
Extract an extension from the url.
Args:
url (str): String representation of a url.
Returns:
str: Filename extension from a url (without a dot), '' if extension is not present.
"""
parsed = urllib.parse.urlparse(url)
root, ext = os.path.splitext(parsed.path)
return ext.lstrip('.')
def delete_duplicates(seq):
"""
Remove duplicates from an iterable, preserving the order.
Args:
seq: Iterable of various type.
Returns:
list: List of unique objects.
"""
seen = set()
seen_add = seen.add
return [x for x in seq if not (x in seen or seen_add(x))]
|
radzak/rtv-downloader
|
rtv/utils.py
|
clean_title
|
python
|
def clean_title(title):
date_pattern = re.compile(r'\W*'
r'\d{1,2}'
r'[/\-.]'
r'\d{1,2}'
r'[/\-.]'
r'(?=\d*)(?:.{4}|.{2})'
r'\W*')
title = date_pattern.sub(' ', title)
title = re.sub(r'\s{2,}', ' ', title)
title = title.strip()
return title
|
Clean title -> remove dates, remove duplicated spaces and strip title.
Args:
title (str): Title.
Returns:
str: Clean title without dates, duplicated, trailing and leading spaces.
|
train
|
https://github.com/radzak/rtv-downloader/blob/b9114b7f4c35fabe6ec9ad1764a65858667a866e/rtv/utils.py#L122-L143
| null |
import contextlib
import os
import re
import sys
import urllib.parse
import tldextract
import validators
from rtv.exceptions import WrongUrlError
class DevNull:
"""
DevNull class that has a no-op write and flush method.
"""
def write(self, *args, **kwargs):
pass
def flush(self):
pass
@contextlib.contextmanager
def suppress_stdout():
"""
Context manager that suppresses stdout.
Examples:
>>> with suppress_stdout():
... print('Test print')
>>> print('test')
test
"""
save_stdout = sys.stdout
sys.stdout = DevNull()
yield
sys.stdout = save_stdout
def validate_url(url):
"""
Validate url using validators package.
Args:
url (str): Url.
Returns:
bool: True if valid, False otherwise.
Examples:
>>> validate_url('http://google.com')
True
>>> validate_url('http://google') # doctest: +ELLIPSIS
ValidationFailure(...)
>>> if not validate_url('http://google'):
... print('not valid')
not valid
"""
return validators.url(url)
def get_domain_name(url):
"""
Extract a domain name from the url (without subdomain).
Args:
url (str): Url.
Returns:
str: Domain name.
Raises:
DomainNotMatchedError: If url is wrong.
Examples:
>>> get_domain_name('https://vod.tvp.pl/video/')
'tvp.pl'
>>> get_domain_name('https://vod')
Traceback (most recent call last):
...
rtv.exceptions.WrongUrlError: Couldn't match domain name of this url: https://vod
"""
if not validate_url(url):
raise WrongUrlError(f'Couldn\'t match domain name of this url: {url}')
ext = tldextract.extract(url)
return f'{ext.domain}.{ext.suffix}'
def clean_video_data(_data):
"""
Clean video data:
-> cleans title
-> ...
Args:
_data (dict): Information about the video.
Returns:
dict: Refined video data.
"""
data = _data.copy()
# TODO: fix this ugliness
title = data.get('title')
if title:
data['title'] = clean_title(title)
return data
def clean_filename(filename):
"""
Remove unsupported filename characters.
On Windows file names cannot contain any of \/:*?"<>| characters.
Effectively remove all characters except alphanumeric, -_#.,() and spaces.
Args:
filename (str): Name of a file.
Returns:
str: Filename without unsupported characters.
"""
return re.sub('[^\w\-_#.,() ]', '', filename)
def file_exists(path):
"""
Check whether a file exists.
Args:
path (str): Path to a file.
Returns:
bool: True if exists, False otherwise.
"""
return os.path.exists(path)
def get_ext(url):
"""
Extract an extension from the url.
Args:
url (str): String representation of a url.
Returns:
str: Filename extension from a url (without a dot), '' if extension is not present.
"""
parsed = urllib.parse.urlparse(url)
root, ext = os.path.splitext(parsed.path)
return ext.lstrip('.')
def delete_duplicates(seq):
"""
Remove duplicates from an iterable, preserving the order.
Args:
seq: Iterable of various type.
Returns:
list: List of unique objects.
"""
seen = set()
seen_add = seen.add
return [x for x in seq if not (x in seen or seen_add(x))]
|
radzak/rtv-downloader
|
rtv/utils.py
|
get_ext
|
python
|
def get_ext(url):
parsed = urllib.parse.urlparse(url)
root, ext = os.path.splitext(parsed.path)
return ext.lstrip('.')
|
Extract an extension from the url.
Args:
url (str): String representation of a url.
Returns:
str: Filename extension from a url (without a dot), '' if extension is not present.
|
train
|
https://github.com/radzak/rtv-downloader/blob/b9114b7f4c35fabe6ec9ad1764a65858667a866e/rtv/utils.py#L176-L190
| null |
import contextlib
import os
import re
import sys
import urllib.parse
import tldextract
import validators
from rtv.exceptions import WrongUrlError
class DevNull:
"""
DevNull class that has a no-op write and flush method.
"""
def write(self, *args, **kwargs):
pass
def flush(self):
pass
@contextlib.contextmanager
def suppress_stdout():
"""
Context manager that suppresses stdout.
Examples:
>>> with suppress_stdout():
... print('Test print')
>>> print('test')
test
"""
save_stdout = sys.stdout
sys.stdout = DevNull()
yield
sys.stdout = save_stdout
def validate_url(url):
"""
Validate url using validators package.
Args:
url (str): Url.
Returns:
bool: True if valid, False otherwise.
Examples:
>>> validate_url('http://google.com')
True
>>> validate_url('http://google') # doctest: +ELLIPSIS
ValidationFailure(...)
>>> if not validate_url('http://google'):
... print('not valid')
not valid
"""
return validators.url(url)
def get_domain_name(url):
"""
Extract a domain name from the url (without subdomain).
Args:
url (str): Url.
Returns:
str: Domain name.
Raises:
DomainNotMatchedError: If url is wrong.
Examples:
>>> get_domain_name('https://vod.tvp.pl/video/')
'tvp.pl'
>>> get_domain_name('https://vod')
Traceback (most recent call last):
...
rtv.exceptions.WrongUrlError: Couldn't match domain name of this url: https://vod
"""
if not validate_url(url):
raise WrongUrlError(f'Couldn\'t match domain name of this url: {url}')
ext = tldextract.extract(url)
return f'{ext.domain}.{ext.suffix}'
def clean_video_data(_data):
"""
Clean video data:
-> cleans title
-> ...
Args:
_data (dict): Information about the video.
Returns:
dict: Refined video data.
"""
data = _data.copy()
# TODO: fix this ugliness
title = data.get('title')
if title:
data['title'] = clean_title(title)
return data
def clean_title(title):
"""
Clean title -> remove dates, remove duplicated spaces and strip title.
Args:
title (str): Title.
Returns:
str: Clean title without dates, duplicated, trailing and leading spaces.
"""
date_pattern = re.compile(r'\W*'
r'\d{1,2}'
r'[/\-.]'
r'\d{1,2}'
r'[/\-.]'
r'(?=\d*)(?:.{4}|.{2})'
r'\W*')
title = date_pattern.sub(' ', title)
title = re.sub(r'\s{2,}', ' ', title)
title = title.strip()
return title
def clean_filename(filename):
"""
Remove unsupported filename characters.
On Windows file names cannot contain any of \/:*?"<>| characters.
Effectively remove all characters except alphanumeric, -_#.,() and spaces.
Args:
filename (str): Name of a file.
Returns:
str: Filename without unsupported characters.
"""
return re.sub('[^\w\-_#.,() ]', '', filename)
def file_exists(path):
"""
Check whether a file exists.
Args:
path (str): Path to a file.
Returns:
bool: True if exists, False otherwise.
"""
return os.path.exists(path)
def delete_duplicates(seq):
"""
Remove duplicates from an iterable, preserving the order.
Args:
seq: Iterable of various type.
Returns:
list: List of unique objects.
"""
seen = set()
seen_add = seen.add
return [x for x in seq if not (x in seen or seen_add(x))]
|
radzak/rtv-downloader
|
rtv/utils.py
|
delete_duplicates
|
python
|
def delete_duplicates(seq):
seen = set()
seen_add = seen.add
return [x for x in seq if not (x in seen or seen_add(x))]
|
Remove duplicates from an iterable, preserving the order.
Args:
seq: Iterable of various type.
Returns:
list: List of unique objects.
|
train
|
https://github.com/radzak/rtv-downloader/blob/b9114b7f4c35fabe6ec9ad1764a65858667a866e/rtv/utils.py#L193-L206
| null |
import contextlib
import os
import re
import sys
import urllib.parse
import tldextract
import validators
from rtv.exceptions import WrongUrlError
class DevNull:
"""
DevNull class that has a no-op write and flush method.
"""
def write(self, *args, **kwargs):
pass
def flush(self):
pass
@contextlib.contextmanager
def suppress_stdout():
"""
Context manager that suppresses stdout.
Examples:
>>> with suppress_stdout():
... print('Test print')
>>> print('test')
test
"""
save_stdout = sys.stdout
sys.stdout = DevNull()
yield
sys.stdout = save_stdout
def validate_url(url):
"""
Validate url using validators package.
Args:
url (str): Url.
Returns:
bool: True if valid, False otherwise.
Examples:
>>> validate_url('http://google.com')
True
>>> validate_url('http://google') # doctest: +ELLIPSIS
ValidationFailure(...)
>>> if not validate_url('http://google'):
... print('not valid')
not valid
"""
return validators.url(url)
def get_domain_name(url):
"""
Extract a domain name from the url (without subdomain).
Args:
url (str): Url.
Returns:
str: Domain name.
Raises:
DomainNotMatchedError: If url is wrong.
Examples:
>>> get_domain_name('https://vod.tvp.pl/video/')
'tvp.pl'
>>> get_domain_name('https://vod')
Traceback (most recent call last):
...
rtv.exceptions.WrongUrlError: Couldn't match domain name of this url: https://vod
"""
if not validate_url(url):
raise WrongUrlError(f'Couldn\'t match domain name of this url: {url}')
ext = tldextract.extract(url)
return f'{ext.domain}.{ext.suffix}'
def clean_video_data(_data):
"""
Clean video data:
-> cleans title
-> ...
Args:
_data (dict): Information about the video.
Returns:
dict: Refined video data.
"""
data = _data.copy()
# TODO: fix this ugliness
title = data.get('title')
if title:
data['title'] = clean_title(title)
return data
def clean_title(title):
"""
Clean title -> remove dates, remove duplicated spaces and strip title.
Args:
title (str): Title.
Returns:
str: Clean title without dates, duplicated, trailing and leading spaces.
"""
date_pattern = re.compile(r'\W*'
r'\d{1,2}'
r'[/\-.]'
r'\d{1,2}'
r'[/\-.]'
r'(?=\d*)(?:.{4}|.{2})'
r'\W*')
title = date_pattern.sub(' ', title)
title = re.sub(r'\s{2,}', ' ', title)
title = title.strip()
return title
def clean_filename(filename):
"""
Remove unsupported filename characters.
On Windows file names cannot contain any of \/:*?"<>| characters.
Effectively remove all characters except alphanumeric, -_#.,() and spaces.
Args:
filename (str): Name of a file.
Returns:
str: Filename without unsupported characters.
"""
return re.sub('[^\w\-_#.,() ]', '', filename)
def file_exists(path):
"""
Check whether a file exists.
Args:
path (str): Path to a file.
Returns:
bool: True if exists, False otherwise.
"""
return os.path.exists(path)
def get_ext(url):
"""
Extract an extension from the url.
Args:
url (str): String representation of a url.
Returns:
str: Filename extension from a url (without a dot), '' if extension is not present.
"""
parsed = urllib.parse.urlparse(url)
root, ext = os.path.splitext(parsed.path)
return ext.lstrip('.')
|
radzak/rtv-downloader
|
rtv/extractors/vodtvp.py
|
VodTVP.get_show_name
|
python
|
def get_show_name(self):
div = self.soup.find('div', attrs={'data-hover': True})
data = json.loads(div['data-hover'])
show_name = data.get('title')
return show_name
|
Get video show name from the website. It's located in the div with 'data-hover'
attribute under the 'title' key.
Returns:
str: Video show name.
|
train
|
https://github.com/radzak/rtv-downloader/blob/b9114b7f4c35fabe6ec9ad1764a65858667a866e/rtv/extractors/vodtvp.py#L43-L56
| null |
class VodTVP(Extractor):
SITE_NAME = 'vod.tvp.pl'
_VALID_URL = (
r'https?://(?:www\.)?vod.tvp\.pl/'
r'.*?'
r'(?:,(?P<date>[\d\-]+))?'
r','
r'(?P<object_id>\d+)'
)
# TODO: change _VALID_URLs to just plain domain name and move date, showname, etc. regexes
# to functions, so the downloader matches the url despite of absence of additional
# parameters in the url then the get_x functions will just return None and the Formatter
# will take care of default values
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.load_html()
self.soup = BeautifulSoup(self.html, 'lxml')
def get_date(self):
match = re.match(self._VALID_URL, self.url)
date_str = match.group('date')
date_formats = [
'%d%m%Y',
'%d%m%Y-%H%M'
]
for d in date_formats:
try:
return datetime.datetime.strptime(date_str, d)
except (ValueError, AttributeError):
pass
def get_title(self):
"""
Get Video title from the website. It's located in the div with 'data-hover'
attribute under the 'episodeCount' key.
Returns:
str: Video title.
"""
# considered as a worse solution since most of the videos have only date in the title
# soup = BeautifulSoup(self.html, 'lxml')
# div = soup.find('div', attrs={'data-hover': True})
# data = json.loads(div['data-hover'])
# title = data.get('episodeCount')
# TODO: _og_search_title/_og_search_description common method
title = self.soup.find('meta', {'property': 'og:title'})['content']
return title
def get_description(self):
"""
Get video description from the website. It's located in the meta tag
with 'og:description' attribute under 'content' attribute.
Returns:
str: Video description.
"""
description = self.soup.find('meta', {'property': 'og:description'})['content']
return description
def extract(self):
entries = [{
'title': self.get_title(),
'show_name': self.get_show_name(),
'description': self.get_description(),
'date': self.get_date(),
'url': self.url,
'ext': 'mp4'
}]
return entries
|
radzak/rtv-downloader
|
rtv/extractors/common.py
|
Extractor.validate_url
|
python
|
def validate_url(cls, url: str) -> Optional[Match[str]]:
match = re.match(cls._VALID_URL, url)
return match
|
Check if the Extractor can handle the given url.
|
train
|
https://github.com/radzak/rtv-downloader/blob/b9114b7f4c35fabe6ec9ad1764a65858667a866e/rtv/extractors/common.py#L29-L32
| null |
class Extractor:
SITE_NAME: ClassVar[str]
_VALID_URL: ClassVar[str]
url: str
html: str
videos: List[Video]
response: requests.models.Response
def __init__(self, url: str) -> None:
self.url = url
self.videos = []
@classmethod
def load_html(self) -> None:
r = requests.get(self.url)
r.encoding = 'utf-8'
self.response = r
self.html = r.text
def get_info(self) -> dict:
"""Get information about the videos from YoutubeDL package."""
with suppress_stdout():
with youtube_dl.YoutubeDL() as ydl:
info_dict = ydl.extract_info(self.url, download=False)
return info_dict
@staticmethod
def update_entries(entries: Entries, data: dict) -> None:
"""Update each entry in the list with some data."""
# TODO: Is mutating the list okay, making copies is such a pain in the ass
for entry in entries:
entry.update(data)
def extract(self) -> Entries:
"""Extract data from the url. Redefine in subclasses."""
raise NotImplementedError('This method must be implemented by subclasses')
def run(self) -> None:
entries = self.extract()
self.update_entries(entries, {
'site': get_domain_name(self.url)
})
if not isinstance(entries, list):
raise TypeError('extract method must return an iterable of dictionaries')
for entry in entries:
video = Video(entry)
self.videos.append(video)
|
radzak/rtv-downloader
|
rtv/extractors/common.py
|
Extractor.get_info
|
python
|
def get_info(self) -> dict:
with suppress_stdout():
with youtube_dl.YoutubeDL() as ydl:
info_dict = ydl.extract_info(self.url, download=False)
return info_dict
|
Get information about the videos from YoutubeDL package.
|
train
|
https://github.com/radzak/rtv-downloader/blob/b9114b7f4c35fabe6ec9ad1764a65858667a866e/rtv/extractors/common.py#L40-L45
| null |
class Extractor:
SITE_NAME: ClassVar[str]
_VALID_URL: ClassVar[str]
url: str
html: str
videos: List[Video]
response: requests.models.Response
def __init__(self, url: str) -> None:
self.url = url
self.videos = []
@classmethod
def validate_url(cls, url: str) -> Optional[Match[str]]:
"""Check if the Extractor can handle the given url."""
match = re.match(cls._VALID_URL, url)
return match
def load_html(self) -> None:
r = requests.get(self.url)
r.encoding = 'utf-8'
self.response = r
self.html = r.text
@staticmethod
def update_entries(entries: Entries, data: dict) -> None:
"""Update each entry in the list with some data."""
# TODO: Is mutating the list okay, making copies is such a pain in the ass
for entry in entries:
entry.update(data)
def extract(self) -> Entries:
"""Extract data from the url. Redefine in subclasses."""
raise NotImplementedError('This method must be implemented by subclasses')
def run(self) -> None:
entries = self.extract()
self.update_entries(entries, {
'site': get_domain_name(self.url)
})
if not isinstance(entries, list):
raise TypeError('extract method must return an iterable of dictionaries')
for entry in entries:
video = Video(entry)
self.videos.append(video)
|
radzak/rtv-downloader
|
rtv/extractors/common.py
|
Extractor.update_entries
|
python
|
def update_entries(entries: Entries, data: dict) -> None:
# TODO: Is mutating the list okay, making copies is such a pain in the ass
for entry in entries:
entry.update(data)
|
Update each entry in the list with some data.
|
train
|
https://github.com/radzak/rtv-downloader/blob/b9114b7f4c35fabe6ec9ad1764a65858667a866e/rtv/extractors/common.py#L48-L52
| null |
class Extractor:
SITE_NAME: ClassVar[str]
_VALID_URL: ClassVar[str]
url: str
html: str
videos: List[Video]
response: requests.models.Response
def __init__(self, url: str) -> None:
self.url = url
self.videos = []
@classmethod
def validate_url(cls, url: str) -> Optional[Match[str]]:
"""Check if the Extractor can handle the given url."""
match = re.match(cls._VALID_URL, url)
return match
def load_html(self) -> None:
r = requests.get(self.url)
r.encoding = 'utf-8'
self.response = r
self.html = r.text
def get_info(self) -> dict:
"""Get information about the videos from YoutubeDL package."""
with suppress_stdout():
with youtube_dl.YoutubeDL() as ydl:
info_dict = ydl.extract_info(self.url, download=False)
return info_dict
@staticmethod
def extract(self) -> Entries:
"""Extract data from the url. Redefine in subclasses."""
raise NotImplementedError('This method must be implemented by subclasses')
def run(self) -> None:
entries = self.extract()
self.update_entries(entries, {
'site': get_domain_name(self.url)
})
if not isinstance(entries, list):
raise TypeError('extract method must return an iterable of dictionaries')
for entry in entries:
video = Video(entry)
self.videos.append(video)
|
radzak/rtv-downloader
|
rtv/extractors/rmf24.py
|
Rmf24.extract_entry
|
python
|
def extract_entry(scraped_info):
quality_mapping = { # ascending in terms of quality
'lo': 0,
'hi': 1
}
entry = scraped_info['tracks'][0]
'''
The structure of entry is as follows:
'src': {
'hi': [
{
'src': 'http://v.iplsc.com/30-11-gosc-marek-jakubiak/0007124B3CGCAE6P-A1.mp4',
'type': 'video/mp4'
}
],
'lo': [
{
'src': 'http://v.iplsc.com/30-11-gosc-marek-jakubiak/0007124B3CGCAE6P-A1.mp4',
'type': 'video/mp4'
}
]
}
'''
sources = entry.pop('src')
# TODO: #LOW_PRIOR Remove date from title of audio files e.g. '10.06 Gość: Jarosław Gowin'
formats = []
for src_name, src in sources.items():
url = src[0]['src']
formats.append({
'url': url,
'quality': quality_mapping[src_name],
'ext': get_ext(url),
'width': int(scraped_info.get('width', 0)),
'height': int(scraped_info.get('height', 0)),
})
# outer level url and ext come from the video of the lowest quality
# you can access rest of the urls under 'formats' key
worst_format = min(formats, key=lambda f: f['quality'])
entry.update({
**entry.pop('data'),
'formats': formats,
'url': worst_format['url'],
'ext': worst_format['ext']
})
return entry
|
Transform scraped_info dictionary into an entry, under the assumption that there is only
one track in 'track' list, since each video/audio is instantiated individually
on the RMF website and each of them is scraped independently, so there shouldn't be cases
when there are 2 unrelated tracks in one info_dict.
Args:
scraped_info (dict): Video info dict, scraped straight from the website.
Returns:
dict: Entry containing title, formats (url, quality), thumbnail, etc.
|
train
|
https://github.com/radzak/rtv-downloader/blob/b9114b7f4c35fabe6ec9ad1764a65858667a866e/rtv/extractors/rmf24.py#L32-L96
|
[
"def get_ext(url):\n \"\"\"\n Extract an extension from the url.\n\n Args:\n url (str): String representation of a url.\n\n Returns:\n str: Filename extension from a url (without a dot), '' if extension is not present.\n\n \"\"\"\n\n parsed = urllib.parse.urlparse(url)\n root, ext = os.path.splitext(parsed.path)\n return ext.lstrip('.')\n"
] |
class Rmf24(GenericTitleMixin, GenericDescriptionMixin, Extractor):
SITE_NAME = 'rmf24.pl'
_VALID_URL = r'https?://(?:www\.)?rmf24\.pl/'
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.load_html()
self.soup = BeautifulSoup(self.html, 'lxml')
# TODO: use decorators to mark the need to use bs4?
# TODO: make_soup(html=Optional) or/and load_html(url=Optional)
def get_date(self) -> Optional[datetime]:
meta_tag = self.soup.select_one('meta[itemprop=datePublished]')
if meta_tag:
date_published_str = meta_tag.get('content')
return datetime.strptime(date_published_str, '%Y-%m-%dT%H:%M:%S')
return None
@staticmethod
def _scrape_entries(self):
entries = []
pattern = re.compile(r'Video.createInstance\((?P<js_object>{.*?})\);', re.DOTALL)
scripts = self.soup.findAll('script', text=pattern)
for script in scripts:
matches = pattern.findall(script.text)
for data in matches: # matches is a list of matched strings, not match objects
info_dict = js2py.eval_js(f'Object({data})').to_dict()
entries.append(self.extract_entry(info_dict))
# temporarily return only audio entries if present, otherwise return all video entries
audio_entries = [e for e in entries if e.get('type', 'video') == 'audio']
if audio_entries:
entries = audio_entries
return entries
def extract(self):
audio_url = self._get_audio_source_url()
extension = get_ext(audio_url)
entries = [{
'title': self.get_title(),
'description': self.get_description(),
'date': self.get_date(),
'url': audio_url,
'ext': extension
}]
return entries
|
radzak/rtv-downloader
|
rtv/extractors/tokfm.py
|
TokFm._extract_id
|
python
|
def _extract_id(self) -> str:
match = re.match(self._VALID_URL, self.url)
if match:
return match.group('video_id')
else:
raise VideoIdNotMatchedError
|
Get video_id needed to obtain the real_url of the video.
Raises:
VideoIdNotMatchedError: If video_id is not matched with regular expression.
|
train
|
https://github.com/radzak/rtv-downloader/blob/b9114b7f4c35fabe6ec9ad1764a65858667a866e/rtv/extractors/tokfm.py#L35-L48
| null |
class TokFm(GenericTitleMixin, GenericDescriptionMixin, Extractor):
SITE_NAME = 'tokfm.pl'
_VALID_URL = r'https?://(?:www\.)?audycje\.tokfm\.pl/.*/(?P<video_id>[a-z0-9-]*)'
VideoInfo = namedtuple('VideoInfo', ('date', 'showname', 'host', 'guests'))
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
self.load_html()
self.soup = BeautifulSoup(self.html, 'lxml')
self.video_id = self._extract_id()
self.info = self._scrape_info()
def get_real_url(self) -> str:
data = {'pid': self.video_id, 'st': 'tokfm'}
r = requests.post('http://audycje.tokfm.pl/gets',
data=json.dumps(data),
cookies=self.response.cookies)
url = json.loads(r.text)['url']
return url
@staticmethod
def _process_info(raw_info: VideoInfo) -> VideoInfo:
"""Process raw information about the video (parse date, etc.)."""
raw_date = raw_info.date
date = datetime.strptime(raw_date, '%Y-%m-%d %H:%M') # 2018-04-05 17:00
video_info = raw_info._replace(date=date)
return video_info
def _scrape_info(self) -> VideoInfo:
rows = self.soup.select('.tok-divTableRow')[:-2] # omit duration SocialMedia links
cells = [row.select('.tok-divTableCell')[1] for row in rows]
cells[1].find('span').decompose() # delete "Obserwuj" text
# TODO: Guests have too much spaces between each guest
# http://audycje.tokfm.pl/podcast/KRS-wybiera-nowych-sedziow-Sadu-Najwyzszego-Kaminski-Intencje-od-poczatku-byly-jasne-i-od-poczatku-byly-zle/66219
data = [cell.get_text(strip=True) for cell in cells]
raw_info = self.VideoInfo(*data)
video_info = self._process_info(raw_info)
return video_info
def extract(self) -> Entries:
entries = [{
**self.info._asdict(),
'title': self.get_title(),
'description': self.get_description(),
'url': self.get_real_url(),
'ext': 'mp3'
}]
return entries
|
radzak/rtv-downloader
|
rtv/extractors/tokfm.py
|
TokFm._process_info
|
python
|
def _process_info(raw_info: VideoInfo) -> VideoInfo:
raw_date = raw_info.date
date = datetime.strptime(raw_date, '%Y-%m-%d %H:%M') # 2018-04-05 17:00
video_info = raw_info._replace(date=date)
return video_info
|
Process raw information about the video (parse date, etc.).
|
train
|
https://github.com/radzak/rtv-downloader/blob/b9114b7f4c35fabe6ec9ad1764a65858667a866e/rtv/extractors/tokfm.py#L51-L56
| null |
class TokFm(GenericTitleMixin, GenericDescriptionMixin, Extractor):
SITE_NAME = 'tokfm.pl'
_VALID_URL = r'https?://(?:www\.)?audycje\.tokfm\.pl/.*/(?P<video_id>[a-z0-9-]*)'
VideoInfo = namedtuple('VideoInfo', ('date', 'showname', 'host', 'guests'))
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
self.load_html()
self.soup = BeautifulSoup(self.html, 'lxml')
self.video_id = self._extract_id()
self.info = self._scrape_info()
def get_real_url(self) -> str:
data = {'pid': self.video_id, 'st': 'tokfm'}
r = requests.post('http://audycje.tokfm.pl/gets',
data=json.dumps(data),
cookies=self.response.cookies)
url = json.loads(r.text)['url']
return url
def _extract_id(self) -> str:
"""
Get video_id needed to obtain the real_url of the video.
Raises:
VideoIdNotMatchedError: If video_id is not matched with regular expression.
"""
match = re.match(self._VALID_URL, self.url)
if match:
return match.group('video_id')
else:
raise VideoIdNotMatchedError
@staticmethod
def _scrape_info(self) -> VideoInfo:
rows = self.soup.select('.tok-divTableRow')[:-2] # omit duration SocialMedia links
cells = [row.select('.tok-divTableCell')[1] for row in rows]
cells[1].find('span').decompose() # delete "Obserwuj" text
# TODO: Guests have too much spaces between each guest
# http://audycje.tokfm.pl/podcast/KRS-wybiera-nowych-sedziow-Sadu-Najwyzszego-Kaminski-Intencje-od-poczatku-byly-jasne-i-od-poczatku-byly-zle/66219
data = [cell.get_text(strip=True) for cell in cells]
raw_info = self.VideoInfo(*data)
video_info = self._process_info(raw_info)
return video_info
def extract(self) -> Entries:
entries = [{
**self.info._asdict(),
'title': self.get_title(),
'description': self.get_description(),
'url': self.get_real_url(),
'ext': 'mp3'
}]
return entries
|
radzak/rtv-downloader
|
rtv/downloaders/common.py
|
VideoDownloader.render_path
|
python
|
def render_path(self) -> str:
# TODO: Fix defaults when date is not found (empty string or None)
# https://stackoverflow.com/questions/23407295/default-kwarg-values-for-pythons-str-format-method
from string import Formatter
class UnseenFormatter(Formatter):
def get_value(self, key, args, kwds):
if isinstance(key, str):
try:
return kwds[key]
except KeyError:
return key
else:
return super().get_value(key, args, kwds)
data = self.video.data
site_name = data['site']
try:
template = self.templates[site_name]
except KeyError:
raise NoTemplateFoundError
fmt = UnseenFormatter()
filename_raw = fmt.format(template, **data)
filename = clean_filename(filename_raw)
path = os.path.join(self.download_dir, filename)
return path
|
Render path by filling the path template with video information.
|
train
|
https://github.com/radzak/rtv-downloader/blob/b9114b7f4c35fabe6ec9ad1764a65858667a866e/rtv/downloaders/common.py#L37-L66
|
[
"def clean_filename(filename):\n \"\"\"\n Remove unsupported filename characters.\n On Windows file names cannot contain any of \\/:*?\"<>| characters.\n Effectively remove all characters except alphanumeric, -_#.,() and spaces.\n\n Args:\n filename (str): Name of a file.\n\n Returns:\n str: Filename without unsupported characters.\n\n \"\"\"\n return re.sub('[^\\w\\-_#.,() ]', '', filename)\n"
] |
class VideoDownloader:
def __init__(self, video, quality=None, download_dir=None, templates=None) -> None:
"""
Create a VideoDownloader for a given video.
Args:
video (Video): Video object.
quality (str): Quality of the video (best/worst). Audio quality defaults to best.
download_dir (str): Destination directory for the downloaded video.
templates (dict): Dictionary of templates needed to generate a download path.
"""
self.video = video
self.quality = quality or DEFAULT_OPTIONS['quality']
self.download_dir = download_dir or DEFAULT_OPTIONS['download_dir']
self.templates = templates or DEFAULT_OPTIONS['templates']
if self.quality not in ('worst', 'best'):
raise WrongQualityError
def _real_download(self, path) -> None:
"""Real download process. Redefine in subclasses."""
raise NotImplementedError('This method must be implemented by subclasses')
def download(self) -> None:
"""Download video to target location. Choose worst quality by default, to decrease file size."""
path = self.render_path()
self._real_download(path)
|
radzak/rtv-downloader
|
rtv/onetab.py
|
get_urls_from_onetab
|
python
|
def get_urls_from_onetab(onetab):
html = requests.get(onetab).text
soup = BeautifulSoup(html, 'lxml')
divs = soup.findAll('div', {'style': 'padding-left: 24px; '
'padding-top: 8px; '
'position: relative; '
'font-size: 13px;'})
return [div.find('a').attrs['href'] for div in divs]
|
Get video urls from a link to the onetab shared page.
Args:
onetab (str): Link to a onetab shared page.
Returns:
list: List of links to the videos.
|
train
|
https://github.com/radzak/rtv-downloader/blob/b9114b7f4c35fabe6ec9ad1764a65858667a866e/rtv/onetab.py#L5-L24
| null |
import requests
from bs4 import BeautifulSoup
|
radzak/rtv-downloader
|
rtv/extractors/wp.py
|
Wp.quality_comparator
|
python
|
def quality_comparator(video_data):
def parse_resolution(res: str) -> Tuple[int, ...]:
return tuple(map(int, res.split('x')))
raw_resolution = video_data['resolution']
resolution = parse_resolution(raw_resolution)
return resolution
|
Custom comparator used to choose the right format based on the resolution.
|
train
|
https://github.com/radzak/rtv-downloader/blob/b9114b7f4c35fabe6ec9ad1764a65858667a866e/rtv/extractors/wp.py#L56-L63
|
[
"def parse_resolution(res: str) -> Tuple[int, ...]:\n return tuple(map(int, res.split('x')))\n"
] |
class Wp(Extractor):
SITE_NAME = 'wp.pl'
_VALID_URL = r'https?://(?:www\.)?video\.wp\.pl/.*'
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
self.load_html()
self.soup = BeautifulSoup(self.html, 'lxml')
self.data = self._fetch_data()
@staticmethod
def _get_json_url(mid: int) -> str:
json_url = f'https://video.wp.pl/api/v1/embed/{mid}'
return json_url
def _fetch_data(self):
mid = self.soup.select_one('#mainPlayer')['data-mid']
json_url = self._get_json_url(mid)
video_data = requests.get(json_url).json()['clip']
return video_data
def get_title(self) -> Optional[str]:
title = self.data.get('title')
return title
def get_description(self) -> Optional[str]:
description = self.data.get('description')
return description
def get_tags(self) -> List[str]:
tags = self.data.get('tags', '').split(',')
return tags
def get_show_name(self) -> Optional[str]:
show_name = self.data['media'].get('program')
return show_name
def get_date(self) -> Optional[datetime]:
raw_date = self.data['media'].get('createDate')
if raw_date:
date = dateparser.parse(raw_date)
return date
return None
@staticmethod
# e.g (1024, 576)
def get_real_url(self) -> str:
formats = list(filter(lambda d: d['type'] == 'mp4@avc', self.data['url'])) # filter out mp4
worst_format = min(formats, key=self.quality_comparator) # for now take the lowest quality
url = worst_format['url']
return url
def extract(self) -> Entries:
entries = [{
'title': self.get_title(),
'description': self.get_description(),
'tags': self.get_tags(),
'show_name': self.get_show_name(),
'date': self.get_date(),
'url': self.get_real_url(),
'ext': 'mp4'
}]
return entries
|
radzak/rtv-downloader
|
rtv/options.py
|
parse_options
|
python
|
def parse_options():
parser = argparse.ArgumentParser(description='Video downloader by radzak.',
prog='RTVdownloader')
urls_group = parser.add_mutually_exclusive_group(required=True)
urls_group.add_argument('urls',
type=str,
metavar='URL',
default=[],
nargs='*',
help='urls of sites containing videos you wish to download'
)
urls_group.add_argument('-f',
type=argparse.FileType('r'),
dest='files',
metavar='FILE',
default=[],
nargs='*',
help='text file with urls of sites containing videos you '
'wish to download '
)
urls_group.add_argument('-o',
type=str,
dest='onetabs',
metavar='ONETAB',
default=[],
nargs='*',
help='onetab links containing urls of the videos you wish to download'
)
options = DEFAULT_OPTIONS
# TODO: add dir option that defaults to the DEFAULT_OPTIONS['dl_path']
args = parser.parse_args()
return options, args
|
Parse command line arguments.
Returns:
options, args
|
train
|
https://github.com/radzak/rtv-downloader/blob/b9114b7f4c35fabe6ec9ad1764a65858667a866e/rtv/options.py#L24-L67
| null |
import argparse
from pathlib import Path
DEFAULT_OPTIONS = {
'download_dir': Path.home() / 'Desktop' / 'RTV',
'templates': {
'ipla.tv': '{date:%d} {title}.{ext}',
'polsatnews.pl': '{date:%d} {title}.{ext}',
'polskieradio.pl': '{date:%d} {title}.{ext}',
'radiozet.pl': '{date:%d} {show_name} - {title}.{ext}',
'rmf24.pl': '{date:%d} {title}.{ext}',
'tokfm.pl': '{date:%d} {title}.{ext}',
'tvn24.pl': '{date:%d} {title}.{ext}',
'tvp.info': '{date:%d} {title}.{ext}',
'tvp.pl': '{date:%d} {title}.{ext}',
'tvpparlament.pl': '{date:%d} {title}.{ext}',
'vod.pl': '{date:%d} {show_name} - {title}.{ext}',
'wp.pl': '{date:%d} {show_name} - {title}.{ext}'
},
'quality': 'worst'
}
|
radzak/rtv-downloader
|
rtv/extractors/tvpinfo.py
|
TvpInfo.get_article_url
|
python
|
def get_article_url(self):
html = requests.get(self.url).text
soup = BeautifulSoup(html, 'lxml')
div = soup.find('div', class_='more-back')
if div:
parsed_uri = urlparse(self.url)
domain = '{uri.scheme}://{uri.netloc}'.format(uri=parsed_uri)
suffix = div.find('a', href=True)['href'].strip()
article_url = domain + suffix
return article_url
else:
return self.url
|
Get the url of the TVP Info article itself, not the url of the preview with
the 'Przejdź do artykułu' hyperlink.
Returns:
(str): Url of the article with the video.
|
train
|
https://github.com/radzak/rtv-downloader/blob/b9114b7f4c35fabe6ec9ad1764a65858667a866e/rtv/extractors/tvpinfo.py#L39-L59
| null |
class TvpInfo(Extractor):
SITE_NAME = 'tvp.info'
_VALID_URL = r'https?://(?:www\.)?tvp\.info/'
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.url = self.get_article_url()
# some data will be scraped from the article page
self.load_html()
self.soup = BeautifulSoup(self.html, 'lxml')
# and some data will be scraped from the player page
self.video_id = self._extract_id()
self.player_url = self.get_player_url()
self.player_html = requests.get(self.player_url).text
self.player_soup = BeautifulSoup(self.player_html, 'lxml')
def _extract_id(self):
pattern = re.compile(r'object_id=(?P<id>\d+)')
match = pattern.search(self.html)
if match:
return match.group('id')
else:
raise VideoIdNotMatchedError
def get_player_url(self):
"""
Get the url of the page containing embedded video player. The html of that page contains
more detailed data about the video than the article page.
"""
return f'http://www.tvp.info/sess/tvplayer.php?object_id={self.video_id}'
def get_date(self):
span = self.soup.find('span', class_='date')
if span:
date_str = span.text
return dateparser.parse(date_str)
def get_title(self):
title = self.player_soup.find('meta', {'property': 'og:title'})['content']
return title
def get_showname(self):
pattern = re.compile(
r'\"SeriesTitle\",'
r'\s*value:\s*'
r'\"(?P<showname>.*?)\"'
)
match = pattern.search(self.player_html)
if match:
showname = match.group('showname')
return showname or None
def get_description(self):
description = self.player_soup.find('meta', {'property': 'og:description'})['content']
return description
def extract(self):
entries = [{
'title': self.get_title(),
'showname': self.get_showname(),
'description:': self.get_description(),
'date': self.get_date(),
'url': self.url,
'ext': 'mp4',
}]
return entries
|
elemoine/papyrus
|
papyrus/xsd.py
|
XSDGenerator.add_column_xsd
|
python
|
def add_column_xsd(self, tb, column, attrs):
if column.nullable:
attrs['minOccurs'] = str(0)
attrs['nillable'] = 'true'
for cls, xsd_type in six.iteritems(self.SIMPLE_XSD_TYPES):
if isinstance(column.type, cls):
attrs['type'] = xsd_type
with tag(tb, 'xsd:element', attrs) as tb:
self.element_callback(tb, column)
return tb
if isinstance(column.type, Geometry):
geometry_type = column.type.geometry_type
xsd_type = self.SIMPLE_GEOMETRY_XSD_TYPES[geometry_type]
attrs['type'] = xsd_type
with tag(tb, 'xsd:element', attrs) as tb:
self.element_callback(tb, column)
return tb
if isinstance(column.type, sqlalchemy.Enum):
with tag(tb, 'xsd:element', attrs) as tb:
with tag(tb, 'xsd:simpleType') as tb:
with tag(tb, 'xsd:restriction', {'base': 'xsd:string'}) \
as tb:
for enum in column.type.enums:
with tag(tb, 'xsd:enumeration', {'value': enum}):
pass
self.element_callback(tb, column)
return tb
if isinstance(column.type, sqlalchemy.Numeric):
if column.type.scale is None and column.type.precision is None:
attrs['type'] = 'xsd:decimal'
with tag(tb, 'xsd:element', attrs) as tb:
self.element_callback(tb, column)
return tb
else:
with tag(tb, 'xsd:element', attrs) as tb:
with tag(tb, 'xsd:simpleType') as tb:
with tag(tb, 'xsd:restriction',
{'base': 'xsd:decimal'}) as tb:
if column.type.scale is not None:
with tag(tb, 'xsd:fractionDigits',
{'value': str(column.type.scale)}) \
as tb:
pass
if column.type.precision is not None:
precision = column.type.precision
with tag(tb, 'xsd:totalDigits',
{'value': str(precision)}) \
as tb:
pass
self.element_callback(tb, column)
return tb
if isinstance(column.type, sqlalchemy.String) \
or isinstance(column.type, sqlalchemy.Text) \
or isinstance(column.type, sqlalchemy.Unicode) \
or isinstance(column.type, sqlalchemy.UnicodeText):
if column.type.length is None:
attrs['type'] = 'xsd:string'
with tag(tb, 'xsd:element', attrs) as tb:
self.element_callback(tb, column)
return tb
else:
with tag(tb, 'xsd:element', attrs) as tb:
with tag(tb, 'xsd:simpleType') as tb:
with tag(tb, 'xsd:restriction',
{'base': 'xsd:string'}) as tb:
with tag(tb, 'xsd:maxLength',
{'value': str(column.type.length)}):
pass
self.element_callback(tb, column)
return tb
raise UnsupportedColumnTypeError(column.type)
|
Add the XSD for a column to tb (a TreeBuilder)
|
train
|
https://github.com/elemoine/papyrus/blob/764fb2326105df74fbd3dbcd7e58f4cb21956005/papyrus/xsd.py#L73-L144
|
[
"def element_callback(self, tb, column):\n pass\n"
] |
class XSDGenerator(object):
""" XSD Generator """
SIMPLE_XSD_TYPES = {
# SQLAlchemy types
sqlalchemy.BigInteger: 'xsd:integer',
sqlalchemy.Boolean: 'xsd:boolean',
sqlalchemy.Date: 'xsd:date',
sqlalchemy.DateTime: 'xsd:dateTime',
sqlalchemy.Float: 'xsd:double',
sqlalchemy.Integer: 'xsd:integer',
sqlalchemy.Interval: 'xsd:duration',
sqlalchemy.LargeBinary: 'xsd:base64Binary',
sqlalchemy.PickleType: 'xsd:base64Binary',
sqlalchemy.SmallInteger: 'xsd:integer',
sqlalchemy.Time: 'xsd:time',
}
SIMPLE_GEOMETRY_XSD_TYPES = {
# GeoAlchemy types
'CURVE': 'gml:CurvePropertyType',
'GEOMETRYCOLLECTION': 'gml:GeometryCollectionPropertyType',
'LINESTRING': 'gml:LineStringPropertyType',
'MULTILINESTRING': 'gml:MultiLineStringPropertyType',
'MULTIPOINT': 'gml:MultiPointPropertyType',
'MULTIPOLYGON': 'gml:MultiPolygonPropertyType',
'POINT': 'gml:PointPropertyType',
'POLYGON': 'gml:PolygonPropertyType',
}
def __init__(self,
include_primary_keys=False,
include_foreign_keys=False,
sequence_callback=None,
element_callback=None):
self.include_primary_keys = include_primary_keys
self.include_foreign_keys = include_foreign_keys
self.sequence_callback = sequence_callback
if element_callback:
self.element_callback = element_callback
def element_callback(self, tb, column):
pass
def add_column_property_xsd(self, tb, column_property):
""" Add the XSD for a column property to the ``TreeBuilder``. """
if len(column_property.columns) != 1:
raise NotImplementedError # pragma: no cover
column = column_property.columns[0]
if column.primary_key and not self.include_primary_keys:
return
if column.foreign_keys and not self.include_foreign_keys:
if len(column.foreign_keys) != 1: # pragma: no cover
# FIXME understand when a column can have multiple
# foreign keys
raise NotImplementedError()
return
attrs = {'name': column_property.key}
self.add_column_xsd(tb, column, attrs)
def add_class_properties_xsd(self, tb, cls):
""" Add the XSD for the class properties to the ``TreeBuilder``. And
call the user ``sequence_callback``. """
for p in class_mapper(cls).iterate_properties:
if isinstance(p, ColumnProperty):
self.add_column_property_xsd(tb, p)
if self.sequence_callback:
self.sequence_callback(tb, cls)
def get_class_xsd(self, io, cls):
""" Returns the XSD for a mapped class. """
attrs = {}
attrs['xmlns:gml'] = 'http://www.opengis.net/gml'
attrs['xmlns:xsd'] = 'http://www.w3.org/2001/XMLSchema'
tb = TreeBuilder()
with tag(tb, 'xsd:schema', attrs) as tb:
with tag(tb, 'xsd:complexType', {'name': cls.__name__}) as tb:
with tag(tb, 'xsd:complexContent') as tb:
with tag(tb, 'xsd:extension',
{'base': 'gml:AbstractFeatureType'}) as tb:
with tag(tb, 'xsd:sequence') as tb:
self.add_class_properties_xsd(tb, cls)
ElementTree(tb.close()).write(io, encoding='utf-8')
return io
|
elemoine/papyrus
|
papyrus/xsd.py
|
XSDGenerator.add_column_property_xsd
|
python
|
def add_column_property_xsd(self, tb, column_property):
if len(column_property.columns) != 1:
raise NotImplementedError # pragma: no cover
column = column_property.columns[0]
if column.primary_key and not self.include_primary_keys:
return
if column.foreign_keys and not self.include_foreign_keys:
if len(column.foreign_keys) != 1: # pragma: no cover
# FIXME understand when a column can have multiple
# foreign keys
raise NotImplementedError()
return
attrs = {'name': column_property.key}
self.add_column_xsd(tb, column, attrs)
|
Add the XSD for a column property to the ``TreeBuilder``.
|
train
|
https://github.com/elemoine/papyrus/blob/764fb2326105df74fbd3dbcd7e58f4cb21956005/papyrus/xsd.py#L146-L160
|
[
"def add_column_xsd(self, tb, column, attrs):\n \"\"\" Add the XSD for a column to tb (a TreeBuilder) \"\"\"\n if column.nullable:\n attrs['minOccurs'] = str(0)\n attrs['nillable'] = 'true'\n for cls, xsd_type in six.iteritems(self.SIMPLE_XSD_TYPES):\n if isinstance(column.type, cls):\n attrs['type'] = xsd_type\n with tag(tb, 'xsd:element', attrs) as tb:\n self.element_callback(tb, column)\n return tb\n if isinstance(column.type, Geometry):\n geometry_type = column.type.geometry_type\n xsd_type = self.SIMPLE_GEOMETRY_XSD_TYPES[geometry_type]\n attrs['type'] = xsd_type\n with tag(tb, 'xsd:element', attrs) as tb:\n self.element_callback(tb, column)\n return tb\n if isinstance(column.type, sqlalchemy.Enum):\n with tag(tb, 'xsd:element', attrs) as tb:\n with tag(tb, 'xsd:simpleType') as tb:\n with tag(tb, 'xsd:restriction', {'base': 'xsd:string'}) \\\n as tb:\n for enum in column.type.enums:\n with tag(tb, 'xsd:enumeration', {'value': enum}):\n pass\n self.element_callback(tb, column)\n return tb\n if isinstance(column.type, sqlalchemy.Numeric):\n if column.type.scale is None and column.type.precision is None:\n attrs['type'] = 'xsd:decimal'\n with tag(tb, 'xsd:element', attrs) as tb:\n self.element_callback(tb, column)\n return tb\n else:\n with tag(tb, 'xsd:element', attrs) as tb:\n with tag(tb, 'xsd:simpleType') as tb:\n with tag(tb, 'xsd:restriction',\n {'base': 'xsd:decimal'}) as tb:\n if column.type.scale is not None:\n with tag(tb, 'xsd:fractionDigits',\n {'value': str(column.type.scale)}) \\\n as tb:\n pass\n if column.type.precision is not None:\n precision = column.type.precision\n with tag(tb, 'xsd:totalDigits',\n {'value': str(precision)}) \\\n as tb:\n pass\n self.element_callback(tb, column)\n return tb\n if isinstance(column.type, sqlalchemy.String) \\\n or isinstance(column.type, sqlalchemy.Text) \\\n or isinstance(column.type, sqlalchemy.Unicode) \\\n or isinstance(column.type, sqlalchemy.UnicodeText):\n if column.type.length is None:\n attrs['type'] = 'xsd:string'\n with tag(tb, 'xsd:element', attrs) as tb:\n self.element_callback(tb, column)\n return tb\n else:\n with tag(tb, 'xsd:element', attrs) as tb:\n with tag(tb, 'xsd:simpleType') as tb:\n with tag(tb, 'xsd:restriction',\n {'base': 'xsd:string'}) as tb:\n with tag(tb, 'xsd:maxLength',\n {'value': str(column.type.length)}):\n pass\n self.element_callback(tb, column)\n return tb\n raise UnsupportedColumnTypeError(column.type)\n"
] |
class XSDGenerator(object):
""" XSD Generator """
SIMPLE_XSD_TYPES = {
# SQLAlchemy types
sqlalchemy.BigInteger: 'xsd:integer',
sqlalchemy.Boolean: 'xsd:boolean',
sqlalchemy.Date: 'xsd:date',
sqlalchemy.DateTime: 'xsd:dateTime',
sqlalchemy.Float: 'xsd:double',
sqlalchemy.Integer: 'xsd:integer',
sqlalchemy.Interval: 'xsd:duration',
sqlalchemy.LargeBinary: 'xsd:base64Binary',
sqlalchemy.PickleType: 'xsd:base64Binary',
sqlalchemy.SmallInteger: 'xsd:integer',
sqlalchemy.Time: 'xsd:time',
}
SIMPLE_GEOMETRY_XSD_TYPES = {
# GeoAlchemy types
'CURVE': 'gml:CurvePropertyType',
'GEOMETRYCOLLECTION': 'gml:GeometryCollectionPropertyType',
'LINESTRING': 'gml:LineStringPropertyType',
'MULTILINESTRING': 'gml:MultiLineStringPropertyType',
'MULTIPOINT': 'gml:MultiPointPropertyType',
'MULTIPOLYGON': 'gml:MultiPolygonPropertyType',
'POINT': 'gml:PointPropertyType',
'POLYGON': 'gml:PolygonPropertyType',
}
def __init__(self,
include_primary_keys=False,
include_foreign_keys=False,
sequence_callback=None,
element_callback=None):
self.include_primary_keys = include_primary_keys
self.include_foreign_keys = include_foreign_keys
self.sequence_callback = sequence_callback
if element_callback:
self.element_callback = element_callback
def element_callback(self, tb, column):
pass
def add_column_xsd(self, tb, column, attrs):
""" Add the XSD for a column to tb (a TreeBuilder) """
if column.nullable:
attrs['minOccurs'] = str(0)
attrs['nillable'] = 'true'
for cls, xsd_type in six.iteritems(self.SIMPLE_XSD_TYPES):
if isinstance(column.type, cls):
attrs['type'] = xsd_type
with tag(tb, 'xsd:element', attrs) as tb:
self.element_callback(tb, column)
return tb
if isinstance(column.type, Geometry):
geometry_type = column.type.geometry_type
xsd_type = self.SIMPLE_GEOMETRY_XSD_TYPES[geometry_type]
attrs['type'] = xsd_type
with tag(tb, 'xsd:element', attrs) as tb:
self.element_callback(tb, column)
return tb
if isinstance(column.type, sqlalchemy.Enum):
with tag(tb, 'xsd:element', attrs) as tb:
with tag(tb, 'xsd:simpleType') as tb:
with tag(tb, 'xsd:restriction', {'base': 'xsd:string'}) \
as tb:
for enum in column.type.enums:
with tag(tb, 'xsd:enumeration', {'value': enum}):
pass
self.element_callback(tb, column)
return tb
if isinstance(column.type, sqlalchemy.Numeric):
if column.type.scale is None and column.type.precision is None:
attrs['type'] = 'xsd:decimal'
with tag(tb, 'xsd:element', attrs) as tb:
self.element_callback(tb, column)
return tb
else:
with tag(tb, 'xsd:element', attrs) as tb:
with tag(tb, 'xsd:simpleType') as tb:
with tag(tb, 'xsd:restriction',
{'base': 'xsd:decimal'}) as tb:
if column.type.scale is not None:
with tag(tb, 'xsd:fractionDigits',
{'value': str(column.type.scale)}) \
as tb:
pass
if column.type.precision is not None:
precision = column.type.precision
with tag(tb, 'xsd:totalDigits',
{'value': str(precision)}) \
as tb:
pass
self.element_callback(tb, column)
return tb
if isinstance(column.type, sqlalchemy.String) \
or isinstance(column.type, sqlalchemy.Text) \
or isinstance(column.type, sqlalchemy.Unicode) \
or isinstance(column.type, sqlalchemy.UnicodeText):
if column.type.length is None:
attrs['type'] = 'xsd:string'
with tag(tb, 'xsd:element', attrs) as tb:
self.element_callback(tb, column)
return tb
else:
with tag(tb, 'xsd:element', attrs) as tb:
with tag(tb, 'xsd:simpleType') as tb:
with tag(tb, 'xsd:restriction',
{'base': 'xsd:string'}) as tb:
with tag(tb, 'xsd:maxLength',
{'value': str(column.type.length)}):
pass
self.element_callback(tb, column)
return tb
raise UnsupportedColumnTypeError(column.type)
def add_class_properties_xsd(self, tb, cls):
""" Add the XSD for the class properties to the ``TreeBuilder``. And
call the user ``sequence_callback``. """
for p in class_mapper(cls).iterate_properties:
if isinstance(p, ColumnProperty):
self.add_column_property_xsd(tb, p)
if self.sequence_callback:
self.sequence_callback(tb, cls)
def get_class_xsd(self, io, cls):
""" Returns the XSD for a mapped class. """
attrs = {}
attrs['xmlns:gml'] = 'http://www.opengis.net/gml'
attrs['xmlns:xsd'] = 'http://www.w3.org/2001/XMLSchema'
tb = TreeBuilder()
with tag(tb, 'xsd:schema', attrs) as tb:
with tag(tb, 'xsd:complexType', {'name': cls.__name__}) as tb:
with tag(tb, 'xsd:complexContent') as tb:
with tag(tb, 'xsd:extension',
{'base': 'gml:AbstractFeatureType'}) as tb:
with tag(tb, 'xsd:sequence') as tb:
self.add_class_properties_xsd(tb, cls)
ElementTree(tb.close()).write(io, encoding='utf-8')
return io
|
elemoine/papyrus
|
papyrus/xsd.py
|
XSDGenerator.add_class_properties_xsd
|
python
|
def add_class_properties_xsd(self, tb, cls):
for p in class_mapper(cls).iterate_properties:
if isinstance(p, ColumnProperty):
self.add_column_property_xsd(tb, p)
if self.sequence_callback:
self.sequence_callback(tb, cls)
|
Add the XSD for the class properties to the ``TreeBuilder``. And
call the user ``sequence_callback``.
|
train
|
https://github.com/elemoine/papyrus/blob/764fb2326105df74fbd3dbcd7e58f4cb21956005/papyrus/xsd.py#L162-L169
|
[
"def add_column_property_xsd(self, tb, column_property):\n \"\"\" Add the XSD for a column property to the ``TreeBuilder``. \"\"\"\n if len(column_property.columns) != 1:\n raise NotImplementedError # pragma: no cover\n column = column_property.columns[0]\n if column.primary_key and not self.include_primary_keys:\n return\n if column.foreign_keys and not self.include_foreign_keys:\n if len(column.foreign_keys) != 1: # pragma: no cover\n # FIXME understand when a column can have multiple\n # foreign keys\n raise NotImplementedError()\n return\n attrs = {'name': column_property.key}\n self.add_column_xsd(tb, column, attrs)\n"
] |
class XSDGenerator(object):
""" XSD Generator """
SIMPLE_XSD_TYPES = {
# SQLAlchemy types
sqlalchemy.BigInteger: 'xsd:integer',
sqlalchemy.Boolean: 'xsd:boolean',
sqlalchemy.Date: 'xsd:date',
sqlalchemy.DateTime: 'xsd:dateTime',
sqlalchemy.Float: 'xsd:double',
sqlalchemy.Integer: 'xsd:integer',
sqlalchemy.Interval: 'xsd:duration',
sqlalchemy.LargeBinary: 'xsd:base64Binary',
sqlalchemy.PickleType: 'xsd:base64Binary',
sqlalchemy.SmallInteger: 'xsd:integer',
sqlalchemy.Time: 'xsd:time',
}
SIMPLE_GEOMETRY_XSD_TYPES = {
# GeoAlchemy types
'CURVE': 'gml:CurvePropertyType',
'GEOMETRYCOLLECTION': 'gml:GeometryCollectionPropertyType',
'LINESTRING': 'gml:LineStringPropertyType',
'MULTILINESTRING': 'gml:MultiLineStringPropertyType',
'MULTIPOINT': 'gml:MultiPointPropertyType',
'MULTIPOLYGON': 'gml:MultiPolygonPropertyType',
'POINT': 'gml:PointPropertyType',
'POLYGON': 'gml:PolygonPropertyType',
}
def __init__(self,
include_primary_keys=False,
include_foreign_keys=False,
sequence_callback=None,
element_callback=None):
self.include_primary_keys = include_primary_keys
self.include_foreign_keys = include_foreign_keys
self.sequence_callback = sequence_callback
if element_callback:
self.element_callback = element_callback
def element_callback(self, tb, column):
pass
def add_column_xsd(self, tb, column, attrs):
""" Add the XSD for a column to tb (a TreeBuilder) """
if column.nullable:
attrs['minOccurs'] = str(0)
attrs['nillable'] = 'true'
for cls, xsd_type in six.iteritems(self.SIMPLE_XSD_TYPES):
if isinstance(column.type, cls):
attrs['type'] = xsd_type
with tag(tb, 'xsd:element', attrs) as tb:
self.element_callback(tb, column)
return tb
if isinstance(column.type, Geometry):
geometry_type = column.type.geometry_type
xsd_type = self.SIMPLE_GEOMETRY_XSD_TYPES[geometry_type]
attrs['type'] = xsd_type
with tag(tb, 'xsd:element', attrs) as tb:
self.element_callback(tb, column)
return tb
if isinstance(column.type, sqlalchemy.Enum):
with tag(tb, 'xsd:element', attrs) as tb:
with tag(tb, 'xsd:simpleType') as tb:
with tag(tb, 'xsd:restriction', {'base': 'xsd:string'}) \
as tb:
for enum in column.type.enums:
with tag(tb, 'xsd:enumeration', {'value': enum}):
pass
self.element_callback(tb, column)
return tb
if isinstance(column.type, sqlalchemy.Numeric):
if column.type.scale is None and column.type.precision is None:
attrs['type'] = 'xsd:decimal'
with tag(tb, 'xsd:element', attrs) as tb:
self.element_callback(tb, column)
return tb
else:
with tag(tb, 'xsd:element', attrs) as tb:
with tag(tb, 'xsd:simpleType') as tb:
with tag(tb, 'xsd:restriction',
{'base': 'xsd:decimal'}) as tb:
if column.type.scale is not None:
with tag(tb, 'xsd:fractionDigits',
{'value': str(column.type.scale)}) \
as tb:
pass
if column.type.precision is not None:
precision = column.type.precision
with tag(tb, 'xsd:totalDigits',
{'value': str(precision)}) \
as tb:
pass
self.element_callback(tb, column)
return tb
if isinstance(column.type, sqlalchemy.String) \
or isinstance(column.type, sqlalchemy.Text) \
or isinstance(column.type, sqlalchemy.Unicode) \
or isinstance(column.type, sqlalchemy.UnicodeText):
if column.type.length is None:
attrs['type'] = 'xsd:string'
with tag(tb, 'xsd:element', attrs) as tb:
self.element_callback(tb, column)
return tb
else:
with tag(tb, 'xsd:element', attrs) as tb:
with tag(tb, 'xsd:simpleType') as tb:
with tag(tb, 'xsd:restriction',
{'base': 'xsd:string'}) as tb:
with tag(tb, 'xsd:maxLength',
{'value': str(column.type.length)}):
pass
self.element_callback(tb, column)
return tb
raise UnsupportedColumnTypeError(column.type)
def add_column_property_xsd(self, tb, column_property):
""" Add the XSD for a column property to the ``TreeBuilder``. """
if len(column_property.columns) != 1:
raise NotImplementedError # pragma: no cover
column = column_property.columns[0]
if column.primary_key and not self.include_primary_keys:
return
if column.foreign_keys and not self.include_foreign_keys:
if len(column.foreign_keys) != 1: # pragma: no cover
# FIXME understand when a column can have multiple
# foreign keys
raise NotImplementedError()
return
attrs = {'name': column_property.key}
self.add_column_xsd(tb, column, attrs)
def get_class_xsd(self, io, cls):
""" Returns the XSD for a mapped class. """
attrs = {}
attrs['xmlns:gml'] = 'http://www.opengis.net/gml'
attrs['xmlns:xsd'] = 'http://www.w3.org/2001/XMLSchema'
tb = TreeBuilder()
with tag(tb, 'xsd:schema', attrs) as tb:
with tag(tb, 'xsd:complexType', {'name': cls.__name__}) as tb:
with tag(tb, 'xsd:complexContent') as tb:
with tag(tb, 'xsd:extension',
{'base': 'gml:AbstractFeatureType'}) as tb:
with tag(tb, 'xsd:sequence') as tb:
self.add_class_properties_xsd(tb, cls)
ElementTree(tb.close()).write(io, encoding='utf-8')
return io
|
elemoine/papyrus
|
papyrus/xsd.py
|
XSDGenerator.get_class_xsd
|
python
|
def get_class_xsd(self, io, cls):
attrs = {}
attrs['xmlns:gml'] = 'http://www.opengis.net/gml'
attrs['xmlns:xsd'] = 'http://www.w3.org/2001/XMLSchema'
tb = TreeBuilder()
with tag(tb, 'xsd:schema', attrs) as tb:
with tag(tb, 'xsd:complexType', {'name': cls.__name__}) as tb:
with tag(tb, 'xsd:complexContent') as tb:
with tag(tb, 'xsd:extension',
{'base': 'gml:AbstractFeatureType'}) as tb:
with tag(tb, 'xsd:sequence') as tb:
self.add_class_properties_xsd(tb, cls)
ElementTree(tb.close()).write(io, encoding='utf-8')
return io
|
Returns the XSD for a mapped class.
|
train
|
https://github.com/elemoine/papyrus/blob/764fb2326105df74fbd3dbcd7e58f4cb21956005/papyrus/xsd.py#L171-L186
|
[
"def add_class_properties_xsd(self, tb, cls):\n \"\"\" Add the XSD for the class properties to the ``TreeBuilder``. And\n call the user ``sequence_callback``. \"\"\"\n for p in class_mapper(cls).iterate_properties:\n if isinstance(p, ColumnProperty):\n self.add_column_property_xsd(tb, p)\n if self.sequence_callback:\n self.sequence_callback(tb, cls)\n"
] |
class XSDGenerator(object):
""" XSD Generator """
SIMPLE_XSD_TYPES = {
# SQLAlchemy types
sqlalchemy.BigInteger: 'xsd:integer',
sqlalchemy.Boolean: 'xsd:boolean',
sqlalchemy.Date: 'xsd:date',
sqlalchemy.DateTime: 'xsd:dateTime',
sqlalchemy.Float: 'xsd:double',
sqlalchemy.Integer: 'xsd:integer',
sqlalchemy.Interval: 'xsd:duration',
sqlalchemy.LargeBinary: 'xsd:base64Binary',
sqlalchemy.PickleType: 'xsd:base64Binary',
sqlalchemy.SmallInteger: 'xsd:integer',
sqlalchemy.Time: 'xsd:time',
}
SIMPLE_GEOMETRY_XSD_TYPES = {
# GeoAlchemy types
'CURVE': 'gml:CurvePropertyType',
'GEOMETRYCOLLECTION': 'gml:GeometryCollectionPropertyType',
'LINESTRING': 'gml:LineStringPropertyType',
'MULTILINESTRING': 'gml:MultiLineStringPropertyType',
'MULTIPOINT': 'gml:MultiPointPropertyType',
'MULTIPOLYGON': 'gml:MultiPolygonPropertyType',
'POINT': 'gml:PointPropertyType',
'POLYGON': 'gml:PolygonPropertyType',
}
def __init__(self,
include_primary_keys=False,
include_foreign_keys=False,
sequence_callback=None,
element_callback=None):
self.include_primary_keys = include_primary_keys
self.include_foreign_keys = include_foreign_keys
self.sequence_callback = sequence_callback
if element_callback:
self.element_callback = element_callback
def element_callback(self, tb, column):
pass
def add_column_xsd(self, tb, column, attrs):
""" Add the XSD for a column to tb (a TreeBuilder) """
if column.nullable:
attrs['minOccurs'] = str(0)
attrs['nillable'] = 'true'
for cls, xsd_type in six.iteritems(self.SIMPLE_XSD_TYPES):
if isinstance(column.type, cls):
attrs['type'] = xsd_type
with tag(tb, 'xsd:element', attrs) as tb:
self.element_callback(tb, column)
return tb
if isinstance(column.type, Geometry):
geometry_type = column.type.geometry_type
xsd_type = self.SIMPLE_GEOMETRY_XSD_TYPES[geometry_type]
attrs['type'] = xsd_type
with tag(tb, 'xsd:element', attrs) as tb:
self.element_callback(tb, column)
return tb
if isinstance(column.type, sqlalchemy.Enum):
with tag(tb, 'xsd:element', attrs) as tb:
with tag(tb, 'xsd:simpleType') as tb:
with tag(tb, 'xsd:restriction', {'base': 'xsd:string'}) \
as tb:
for enum in column.type.enums:
with tag(tb, 'xsd:enumeration', {'value': enum}):
pass
self.element_callback(tb, column)
return tb
if isinstance(column.type, sqlalchemy.Numeric):
if column.type.scale is None and column.type.precision is None:
attrs['type'] = 'xsd:decimal'
with tag(tb, 'xsd:element', attrs) as tb:
self.element_callback(tb, column)
return tb
else:
with tag(tb, 'xsd:element', attrs) as tb:
with tag(tb, 'xsd:simpleType') as tb:
with tag(tb, 'xsd:restriction',
{'base': 'xsd:decimal'}) as tb:
if column.type.scale is not None:
with tag(tb, 'xsd:fractionDigits',
{'value': str(column.type.scale)}) \
as tb:
pass
if column.type.precision is not None:
precision = column.type.precision
with tag(tb, 'xsd:totalDigits',
{'value': str(precision)}) \
as tb:
pass
self.element_callback(tb, column)
return tb
if isinstance(column.type, sqlalchemy.String) \
or isinstance(column.type, sqlalchemy.Text) \
or isinstance(column.type, sqlalchemy.Unicode) \
or isinstance(column.type, sqlalchemy.UnicodeText):
if column.type.length is None:
attrs['type'] = 'xsd:string'
with tag(tb, 'xsd:element', attrs) as tb:
self.element_callback(tb, column)
return tb
else:
with tag(tb, 'xsd:element', attrs) as tb:
with tag(tb, 'xsd:simpleType') as tb:
with tag(tb, 'xsd:restriction',
{'base': 'xsd:string'}) as tb:
with tag(tb, 'xsd:maxLength',
{'value': str(column.type.length)}):
pass
self.element_callback(tb, column)
return tb
raise UnsupportedColumnTypeError(column.type)
def add_column_property_xsd(self, tb, column_property):
""" Add the XSD for a column property to the ``TreeBuilder``. """
if len(column_property.columns) != 1:
raise NotImplementedError # pragma: no cover
column = column_property.columns[0]
if column.primary_key and not self.include_primary_keys:
return
if column.foreign_keys and not self.include_foreign_keys:
if len(column.foreign_keys) != 1: # pragma: no cover
# FIXME understand when a column can have multiple
# foreign keys
raise NotImplementedError()
return
attrs = {'name': column_property.key}
self.add_column_xsd(tb, column, attrs)
def add_class_properties_xsd(self, tb, cls):
""" Add the XSD for the class properties to the ``TreeBuilder``. And
call the user ``sequence_callback``. """
for p in class_mapper(cls).iterate_properties:
if isinstance(p, ColumnProperty):
self.add_column_property_xsd(tb, p)
if self.sequence_callback:
self.sequence_callback(tb, cls)
|
elemoine/papyrus
|
papyrus/protocol.py
|
_get_col_epsg
|
python
|
def _get_col_epsg(mapped_class, geom_attr):
col = class_mapper(mapped_class).get_property(geom_attr).columns[0]
return col.type.srid
|
Get the EPSG code associated with a geometry attribute.
Arguments:
geom_attr
the key of the geometry property as defined in the SQLAlchemy
mapper. If you use ``declarative_base`` this is the name of
the geometry attribute as defined in the mapped class.
|
train
|
https://github.com/elemoine/papyrus/blob/764fb2326105df74fbd3dbcd7e58f4cb21956005/papyrus/protocol.py#L44-L56
| null |
# Copyright (c) 2008-2011 Camptocamp. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer. 2. Redistributions in
# binary form must reproduce the above copyright notice, this list of
# conditions and the following disclaimer in the documentation and/or other
# materials provided with the distribution. 3. Neither the name of Camptocamp
# nor the names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
import six
from pyramid.httpexceptions import (HTTPBadRequest, HTTPMethodNotAllowed,
HTTPNotFound)
from pyramid.response import Response
from shapely.geometry import asShape
from shapely.geometry.point import Point
from shapely.geometry.polygon import Polygon
from sqlalchemy.sql import asc, desc, and_, func
from sqlalchemy.orm.util import class_mapper
from geoalchemy2.shape import from_shape
from geojson import Feature, FeatureCollection, loads, GeoJSON
def create_geom_filter(request, mapped_class, geom_attr):
"""Create MapFish geometry filter based on the request params. Either
a box or within or geometry filter, depending on the request params.
Additional named arguments are passed to the spatial filter.
Arguments:
request
the request.
mapped_class
the SQLAlchemy mapped class.
geom_attr
the key of the geometry property as defined in the SQLAlchemy
mapper. If you use ``declarative_base`` this is the name of
the geometry attribute as defined in the mapped class.
"""
tolerance = float(request.params.get('tolerance', 0.0))
epsg = None
if 'epsg' in request.params:
epsg = int(request.params['epsg'])
box = request.params.get('bbox')
shape = None
if box is not None:
box = [float(x) for x in box.split(',')]
shape = Polygon(((box[0], box[1]), (box[0], box[3]),
(box[2], box[3]), (box[2], box[1]),
(box[0], box[1])))
elif 'lon' in request.params and 'lat' in request.params:
shape = Point(float(request.params['lon']),
float(request.params['lat']))
elif 'geometry' in request.params:
shape = loads(request.params['geometry'],
object_hook=GeoJSON.to_instance)
shape = asShape(shape)
if shape is None:
return None
column_epsg = _get_col_epsg(mapped_class, geom_attr)
geom_attr = getattr(mapped_class, geom_attr)
epsg = column_epsg if epsg is None else epsg
if epsg != column_epsg:
geom_attr = func.ST_Transform(geom_attr, epsg)
geometry = from_shape(shape, srid=epsg)
return func.ST_DWITHIN(geom_attr, geometry, tolerance)
def create_attr_filter(request, mapped_class):
"""Create an ``and_`` SQLAlchemy filter (a ClauseList object) based
on the request params (``queryable``, ``eq``, ``ne``, ...).
Arguments:
request
the request.
mapped_class
the SQLAlchemy mapped class.
"""
mapping = {
'eq': '__eq__',
'ne': '__ne__',
'lt': '__lt__',
'lte': '__le__',
'gt': '__gt__',
'gte': '__ge__',
'like': 'like',
'ilike': 'ilike'
}
filters = []
if 'queryable' in request.params:
queryable = request.params['queryable'].split(',')
for k in request.params:
if len(request.params[k]) <= 0 or '__' not in k:
continue
col, op = k.split("__")
if col not in queryable or op not in mapping:
continue
column = getattr(mapped_class, col)
f = getattr(column, mapping[op])(request.params[k])
filters.append(f)
return and_(*filters) if len(filters) > 0 else None
def create_filter(request, mapped_class, geom_attr, **kwargs):
""" Create MapFish default filter based on the request params.
Arguments:
request
the request.
mapped_class
the SQLAlchemy mapped class.
geom_attr
the key of the geometry property as defined in the SQLAlchemy
mapper. If you use ``declarative_base`` this is the name of
the geometry attribute as defined in the mapped class.
\\**kwargs
additional arguments passed to ``create_geom_filter()``.
"""
attr_filter = create_attr_filter(request, mapped_class)
geom_filter = create_geom_filter(request, mapped_class, geom_attr,
**kwargs)
if geom_filter is None and attr_filter is None:
return None
if geom_filter is None:
return attr_filter
if attr_filter is None:
return geom_filter
return and_(geom_filter, attr_filter)
def asbool(val):
# Convert the passed value to a boolean.
if isinstance(val, six.string_types):
return val.lower() not in ['false', '0']
else:
return bool(val)
class Protocol(object):
""" Protocol class.
Session
an SQLAlchemy ``Session`` class.
mapped_class
the class mapped to a database table in the ORM.
geom_attr
the key of the geometry property as defined in the SQLAlchemy
mapper. If you use ``declarative_base`` this is the name of
the geometry attribute as defined in the mapped class.
readonly
``True`` if this protocol is read-only, ``False`` otherwise. If
``True``, the methods ``create()``, ``update()`` and ``delete()``
will set 405 (Method Not Allowed) as the response status and
return right away.
\\**kwargs
before_create
a callback function called before a feature is inserted
in the database table, the function receives the request,
the feature read from the GeoJSON document sent in the
request, and the database object to be updated. The
latter is None if this is is an actual insertion.
before_update
a callback function called before a feature is updated
in the database table, the function receives the request,
the feature read from the GeoJSON document sent in the
request, and the database object to be updated.
before_delete
a callback function called before a feature is deleted
in the database table, the function receives the request
and the database object about to be deleted.
"""
def __init__(self, Session, mapped_class, geom_attr, readonly=False,
**kwargs):
self.Session = Session
self.mapped_class = mapped_class
self.geom_attr = geom_attr
self.readonly = readonly
self.before_create = kwargs.get('before_create')
self.before_update = kwargs.get('before_update')
self.before_delete = kwargs.get('before_delete')
def _filter_attrs(self, feature, request):
""" Remove some attributes from the feature and set the geometry to None
in the feature based ``attrs`` and the ``no_geom`` parameters. """
if 'attrs' in request.params:
attrs = request.params['attrs'].split(',')
props = feature.properties
new_props = {}
for name in attrs:
if name in props:
new_props[name] = props[name]
feature.properties = new_props
if asbool(request.params.get('no_geom', False)):
feature.geometry = None
return feature
def _get_order_by(self, request):
""" Return an SA order_by """
attr = request.params.get('sort', request.params.get('order_by'))
if attr is None or not hasattr(self.mapped_class, attr):
return None
if request.params.get('dir', '').upper() == 'DESC':
return desc(getattr(self.mapped_class, attr))
else:
return asc(getattr(self.mapped_class, attr))
def _query(self, request, filter=None):
""" Build a query based on the filter and the request params,
and send the query to the database. """
limit = None
offset = None
if 'maxfeatures' in request.params:
limit = int(request.params['maxfeatures'])
if 'limit' in request.params:
limit = int(request.params['limit'])
if 'offset' in request.params:
offset = int(request.params['offset'])
if filter is None:
filter = create_filter(request, self.mapped_class, self.geom_attr)
query = self.Session().query(self.mapped_class)
if filter is not None:
query = query.filter(filter)
order_by = self._get_order_by(request)
if order_by is not None:
query = query.order_by(order_by)
query = query.limit(limit).offset(offset)
return query.all()
def count(self, request, filter=None):
""" Return the number of records matching the given filter. """
if filter is None:
filter = create_filter(request, self.mapped_class, self.geom_attr)
query = self.Session().query(self.mapped_class)
if filter is not None:
query = query.filter(filter)
return query.count()
def read(self, request, filter=None, id=None):
""" Build a query based on the filter or the idenfier, send the query
to the database, and return a Feature or a FeatureCollection. """
ret = None
if id is not None:
o = self.Session().query(self.mapped_class).get(id)
if o is None:
return HTTPNotFound()
# FIXME: we return a Feature here, not a mapped object, do
# we really want that?
ret = self._filter_attrs(o.__geo_interface__, request)
else:
objs = self._query(request, filter)
ret = FeatureCollection(
[self._filter_attrs(o.__geo_interface__, request)
for o in objs if o is not None])
return ret
def create(self, request):
""" Read the GeoJSON feature collection from the request body and
create new objects in the database. """
if self.readonly:
return HTTPMethodNotAllowed(headers={'Allow': 'GET, HEAD'})
collection = loads(request.body, object_hook=GeoJSON.to_instance)
if not isinstance(collection, FeatureCollection):
return HTTPBadRequest()
session = self.Session()
objects = []
for feature in collection.features:
create = False
obj = None
if hasattr(feature, 'id') and feature.id is not None:
obj = session.query(self.mapped_class).get(feature.id)
if self.before_create is not None:
self.before_create(request, feature, obj)
if obj is None:
obj = self.mapped_class(feature)
create = True
else:
obj.__update__(feature)
if create:
session.add(obj)
objects.append(obj)
session.flush()
collection = FeatureCollection(objects) if len(objects) > 0 else None
request.response.status_int = 201
return collection
def update(self, request, id):
""" Read the GeoJSON feature from the request body and update the
corresponding object in the database. """
if self.readonly:
return HTTPMethodNotAllowed(headers={'Allow': 'GET, HEAD'})
session = self.Session()
obj = session.query(self.mapped_class).get(id)
if obj is None:
return HTTPNotFound()
feature = loads(request.body, object_hook=GeoJSON.to_instance)
if not isinstance(feature, Feature):
return HTTPBadRequest()
if self.before_update is not None:
self.before_update(request, feature, obj)
obj.__update__(feature)
session.flush()
request.response.status_int = 200
return obj
def delete(self, request, id):
""" Remove the targeted feature from the database """
if self.readonly:
return HTTPMethodNotAllowed(headers={'Allow': 'GET, HEAD'})
session = self.Session()
obj = session.query(self.mapped_class).get(id)
if obj is None:
return HTTPNotFound()
if self.before_delete is not None:
self.before_delete(request, obj)
session.delete(obj)
return Response(status_int=204)
|
elemoine/papyrus
|
papyrus/protocol.py
|
create_geom_filter
|
python
|
def create_geom_filter(request, mapped_class, geom_attr):
tolerance = float(request.params.get('tolerance', 0.0))
epsg = None
if 'epsg' in request.params:
epsg = int(request.params['epsg'])
box = request.params.get('bbox')
shape = None
if box is not None:
box = [float(x) for x in box.split(',')]
shape = Polygon(((box[0], box[1]), (box[0], box[3]),
(box[2], box[3]), (box[2], box[1]),
(box[0], box[1])))
elif 'lon' in request.params and 'lat' in request.params:
shape = Point(float(request.params['lon']),
float(request.params['lat']))
elif 'geometry' in request.params:
shape = loads(request.params['geometry'],
object_hook=GeoJSON.to_instance)
shape = asShape(shape)
if shape is None:
return None
column_epsg = _get_col_epsg(mapped_class, geom_attr)
geom_attr = getattr(mapped_class, geom_attr)
epsg = column_epsg if epsg is None else epsg
if epsg != column_epsg:
geom_attr = func.ST_Transform(geom_attr, epsg)
geometry = from_shape(shape, srid=epsg)
return func.ST_DWITHIN(geom_attr, geometry, tolerance)
|
Create MapFish geometry filter based on the request params. Either
a box or within or geometry filter, depending on the request params.
Additional named arguments are passed to the spatial filter.
Arguments:
request
the request.
mapped_class
the SQLAlchemy mapped class.
geom_attr
the key of the geometry property as defined in the SQLAlchemy
mapper. If you use ``declarative_base`` this is the name of
the geometry attribute as defined in the mapped class.
|
train
|
https://github.com/elemoine/papyrus/blob/764fb2326105df74fbd3dbcd7e58f4cb21956005/papyrus/protocol.py#L59-L103
|
[
"def _get_col_epsg(mapped_class, geom_attr):\n \"\"\"Get the EPSG code associated with a geometry attribute.\n\n Arguments:\n\n\n geom_attr\n the key of the geometry property as defined in the SQLAlchemy\n mapper. If you use ``declarative_base`` this is the name of\n the geometry attribute as defined in the mapped class.\n \"\"\"\n col = class_mapper(mapped_class).get_property(geom_attr).columns[0]\n return col.type.srid\n"
] |
# Copyright (c) 2008-2011 Camptocamp. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer. 2. Redistributions in
# binary form must reproduce the above copyright notice, this list of
# conditions and the following disclaimer in the documentation and/or other
# materials provided with the distribution. 3. Neither the name of Camptocamp
# nor the names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
import six
from pyramid.httpexceptions import (HTTPBadRequest, HTTPMethodNotAllowed,
HTTPNotFound)
from pyramid.response import Response
from shapely.geometry import asShape
from shapely.geometry.point import Point
from shapely.geometry.polygon import Polygon
from sqlalchemy.sql import asc, desc, and_, func
from sqlalchemy.orm.util import class_mapper
from geoalchemy2.shape import from_shape
from geojson import Feature, FeatureCollection, loads, GeoJSON
def _get_col_epsg(mapped_class, geom_attr):
"""Get the EPSG code associated with a geometry attribute.
Arguments:
geom_attr
the key of the geometry property as defined in the SQLAlchemy
mapper. If you use ``declarative_base`` this is the name of
the geometry attribute as defined in the mapped class.
"""
col = class_mapper(mapped_class).get_property(geom_attr).columns[0]
return col.type.srid
def create_attr_filter(request, mapped_class):
"""Create an ``and_`` SQLAlchemy filter (a ClauseList object) based
on the request params (``queryable``, ``eq``, ``ne``, ...).
Arguments:
request
the request.
mapped_class
the SQLAlchemy mapped class.
"""
mapping = {
'eq': '__eq__',
'ne': '__ne__',
'lt': '__lt__',
'lte': '__le__',
'gt': '__gt__',
'gte': '__ge__',
'like': 'like',
'ilike': 'ilike'
}
filters = []
if 'queryable' in request.params:
queryable = request.params['queryable'].split(',')
for k in request.params:
if len(request.params[k]) <= 0 or '__' not in k:
continue
col, op = k.split("__")
if col not in queryable or op not in mapping:
continue
column = getattr(mapped_class, col)
f = getattr(column, mapping[op])(request.params[k])
filters.append(f)
return and_(*filters) if len(filters) > 0 else None
def create_filter(request, mapped_class, geom_attr, **kwargs):
""" Create MapFish default filter based on the request params.
Arguments:
request
the request.
mapped_class
the SQLAlchemy mapped class.
geom_attr
the key of the geometry property as defined in the SQLAlchemy
mapper. If you use ``declarative_base`` this is the name of
the geometry attribute as defined in the mapped class.
\\**kwargs
additional arguments passed to ``create_geom_filter()``.
"""
attr_filter = create_attr_filter(request, mapped_class)
geom_filter = create_geom_filter(request, mapped_class, geom_attr,
**kwargs)
if geom_filter is None and attr_filter is None:
return None
if geom_filter is None:
return attr_filter
if attr_filter is None:
return geom_filter
return and_(geom_filter, attr_filter)
def asbool(val):
# Convert the passed value to a boolean.
if isinstance(val, six.string_types):
return val.lower() not in ['false', '0']
else:
return bool(val)
class Protocol(object):
""" Protocol class.
Session
an SQLAlchemy ``Session`` class.
mapped_class
the class mapped to a database table in the ORM.
geom_attr
the key of the geometry property as defined in the SQLAlchemy
mapper. If you use ``declarative_base`` this is the name of
the geometry attribute as defined in the mapped class.
readonly
``True`` if this protocol is read-only, ``False`` otherwise. If
``True``, the methods ``create()``, ``update()`` and ``delete()``
will set 405 (Method Not Allowed) as the response status and
return right away.
\\**kwargs
before_create
a callback function called before a feature is inserted
in the database table, the function receives the request,
the feature read from the GeoJSON document sent in the
request, and the database object to be updated. The
latter is None if this is is an actual insertion.
before_update
a callback function called before a feature is updated
in the database table, the function receives the request,
the feature read from the GeoJSON document sent in the
request, and the database object to be updated.
before_delete
a callback function called before a feature is deleted
in the database table, the function receives the request
and the database object about to be deleted.
"""
def __init__(self, Session, mapped_class, geom_attr, readonly=False,
**kwargs):
self.Session = Session
self.mapped_class = mapped_class
self.geom_attr = geom_attr
self.readonly = readonly
self.before_create = kwargs.get('before_create')
self.before_update = kwargs.get('before_update')
self.before_delete = kwargs.get('before_delete')
def _filter_attrs(self, feature, request):
""" Remove some attributes from the feature and set the geometry to None
in the feature based ``attrs`` and the ``no_geom`` parameters. """
if 'attrs' in request.params:
attrs = request.params['attrs'].split(',')
props = feature.properties
new_props = {}
for name in attrs:
if name in props:
new_props[name] = props[name]
feature.properties = new_props
if asbool(request.params.get('no_geom', False)):
feature.geometry = None
return feature
def _get_order_by(self, request):
""" Return an SA order_by """
attr = request.params.get('sort', request.params.get('order_by'))
if attr is None or not hasattr(self.mapped_class, attr):
return None
if request.params.get('dir', '').upper() == 'DESC':
return desc(getattr(self.mapped_class, attr))
else:
return asc(getattr(self.mapped_class, attr))
def _query(self, request, filter=None):
""" Build a query based on the filter and the request params,
and send the query to the database. """
limit = None
offset = None
if 'maxfeatures' in request.params:
limit = int(request.params['maxfeatures'])
if 'limit' in request.params:
limit = int(request.params['limit'])
if 'offset' in request.params:
offset = int(request.params['offset'])
if filter is None:
filter = create_filter(request, self.mapped_class, self.geom_attr)
query = self.Session().query(self.mapped_class)
if filter is not None:
query = query.filter(filter)
order_by = self._get_order_by(request)
if order_by is not None:
query = query.order_by(order_by)
query = query.limit(limit).offset(offset)
return query.all()
def count(self, request, filter=None):
""" Return the number of records matching the given filter. """
if filter is None:
filter = create_filter(request, self.mapped_class, self.geom_attr)
query = self.Session().query(self.mapped_class)
if filter is not None:
query = query.filter(filter)
return query.count()
def read(self, request, filter=None, id=None):
""" Build a query based on the filter or the idenfier, send the query
to the database, and return a Feature or a FeatureCollection. """
ret = None
if id is not None:
o = self.Session().query(self.mapped_class).get(id)
if o is None:
return HTTPNotFound()
# FIXME: we return a Feature here, not a mapped object, do
# we really want that?
ret = self._filter_attrs(o.__geo_interface__, request)
else:
objs = self._query(request, filter)
ret = FeatureCollection(
[self._filter_attrs(o.__geo_interface__, request)
for o in objs if o is not None])
return ret
def create(self, request):
""" Read the GeoJSON feature collection from the request body and
create new objects in the database. """
if self.readonly:
return HTTPMethodNotAllowed(headers={'Allow': 'GET, HEAD'})
collection = loads(request.body, object_hook=GeoJSON.to_instance)
if not isinstance(collection, FeatureCollection):
return HTTPBadRequest()
session = self.Session()
objects = []
for feature in collection.features:
create = False
obj = None
if hasattr(feature, 'id') and feature.id is not None:
obj = session.query(self.mapped_class).get(feature.id)
if self.before_create is not None:
self.before_create(request, feature, obj)
if obj is None:
obj = self.mapped_class(feature)
create = True
else:
obj.__update__(feature)
if create:
session.add(obj)
objects.append(obj)
session.flush()
collection = FeatureCollection(objects) if len(objects) > 0 else None
request.response.status_int = 201
return collection
def update(self, request, id):
""" Read the GeoJSON feature from the request body and update the
corresponding object in the database. """
if self.readonly:
return HTTPMethodNotAllowed(headers={'Allow': 'GET, HEAD'})
session = self.Session()
obj = session.query(self.mapped_class).get(id)
if obj is None:
return HTTPNotFound()
feature = loads(request.body, object_hook=GeoJSON.to_instance)
if not isinstance(feature, Feature):
return HTTPBadRequest()
if self.before_update is not None:
self.before_update(request, feature, obj)
obj.__update__(feature)
session.flush()
request.response.status_int = 200
return obj
def delete(self, request, id):
""" Remove the targeted feature from the database """
if self.readonly:
return HTTPMethodNotAllowed(headers={'Allow': 'GET, HEAD'})
session = self.Session()
obj = session.query(self.mapped_class).get(id)
if obj is None:
return HTTPNotFound()
if self.before_delete is not None:
self.before_delete(request, obj)
session.delete(obj)
return Response(status_int=204)
|
elemoine/papyrus
|
papyrus/protocol.py
|
create_attr_filter
|
python
|
def create_attr_filter(request, mapped_class):
mapping = {
'eq': '__eq__',
'ne': '__ne__',
'lt': '__lt__',
'lte': '__le__',
'gt': '__gt__',
'gte': '__ge__',
'like': 'like',
'ilike': 'ilike'
}
filters = []
if 'queryable' in request.params:
queryable = request.params['queryable'].split(',')
for k in request.params:
if len(request.params[k]) <= 0 or '__' not in k:
continue
col, op = k.split("__")
if col not in queryable or op not in mapping:
continue
column = getattr(mapped_class, col)
f = getattr(column, mapping[op])(request.params[k])
filters.append(f)
return and_(*filters) if len(filters) > 0 else None
|
Create an ``and_`` SQLAlchemy filter (a ClauseList object) based
on the request params (``queryable``, ``eq``, ``ne``, ...).
Arguments:
request
the request.
mapped_class
the SQLAlchemy mapped class.
|
train
|
https://github.com/elemoine/papyrus/blob/764fb2326105df74fbd3dbcd7e58f4cb21956005/papyrus/protocol.py#L106-L141
| null |
# Copyright (c) 2008-2011 Camptocamp. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer. 2. Redistributions in
# binary form must reproduce the above copyright notice, this list of
# conditions and the following disclaimer in the documentation and/or other
# materials provided with the distribution. 3. Neither the name of Camptocamp
# nor the names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
import six
from pyramid.httpexceptions import (HTTPBadRequest, HTTPMethodNotAllowed,
HTTPNotFound)
from pyramid.response import Response
from shapely.geometry import asShape
from shapely.geometry.point import Point
from shapely.geometry.polygon import Polygon
from sqlalchemy.sql import asc, desc, and_, func
from sqlalchemy.orm.util import class_mapper
from geoalchemy2.shape import from_shape
from geojson import Feature, FeatureCollection, loads, GeoJSON
def _get_col_epsg(mapped_class, geom_attr):
"""Get the EPSG code associated with a geometry attribute.
Arguments:
geom_attr
the key of the geometry property as defined in the SQLAlchemy
mapper. If you use ``declarative_base`` this is the name of
the geometry attribute as defined in the mapped class.
"""
col = class_mapper(mapped_class).get_property(geom_attr).columns[0]
return col.type.srid
def create_geom_filter(request, mapped_class, geom_attr):
"""Create MapFish geometry filter based on the request params. Either
a box or within or geometry filter, depending on the request params.
Additional named arguments are passed to the spatial filter.
Arguments:
request
the request.
mapped_class
the SQLAlchemy mapped class.
geom_attr
the key of the geometry property as defined in the SQLAlchemy
mapper. If you use ``declarative_base`` this is the name of
the geometry attribute as defined in the mapped class.
"""
tolerance = float(request.params.get('tolerance', 0.0))
epsg = None
if 'epsg' in request.params:
epsg = int(request.params['epsg'])
box = request.params.get('bbox')
shape = None
if box is not None:
box = [float(x) for x in box.split(',')]
shape = Polygon(((box[0], box[1]), (box[0], box[3]),
(box[2], box[3]), (box[2], box[1]),
(box[0], box[1])))
elif 'lon' in request.params and 'lat' in request.params:
shape = Point(float(request.params['lon']),
float(request.params['lat']))
elif 'geometry' in request.params:
shape = loads(request.params['geometry'],
object_hook=GeoJSON.to_instance)
shape = asShape(shape)
if shape is None:
return None
column_epsg = _get_col_epsg(mapped_class, geom_attr)
geom_attr = getattr(mapped_class, geom_attr)
epsg = column_epsg if epsg is None else epsg
if epsg != column_epsg:
geom_attr = func.ST_Transform(geom_attr, epsg)
geometry = from_shape(shape, srid=epsg)
return func.ST_DWITHIN(geom_attr, geometry, tolerance)
def create_filter(request, mapped_class, geom_attr, **kwargs):
""" Create MapFish default filter based on the request params.
Arguments:
request
the request.
mapped_class
the SQLAlchemy mapped class.
geom_attr
the key of the geometry property as defined in the SQLAlchemy
mapper. If you use ``declarative_base`` this is the name of
the geometry attribute as defined in the mapped class.
\\**kwargs
additional arguments passed to ``create_geom_filter()``.
"""
attr_filter = create_attr_filter(request, mapped_class)
geom_filter = create_geom_filter(request, mapped_class, geom_attr,
**kwargs)
if geom_filter is None and attr_filter is None:
return None
if geom_filter is None:
return attr_filter
if attr_filter is None:
return geom_filter
return and_(geom_filter, attr_filter)
def asbool(val):
# Convert the passed value to a boolean.
if isinstance(val, six.string_types):
return val.lower() not in ['false', '0']
else:
return bool(val)
class Protocol(object):
""" Protocol class.
Session
an SQLAlchemy ``Session`` class.
mapped_class
the class mapped to a database table in the ORM.
geom_attr
the key of the geometry property as defined in the SQLAlchemy
mapper. If you use ``declarative_base`` this is the name of
the geometry attribute as defined in the mapped class.
readonly
``True`` if this protocol is read-only, ``False`` otherwise. If
``True``, the methods ``create()``, ``update()`` and ``delete()``
will set 405 (Method Not Allowed) as the response status and
return right away.
\\**kwargs
before_create
a callback function called before a feature is inserted
in the database table, the function receives the request,
the feature read from the GeoJSON document sent in the
request, and the database object to be updated. The
latter is None if this is is an actual insertion.
before_update
a callback function called before a feature is updated
in the database table, the function receives the request,
the feature read from the GeoJSON document sent in the
request, and the database object to be updated.
before_delete
a callback function called before a feature is deleted
in the database table, the function receives the request
and the database object about to be deleted.
"""
def __init__(self, Session, mapped_class, geom_attr, readonly=False,
**kwargs):
self.Session = Session
self.mapped_class = mapped_class
self.geom_attr = geom_attr
self.readonly = readonly
self.before_create = kwargs.get('before_create')
self.before_update = kwargs.get('before_update')
self.before_delete = kwargs.get('before_delete')
def _filter_attrs(self, feature, request):
""" Remove some attributes from the feature and set the geometry to None
in the feature based ``attrs`` and the ``no_geom`` parameters. """
if 'attrs' in request.params:
attrs = request.params['attrs'].split(',')
props = feature.properties
new_props = {}
for name in attrs:
if name in props:
new_props[name] = props[name]
feature.properties = new_props
if asbool(request.params.get('no_geom', False)):
feature.geometry = None
return feature
def _get_order_by(self, request):
""" Return an SA order_by """
attr = request.params.get('sort', request.params.get('order_by'))
if attr is None or not hasattr(self.mapped_class, attr):
return None
if request.params.get('dir', '').upper() == 'DESC':
return desc(getattr(self.mapped_class, attr))
else:
return asc(getattr(self.mapped_class, attr))
def _query(self, request, filter=None):
""" Build a query based on the filter and the request params,
and send the query to the database. """
limit = None
offset = None
if 'maxfeatures' in request.params:
limit = int(request.params['maxfeatures'])
if 'limit' in request.params:
limit = int(request.params['limit'])
if 'offset' in request.params:
offset = int(request.params['offset'])
if filter is None:
filter = create_filter(request, self.mapped_class, self.geom_attr)
query = self.Session().query(self.mapped_class)
if filter is not None:
query = query.filter(filter)
order_by = self._get_order_by(request)
if order_by is not None:
query = query.order_by(order_by)
query = query.limit(limit).offset(offset)
return query.all()
def count(self, request, filter=None):
""" Return the number of records matching the given filter. """
if filter is None:
filter = create_filter(request, self.mapped_class, self.geom_attr)
query = self.Session().query(self.mapped_class)
if filter is not None:
query = query.filter(filter)
return query.count()
def read(self, request, filter=None, id=None):
""" Build a query based on the filter or the idenfier, send the query
to the database, and return a Feature or a FeatureCollection. """
ret = None
if id is not None:
o = self.Session().query(self.mapped_class).get(id)
if o is None:
return HTTPNotFound()
# FIXME: we return a Feature here, not a mapped object, do
# we really want that?
ret = self._filter_attrs(o.__geo_interface__, request)
else:
objs = self._query(request, filter)
ret = FeatureCollection(
[self._filter_attrs(o.__geo_interface__, request)
for o in objs if o is not None])
return ret
def create(self, request):
""" Read the GeoJSON feature collection from the request body and
create new objects in the database. """
if self.readonly:
return HTTPMethodNotAllowed(headers={'Allow': 'GET, HEAD'})
collection = loads(request.body, object_hook=GeoJSON.to_instance)
if not isinstance(collection, FeatureCollection):
return HTTPBadRequest()
session = self.Session()
objects = []
for feature in collection.features:
create = False
obj = None
if hasattr(feature, 'id') and feature.id is not None:
obj = session.query(self.mapped_class).get(feature.id)
if self.before_create is not None:
self.before_create(request, feature, obj)
if obj is None:
obj = self.mapped_class(feature)
create = True
else:
obj.__update__(feature)
if create:
session.add(obj)
objects.append(obj)
session.flush()
collection = FeatureCollection(objects) if len(objects) > 0 else None
request.response.status_int = 201
return collection
def update(self, request, id):
""" Read the GeoJSON feature from the request body and update the
corresponding object in the database. """
if self.readonly:
return HTTPMethodNotAllowed(headers={'Allow': 'GET, HEAD'})
session = self.Session()
obj = session.query(self.mapped_class).get(id)
if obj is None:
return HTTPNotFound()
feature = loads(request.body, object_hook=GeoJSON.to_instance)
if not isinstance(feature, Feature):
return HTTPBadRequest()
if self.before_update is not None:
self.before_update(request, feature, obj)
obj.__update__(feature)
session.flush()
request.response.status_int = 200
return obj
def delete(self, request, id):
""" Remove the targeted feature from the database """
if self.readonly:
return HTTPMethodNotAllowed(headers={'Allow': 'GET, HEAD'})
session = self.Session()
obj = session.query(self.mapped_class).get(id)
if obj is None:
return HTTPNotFound()
if self.before_delete is not None:
self.before_delete(request, obj)
session.delete(obj)
return Response(status_int=204)
|
elemoine/papyrus
|
papyrus/protocol.py
|
create_filter
|
python
|
def create_filter(request, mapped_class, geom_attr, **kwargs):
attr_filter = create_attr_filter(request, mapped_class)
geom_filter = create_geom_filter(request, mapped_class, geom_attr,
**kwargs)
if geom_filter is None and attr_filter is None:
return None
if geom_filter is None:
return attr_filter
if attr_filter is None:
return geom_filter
return and_(geom_filter, attr_filter)
|
Create MapFish default filter based on the request params.
Arguments:
request
the request.
mapped_class
the SQLAlchemy mapped class.
geom_attr
the key of the geometry property as defined in the SQLAlchemy
mapper. If you use ``declarative_base`` this is the name of
the geometry attribute as defined in the mapped class.
\\**kwargs
additional arguments passed to ``create_geom_filter()``.
|
train
|
https://github.com/elemoine/papyrus/blob/764fb2326105df74fbd3dbcd7e58f4cb21956005/papyrus/protocol.py#L144-L172
|
[
"def create_geom_filter(request, mapped_class, geom_attr):\n \"\"\"Create MapFish geometry filter based on the request params. Either\n a box or within or geometry filter, depending on the request params.\n Additional named arguments are passed to the spatial filter.\n\n Arguments:\n\n request\n the request.\n\n mapped_class\n the SQLAlchemy mapped class.\n\n geom_attr\n the key of the geometry property as defined in the SQLAlchemy\n mapper. If you use ``declarative_base`` this is the name of\n the geometry attribute as defined in the mapped class.\n \"\"\"\n tolerance = float(request.params.get('tolerance', 0.0))\n epsg = None\n if 'epsg' in request.params:\n epsg = int(request.params['epsg'])\n box = request.params.get('bbox')\n shape = None\n if box is not None:\n box = [float(x) for x in box.split(',')]\n shape = Polygon(((box[0], box[1]), (box[0], box[3]),\n (box[2], box[3]), (box[2], box[1]),\n (box[0], box[1])))\n elif 'lon' in request.params and 'lat' in request.params:\n shape = Point(float(request.params['lon']),\n float(request.params['lat']))\n elif 'geometry' in request.params:\n shape = loads(request.params['geometry'],\n object_hook=GeoJSON.to_instance)\n shape = asShape(shape)\n if shape is None:\n return None\n column_epsg = _get_col_epsg(mapped_class, geom_attr)\n geom_attr = getattr(mapped_class, geom_attr)\n epsg = column_epsg if epsg is None else epsg\n if epsg != column_epsg:\n geom_attr = func.ST_Transform(geom_attr, epsg)\n geometry = from_shape(shape, srid=epsg)\n return func.ST_DWITHIN(geom_attr, geometry, tolerance)\n",
"def create_attr_filter(request, mapped_class):\n \"\"\"Create an ``and_`` SQLAlchemy filter (a ClauseList object) based\n on the request params (``queryable``, ``eq``, ``ne``, ...).\n\n Arguments:\n\n request\n the request.\n\n mapped_class\n the SQLAlchemy mapped class.\n \"\"\"\n\n mapping = {\n 'eq': '__eq__',\n 'ne': '__ne__',\n 'lt': '__lt__',\n 'lte': '__le__',\n 'gt': '__gt__',\n 'gte': '__ge__',\n 'like': 'like',\n 'ilike': 'ilike'\n }\n filters = []\n if 'queryable' in request.params:\n queryable = request.params['queryable'].split(',')\n for k in request.params:\n if len(request.params[k]) <= 0 or '__' not in k:\n continue\n col, op = k.split(\"__\")\n if col not in queryable or op not in mapping:\n continue\n column = getattr(mapped_class, col)\n f = getattr(column, mapping[op])(request.params[k])\n filters.append(f)\n return and_(*filters) if len(filters) > 0 else None\n"
] |
# Copyright (c) 2008-2011 Camptocamp. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer. 2. Redistributions in
# binary form must reproduce the above copyright notice, this list of
# conditions and the following disclaimer in the documentation and/or other
# materials provided with the distribution. 3. Neither the name of Camptocamp
# nor the names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
import six
from pyramid.httpexceptions import (HTTPBadRequest, HTTPMethodNotAllowed,
HTTPNotFound)
from pyramid.response import Response
from shapely.geometry import asShape
from shapely.geometry.point import Point
from shapely.geometry.polygon import Polygon
from sqlalchemy.sql import asc, desc, and_, func
from sqlalchemy.orm.util import class_mapper
from geoalchemy2.shape import from_shape
from geojson import Feature, FeatureCollection, loads, GeoJSON
def _get_col_epsg(mapped_class, geom_attr):
"""Get the EPSG code associated with a geometry attribute.
Arguments:
geom_attr
the key of the geometry property as defined in the SQLAlchemy
mapper. If you use ``declarative_base`` this is the name of
the geometry attribute as defined in the mapped class.
"""
col = class_mapper(mapped_class).get_property(geom_attr).columns[0]
return col.type.srid
def create_geom_filter(request, mapped_class, geom_attr):
"""Create MapFish geometry filter based on the request params. Either
a box or within or geometry filter, depending on the request params.
Additional named arguments are passed to the spatial filter.
Arguments:
request
the request.
mapped_class
the SQLAlchemy mapped class.
geom_attr
the key of the geometry property as defined in the SQLAlchemy
mapper. If you use ``declarative_base`` this is the name of
the geometry attribute as defined in the mapped class.
"""
tolerance = float(request.params.get('tolerance', 0.0))
epsg = None
if 'epsg' in request.params:
epsg = int(request.params['epsg'])
box = request.params.get('bbox')
shape = None
if box is not None:
box = [float(x) for x in box.split(',')]
shape = Polygon(((box[0], box[1]), (box[0], box[3]),
(box[2], box[3]), (box[2], box[1]),
(box[0], box[1])))
elif 'lon' in request.params and 'lat' in request.params:
shape = Point(float(request.params['lon']),
float(request.params['lat']))
elif 'geometry' in request.params:
shape = loads(request.params['geometry'],
object_hook=GeoJSON.to_instance)
shape = asShape(shape)
if shape is None:
return None
column_epsg = _get_col_epsg(mapped_class, geom_attr)
geom_attr = getattr(mapped_class, geom_attr)
epsg = column_epsg if epsg is None else epsg
if epsg != column_epsg:
geom_attr = func.ST_Transform(geom_attr, epsg)
geometry = from_shape(shape, srid=epsg)
return func.ST_DWITHIN(geom_attr, geometry, tolerance)
def create_attr_filter(request, mapped_class):
"""Create an ``and_`` SQLAlchemy filter (a ClauseList object) based
on the request params (``queryable``, ``eq``, ``ne``, ...).
Arguments:
request
the request.
mapped_class
the SQLAlchemy mapped class.
"""
mapping = {
'eq': '__eq__',
'ne': '__ne__',
'lt': '__lt__',
'lte': '__le__',
'gt': '__gt__',
'gte': '__ge__',
'like': 'like',
'ilike': 'ilike'
}
filters = []
if 'queryable' in request.params:
queryable = request.params['queryable'].split(',')
for k in request.params:
if len(request.params[k]) <= 0 or '__' not in k:
continue
col, op = k.split("__")
if col not in queryable or op not in mapping:
continue
column = getattr(mapped_class, col)
f = getattr(column, mapping[op])(request.params[k])
filters.append(f)
return and_(*filters) if len(filters) > 0 else None
def asbool(val):
# Convert the passed value to a boolean.
if isinstance(val, six.string_types):
return val.lower() not in ['false', '0']
else:
return bool(val)
class Protocol(object):
""" Protocol class.
Session
an SQLAlchemy ``Session`` class.
mapped_class
the class mapped to a database table in the ORM.
geom_attr
the key of the geometry property as defined in the SQLAlchemy
mapper. If you use ``declarative_base`` this is the name of
the geometry attribute as defined in the mapped class.
readonly
``True`` if this protocol is read-only, ``False`` otherwise. If
``True``, the methods ``create()``, ``update()`` and ``delete()``
will set 405 (Method Not Allowed) as the response status and
return right away.
\\**kwargs
before_create
a callback function called before a feature is inserted
in the database table, the function receives the request,
the feature read from the GeoJSON document sent in the
request, and the database object to be updated. The
latter is None if this is is an actual insertion.
before_update
a callback function called before a feature is updated
in the database table, the function receives the request,
the feature read from the GeoJSON document sent in the
request, and the database object to be updated.
before_delete
a callback function called before a feature is deleted
in the database table, the function receives the request
and the database object about to be deleted.
"""
def __init__(self, Session, mapped_class, geom_attr, readonly=False,
**kwargs):
self.Session = Session
self.mapped_class = mapped_class
self.geom_attr = geom_attr
self.readonly = readonly
self.before_create = kwargs.get('before_create')
self.before_update = kwargs.get('before_update')
self.before_delete = kwargs.get('before_delete')
def _filter_attrs(self, feature, request):
""" Remove some attributes from the feature and set the geometry to None
in the feature based ``attrs`` and the ``no_geom`` parameters. """
if 'attrs' in request.params:
attrs = request.params['attrs'].split(',')
props = feature.properties
new_props = {}
for name in attrs:
if name in props:
new_props[name] = props[name]
feature.properties = new_props
if asbool(request.params.get('no_geom', False)):
feature.geometry = None
return feature
def _get_order_by(self, request):
""" Return an SA order_by """
attr = request.params.get('sort', request.params.get('order_by'))
if attr is None or not hasattr(self.mapped_class, attr):
return None
if request.params.get('dir', '').upper() == 'DESC':
return desc(getattr(self.mapped_class, attr))
else:
return asc(getattr(self.mapped_class, attr))
def _query(self, request, filter=None):
""" Build a query based on the filter and the request params,
and send the query to the database. """
limit = None
offset = None
if 'maxfeatures' in request.params:
limit = int(request.params['maxfeatures'])
if 'limit' in request.params:
limit = int(request.params['limit'])
if 'offset' in request.params:
offset = int(request.params['offset'])
if filter is None:
filter = create_filter(request, self.mapped_class, self.geom_attr)
query = self.Session().query(self.mapped_class)
if filter is not None:
query = query.filter(filter)
order_by = self._get_order_by(request)
if order_by is not None:
query = query.order_by(order_by)
query = query.limit(limit).offset(offset)
return query.all()
def count(self, request, filter=None):
""" Return the number of records matching the given filter. """
if filter is None:
filter = create_filter(request, self.mapped_class, self.geom_attr)
query = self.Session().query(self.mapped_class)
if filter is not None:
query = query.filter(filter)
return query.count()
def read(self, request, filter=None, id=None):
""" Build a query based on the filter or the idenfier, send the query
to the database, and return a Feature or a FeatureCollection. """
ret = None
if id is not None:
o = self.Session().query(self.mapped_class).get(id)
if o is None:
return HTTPNotFound()
# FIXME: we return a Feature here, not a mapped object, do
# we really want that?
ret = self._filter_attrs(o.__geo_interface__, request)
else:
objs = self._query(request, filter)
ret = FeatureCollection(
[self._filter_attrs(o.__geo_interface__, request)
for o in objs if o is not None])
return ret
def create(self, request):
""" Read the GeoJSON feature collection from the request body and
create new objects in the database. """
if self.readonly:
return HTTPMethodNotAllowed(headers={'Allow': 'GET, HEAD'})
collection = loads(request.body, object_hook=GeoJSON.to_instance)
if not isinstance(collection, FeatureCollection):
return HTTPBadRequest()
session = self.Session()
objects = []
for feature in collection.features:
create = False
obj = None
if hasattr(feature, 'id') and feature.id is not None:
obj = session.query(self.mapped_class).get(feature.id)
if self.before_create is not None:
self.before_create(request, feature, obj)
if obj is None:
obj = self.mapped_class(feature)
create = True
else:
obj.__update__(feature)
if create:
session.add(obj)
objects.append(obj)
session.flush()
collection = FeatureCollection(objects) if len(objects) > 0 else None
request.response.status_int = 201
return collection
def update(self, request, id):
""" Read the GeoJSON feature from the request body and update the
corresponding object in the database. """
if self.readonly:
return HTTPMethodNotAllowed(headers={'Allow': 'GET, HEAD'})
session = self.Session()
obj = session.query(self.mapped_class).get(id)
if obj is None:
return HTTPNotFound()
feature = loads(request.body, object_hook=GeoJSON.to_instance)
if not isinstance(feature, Feature):
return HTTPBadRequest()
if self.before_update is not None:
self.before_update(request, feature, obj)
obj.__update__(feature)
session.flush()
request.response.status_int = 200
return obj
def delete(self, request, id):
""" Remove the targeted feature from the database """
if self.readonly:
return HTTPMethodNotAllowed(headers={'Allow': 'GET, HEAD'})
session = self.Session()
obj = session.query(self.mapped_class).get(id)
if obj is None:
return HTTPNotFound()
if self.before_delete is not None:
self.before_delete(request, obj)
session.delete(obj)
return Response(status_int=204)
|
elemoine/papyrus
|
papyrus/protocol.py
|
Protocol._filter_attrs
|
python
|
def _filter_attrs(self, feature, request):
if 'attrs' in request.params:
attrs = request.params['attrs'].split(',')
props = feature.properties
new_props = {}
for name in attrs:
if name in props:
new_props[name] = props[name]
feature.properties = new_props
if asbool(request.params.get('no_geom', False)):
feature.geometry = None
return feature
|
Remove some attributes from the feature and set the geometry to None
in the feature based ``attrs`` and the ``no_geom`` parameters.
|
train
|
https://github.com/elemoine/papyrus/blob/764fb2326105df74fbd3dbcd7e58f4cb21956005/papyrus/protocol.py#L233-L246
|
[
"def asbool(val):\n # Convert the passed value to a boolean.\n if isinstance(val, six.string_types):\n return val.lower() not in ['false', '0']\n else:\n return bool(val)\n"
] |
class Protocol(object):
""" Protocol class.
Session
an SQLAlchemy ``Session`` class.
mapped_class
the class mapped to a database table in the ORM.
geom_attr
the key of the geometry property as defined in the SQLAlchemy
mapper. If you use ``declarative_base`` this is the name of
the geometry attribute as defined in the mapped class.
readonly
``True`` if this protocol is read-only, ``False`` otherwise. If
``True``, the methods ``create()``, ``update()`` and ``delete()``
will set 405 (Method Not Allowed) as the response status and
return right away.
\\**kwargs
before_create
a callback function called before a feature is inserted
in the database table, the function receives the request,
the feature read from the GeoJSON document sent in the
request, and the database object to be updated. The
latter is None if this is is an actual insertion.
before_update
a callback function called before a feature is updated
in the database table, the function receives the request,
the feature read from the GeoJSON document sent in the
request, and the database object to be updated.
before_delete
a callback function called before a feature is deleted
in the database table, the function receives the request
and the database object about to be deleted.
"""
def __init__(self, Session, mapped_class, geom_attr, readonly=False,
**kwargs):
self.Session = Session
self.mapped_class = mapped_class
self.geom_attr = geom_attr
self.readonly = readonly
self.before_create = kwargs.get('before_create')
self.before_update = kwargs.get('before_update')
self.before_delete = kwargs.get('before_delete')
def _get_order_by(self, request):
""" Return an SA order_by """
attr = request.params.get('sort', request.params.get('order_by'))
if attr is None or not hasattr(self.mapped_class, attr):
return None
if request.params.get('dir', '').upper() == 'DESC':
return desc(getattr(self.mapped_class, attr))
else:
return asc(getattr(self.mapped_class, attr))
def _query(self, request, filter=None):
""" Build a query based on the filter and the request params,
and send the query to the database. """
limit = None
offset = None
if 'maxfeatures' in request.params:
limit = int(request.params['maxfeatures'])
if 'limit' in request.params:
limit = int(request.params['limit'])
if 'offset' in request.params:
offset = int(request.params['offset'])
if filter is None:
filter = create_filter(request, self.mapped_class, self.geom_attr)
query = self.Session().query(self.mapped_class)
if filter is not None:
query = query.filter(filter)
order_by = self._get_order_by(request)
if order_by is not None:
query = query.order_by(order_by)
query = query.limit(limit).offset(offset)
return query.all()
def count(self, request, filter=None):
""" Return the number of records matching the given filter. """
if filter is None:
filter = create_filter(request, self.mapped_class, self.geom_attr)
query = self.Session().query(self.mapped_class)
if filter is not None:
query = query.filter(filter)
return query.count()
def read(self, request, filter=None, id=None):
""" Build a query based on the filter or the idenfier, send the query
to the database, and return a Feature or a FeatureCollection. """
ret = None
if id is not None:
o = self.Session().query(self.mapped_class).get(id)
if o is None:
return HTTPNotFound()
# FIXME: we return a Feature here, not a mapped object, do
# we really want that?
ret = self._filter_attrs(o.__geo_interface__, request)
else:
objs = self._query(request, filter)
ret = FeatureCollection(
[self._filter_attrs(o.__geo_interface__, request)
for o in objs if o is not None])
return ret
def create(self, request):
""" Read the GeoJSON feature collection from the request body and
create new objects in the database. """
if self.readonly:
return HTTPMethodNotAllowed(headers={'Allow': 'GET, HEAD'})
collection = loads(request.body, object_hook=GeoJSON.to_instance)
if not isinstance(collection, FeatureCollection):
return HTTPBadRequest()
session = self.Session()
objects = []
for feature in collection.features:
create = False
obj = None
if hasattr(feature, 'id') and feature.id is not None:
obj = session.query(self.mapped_class).get(feature.id)
if self.before_create is not None:
self.before_create(request, feature, obj)
if obj is None:
obj = self.mapped_class(feature)
create = True
else:
obj.__update__(feature)
if create:
session.add(obj)
objects.append(obj)
session.flush()
collection = FeatureCollection(objects) if len(objects) > 0 else None
request.response.status_int = 201
return collection
def update(self, request, id):
""" Read the GeoJSON feature from the request body and update the
corresponding object in the database. """
if self.readonly:
return HTTPMethodNotAllowed(headers={'Allow': 'GET, HEAD'})
session = self.Session()
obj = session.query(self.mapped_class).get(id)
if obj is None:
return HTTPNotFound()
feature = loads(request.body, object_hook=GeoJSON.to_instance)
if not isinstance(feature, Feature):
return HTTPBadRequest()
if self.before_update is not None:
self.before_update(request, feature, obj)
obj.__update__(feature)
session.flush()
request.response.status_int = 200
return obj
def delete(self, request, id):
""" Remove the targeted feature from the database """
if self.readonly:
return HTTPMethodNotAllowed(headers={'Allow': 'GET, HEAD'})
session = self.Session()
obj = session.query(self.mapped_class).get(id)
if obj is None:
return HTTPNotFound()
if self.before_delete is not None:
self.before_delete(request, obj)
session.delete(obj)
return Response(status_int=204)
|
elemoine/papyrus
|
papyrus/protocol.py
|
Protocol._get_order_by
|
python
|
def _get_order_by(self, request):
attr = request.params.get('sort', request.params.get('order_by'))
if attr is None or not hasattr(self.mapped_class, attr):
return None
if request.params.get('dir', '').upper() == 'DESC':
return desc(getattr(self.mapped_class, attr))
else:
return asc(getattr(self.mapped_class, attr))
|
Return an SA order_by
|
train
|
https://github.com/elemoine/papyrus/blob/764fb2326105df74fbd3dbcd7e58f4cb21956005/papyrus/protocol.py#L248-L256
| null |
class Protocol(object):
""" Protocol class.
Session
an SQLAlchemy ``Session`` class.
mapped_class
the class mapped to a database table in the ORM.
geom_attr
the key of the geometry property as defined in the SQLAlchemy
mapper. If you use ``declarative_base`` this is the name of
the geometry attribute as defined in the mapped class.
readonly
``True`` if this protocol is read-only, ``False`` otherwise. If
``True``, the methods ``create()``, ``update()`` and ``delete()``
will set 405 (Method Not Allowed) as the response status and
return right away.
\\**kwargs
before_create
a callback function called before a feature is inserted
in the database table, the function receives the request,
the feature read from the GeoJSON document sent in the
request, and the database object to be updated. The
latter is None if this is is an actual insertion.
before_update
a callback function called before a feature is updated
in the database table, the function receives the request,
the feature read from the GeoJSON document sent in the
request, and the database object to be updated.
before_delete
a callback function called before a feature is deleted
in the database table, the function receives the request
and the database object about to be deleted.
"""
def __init__(self, Session, mapped_class, geom_attr, readonly=False,
**kwargs):
self.Session = Session
self.mapped_class = mapped_class
self.geom_attr = geom_attr
self.readonly = readonly
self.before_create = kwargs.get('before_create')
self.before_update = kwargs.get('before_update')
self.before_delete = kwargs.get('before_delete')
def _filter_attrs(self, feature, request):
""" Remove some attributes from the feature and set the geometry to None
in the feature based ``attrs`` and the ``no_geom`` parameters. """
if 'attrs' in request.params:
attrs = request.params['attrs'].split(',')
props = feature.properties
new_props = {}
for name in attrs:
if name in props:
new_props[name] = props[name]
feature.properties = new_props
if asbool(request.params.get('no_geom', False)):
feature.geometry = None
return feature
def _query(self, request, filter=None):
""" Build a query based on the filter and the request params,
and send the query to the database. """
limit = None
offset = None
if 'maxfeatures' in request.params:
limit = int(request.params['maxfeatures'])
if 'limit' in request.params:
limit = int(request.params['limit'])
if 'offset' in request.params:
offset = int(request.params['offset'])
if filter is None:
filter = create_filter(request, self.mapped_class, self.geom_attr)
query = self.Session().query(self.mapped_class)
if filter is not None:
query = query.filter(filter)
order_by = self._get_order_by(request)
if order_by is not None:
query = query.order_by(order_by)
query = query.limit(limit).offset(offset)
return query.all()
def count(self, request, filter=None):
""" Return the number of records matching the given filter. """
if filter is None:
filter = create_filter(request, self.mapped_class, self.geom_attr)
query = self.Session().query(self.mapped_class)
if filter is not None:
query = query.filter(filter)
return query.count()
def read(self, request, filter=None, id=None):
""" Build a query based on the filter or the idenfier, send the query
to the database, and return a Feature or a FeatureCollection. """
ret = None
if id is not None:
o = self.Session().query(self.mapped_class).get(id)
if o is None:
return HTTPNotFound()
# FIXME: we return a Feature here, not a mapped object, do
# we really want that?
ret = self._filter_attrs(o.__geo_interface__, request)
else:
objs = self._query(request, filter)
ret = FeatureCollection(
[self._filter_attrs(o.__geo_interface__, request)
for o in objs if o is not None])
return ret
def create(self, request):
""" Read the GeoJSON feature collection from the request body and
create new objects in the database. """
if self.readonly:
return HTTPMethodNotAllowed(headers={'Allow': 'GET, HEAD'})
collection = loads(request.body, object_hook=GeoJSON.to_instance)
if not isinstance(collection, FeatureCollection):
return HTTPBadRequest()
session = self.Session()
objects = []
for feature in collection.features:
create = False
obj = None
if hasattr(feature, 'id') and feature.id is not None:
obj = session.query(self.mapped_class).get(feature.id)
if self.before_create is not None:
self.before_create(request, feature, obj)
if obj is None:
obj = self.mapped_class(feature)
create = True
else:
obj.__update__(feature)
if create:
session.add(obj)
objects.append(obj)
session.flush()
collection = FeatureCollection(objects) if len(objects) > 0 else None
request.response.status_int = 201
return collection
def update(self, request, id):
""" Read the GeoJSON feature from the request body and update the
corresponding object in the database. """
if self.readonly:
return HTTPMethodNotAllowed(headers={'Allow': 'GET, HEAD'})
session = self.Session()
obj = session.query(self.mapped_class).get(id)
if obj is None:
return HTTPNotFound()
feature = loads(request.body, object_hook=GeoJSON.to_instance)
if not isinstance(feature, Feature):
return HTTPBadRequest()
if self.before_update is not None:
self.before_update(request, feature, obj)
obj.__update__(feature)
session.flush()
request.response.status_int = 200
return obj
def delete(self, request, id):
""" Remove the targeted feature from the database """
if self.readonly:
return HTTPMethodNotAllowed(headers={'Allow': 'GET, HEAD'})
session = self.Session()
obj = session.query(self.mapped_class).get(id)
if obj is None:
return HTTPNotFound()
if self.before_delete is not None:
self.before_delete(request, obj)
session.delete(obj)
return Response(status_int=204)
|
elemoine/papyrus
|
papyrus/protocol.py
|
Protocol._query
|
python
|
def _query(self, request, filter=None):
limit = None
offset = None
if 'maxfeatures' in request.params:
limit = int(request.params['maxfeatures'])
if 'limit' in request.params:
limit = int(request.params['limit'])
if 'offset' in request.params:
offset = int(request.params['offset'])
if filter is None:
filter = create_filter(request, self.mapped_class, self.geom_attr)
query = self.Session().query(self.mapped_class)
if filter is not None:
query = query.filter(filter)
order_by = self._get_order_by(request)
if order_by is not None:
query = query.order_by(order_by)
query = query.limit(limit).offset(offset)
return query.all()
|
Build a query based on the filter and the request params,
and send the query to the database.
|
train
|
https://github.com/elemoine/papyrus/blob/764fb2326105df74fbd3dbcd7e58f4cb21956005/papyrus/protocol.py#L258-L278
|
[
"def create_filter(request, mapped_class, geom_attr, **kwargs):\n \"\"\" Create MapFish default filter based on the request params.\n\n Arguments:\n\n request\n the request.\n\n mapped_class\n the SQLAlchemy mapped class.\n\n geom_attr\n the key of the geometry property as defined in the SQLAlchemy\n mapper. If you use ``declarative_base`` this is the name of\n the geometry attribute as defined in the mapped class.\n\n \\\\**kwargs\n additional arguments passed to ``create_geom_filter()``.\n \"\"\"\n attr_filter = create_attr_filter(request, mapped_class)\n geom_filter = create_geom_filter(request, mapped_class, geom_attr,\n **kwargs)\n if geom_filter is None and attr_filter is None:\n return None\n if geom_filter is None:\n return attr_filter\n if attr_filter is None:\n return geom_filter\n return and_(geom_filter, attr_filter)\n",
"def _get_order_by(self, request):\n \"\"\" Return an SA order_by \"\"\"\n attr = request.params.get('sort', request.params.get('order_by'))\n if attr is None or not hasattr(self.mapped_class, attr):\n return None\n if request.params.get('dir', '').upper() == 'DESC':\n return desc(getattr(self.mapped_class, attr))\n else:\n return asc(getattr(self.mapped_class, attr))\n"
] |
class Protocol(object):
""" Protocol class.
Session
an SQLAlchemy ``Session`` class.
mapped_class
the class mapped to a database table in the ORM.
geom_attr
the key of the geometry property as defined in the SQLAlchemy
mapper. If you use ``declarative_base`` this is the name of
the geometry attribute as defined in the mapped class.
readonly
``True`` if this protocol is read-only, ``False`` otherwise. If
``True``, the methods ``create()``, ``update()`` and ``delete()``
will set 405 (Method Not Allowed) as the response status and
return right away.
\\**kwargs
before_create
a callback function called before a feature is inserted
in the database table, the function receives the request,
the feature read from the GeoJSON document sent in the
request, and the database object to be updated. The
latter is None if this is is an actual insertion.
before_update
a callback function called before a feature is updated
in the database table, the function receives the request,
the feature read from the GeoJSON document sent in the
request, and the database object to be updated.
before_delete
a callback function called before a feature is deleted
in the database table, the function receives the request
and the database object about to be deleted.
"""
def __init__(self, Session, mapped_class, geom_attr, readonly=False,
**kwargs):
self.Session = Session
self.mapped_class = mapped_class
self.geom_attr = geom_attr
self.readonly = readonly
self.before_create = kwargs.get('before_create')
self.before_update = kwargs.get('before_update')
self.before_delete = kwargs.get('before_delete')
def _filter_attrs(self, feature, request):
""" Remove some attributes from the feature and set the geometry to None
in the feature based ``attrs`` and the ``no_geom`` parameters. """
if 'attrs' in request.params:
attrs = request.params['attrs'].split(',')
props = feature.properties
new_props = {}
for name in attrs:
if name in props:
new_props[name] = props[name]
feature.properties = new_props
if asbool(request.params.get('no_geom', False)):
feature.geometry = None
return feature
def _get_order_by(self, request):
""" Return an SA order_by """
attr = request.params.get('sort', request.params.get('order_by'))
if attr is None or not hasattr(self.mapped_class, attr):
return None
if request.params.get('dir', '').upper() == 'DESC':
return desc(getattr(self.mapped_class, attr))
else:
return asc(getattr(self.mapped_class, attr))
def count(self, request, filter=None):
""" Return the number of records matching the given filter. """
if filter is None:
filter = create_filter(request, self.mapped_class, self.geom_attr)
query = self.Session().query(self.mapped_class)
if filter is not None:
query = query.filter(filter)
return query.count()
def read(self, request, filter=None, id=None):
""" Build a query based on the filter or the idenfier, send the query
to the database, and return a Feature or a FeatureCollection. """
ret = None
if id is not None:
o = self.Session().query(self.mapped_class).get(id)
if o is None:
return HTTPNotFound()
# FIXME: we return a Feature here, not a mapped object, do
# we really want that?
ret = self._filter_attrs(o.__geo_interface__, request)
else:
objs = self._query(request, filter)
ret = FeatureCollection(
[self._filter_attrs(o.__geo_interface__, request)
for o in objs if o is not None])
return ret
def create(self, request):
""" Read the GeoJSON feature collection from the request body and
create new objects in the database. """
if self.readonly:
return HTTPMethodNotAllowed(headers={'Allow': 'GET, HEAD'})
collection = loads(request.body, object_hook=GeoJSON.to_instance)
if not isinstance(collection, FeatureCollection):
return HTTPBadRequest()
session = self.Session()
objects = []
for feature in collection.features:
create = False
obj = None
if hasattr(feature, 'id') and feature.id is not None:
obj = session.query(self.mapped_class).get(feature.id)
if self.before_create is not None:
self.before_create(request, feature, obj)
if obj is None:
obj = self.mapped_class(feature)
create = True
else:
obj.__update__(feature)
if create:
session.add(obj)
objects.append(obj)
session.flush()
collection = FeatureCollection(objects) if len(objects) > 0 else None
request.response.status_int = 201
return collection
def update(self, request, id):
""" Read the GeoJSON feature from the request body and update the
corresponding object in the database. """
if self.readonly:
return HTTPMethodNotAllowed(headers={'Allow': 'GET, HEAD'})
session = self.Session()
obj = session.query(self.mapped_class).get(id)
if obj is None:
return HTTPNotFound()
feature = loads(request.body, object_hook=GeoJSON.to_instance)
if not isinstance(feature, Feature):
return HTTPBadRequest()
if self.before_update is not None:
self.before_update(request, feature, obj)
obj.__update__(feature)
session.flush()
request.response.status_int = 200
return obj
def delete(self, request, id):
""" Remove the targeted feature from the database """
if self.readonly:
return HTTPMethodNotAllowed(headers={'Allow': 'GET, HEAD'})
session = self.Session()
obj = session.query(self.mapped_class).get(id)
if obj is None:
return HTTPNotFound()
if self.before_delete is not None:
self.before_delete(request, obj)
session.delete(obj)
return Response(status_int=204)
|
elemoine/papyrus
|
papyrus/protocol.py
|
Protocol.count
|
python
|
def count(self, request, filter=None):
if filter is None:
filter = create_filter(request, self.mapped_class, self.geom_attr)
query = self.Session().query(self.mapped_class)
if filter is not None:
query = query.filter(filter)
return query.count()
|
Return the number of records matching the given filter.
|
train
|
https://github.com/elemoine/papyrus/blob/764fb2326105df74fbd3dbcd7e58f4cb21956005/papyrus/protocol.py#L280-L287
|
[
"def create_filter(request, mapped_class, geom_attr, **kwargs):\n \"\"\" Create MapFish default filter based on the request params.\n\n Arguments:\n\n request\n the request.\n\n mapped_class\n the SQLAlchemy mapped class.\n\n geom_attr\n the key of the geometry property as defined in the SQLAlchemy\n mapper. If you use ``declarative_base`` this is the name of\n the geometry attribute as defined in the mapped class.\n\n \\\\**kwargs\n additional arguments passed to ``create_geom_filter()``.\n \"\"\"\n attr_filter = create_attr_filter(request, mapped_class)\n geom_filter = create_geom_filter(request, mapped_class, geom_attr,\n **kwargs)\n if geom_filter is None and attr_filter is None:\n return None\n if geom_filter is None:\n return attr_filter\n if attr_filter is None:\n return geom_filter\n return and_(geom_filter, attr_filter)\n"
] |
class Protocol(object):
""" Protocol class.
Session
an SQLAlchemy ``Session`` class.
mapped_class
the class mapped to a database table in the ORM.
geom_attr
the key of the geometry property as defined in the SQLAlchemy
mapper. If you use ``declarative_base`` this is the name of
the geometry attribute as defined in the mapped class.
readonly
``True`` if this protocol is read-only, ``False`` otherwise. If
``True``, the methods ``create()``, ``update()`` and ``delete()``
will set 405 (Method Not Allowed) as the response status and
return right away.
\\**kwargs
before_create
a callback function called before a feature is inserted
in the database table, the function receives the request,
the feature read from the GeoJSON document sent in the
request, and the database object to be updated. The
latter is None if this is is an actual insertion.
before_update
a callback function called before a feature is updated
in the database table, the function receives the request,
the feature read from the GeoJSON document sent in the
request, and the database object to be updated.
before_delete
a callback function called before a feature is deleted
in the database table, the function receives the request
and the database object about to be deleted.
"""
def __init__(self, Session, mapped_class, geom_attr, readonly=False,
**kwargs):
self.Session = Session
self.mapped_class = mapped_class
self.geom_attr = geom_attr
self.readonly = readonly
self.before_create = kwargs.get('before_create')
self.before_update = kwargs.get('before_update')
self.before_delete = kwargs.get('before_delete')
def _filter_attrs(self, feature, request):
""" Remove some attributes from the feature and set the geometry to None
in the feature based ``attrs`` and the ``no_geom`` parameters. """
if 'attrs' in request.params:
attrs = request.params['attrs'].split(',')
props = feature.properties
new_props = {}
for name in attrs:
if name in props:
new_props[name] = props[name]
feature.properties = new_props
if asbool(request.params.get('no_geom', False)):
feature.geometry = None
return feature
def _get_order_by(self, request):
""" Return an SA order_by """
attr = request.params.get('sort', request.params.get('order_by'))
if attr is None or not hasattr(self.mapped_class, attr):
return None
if request.params.get('dir', '').upper() == 'DESC':
return desc(getattr(self.mapped_class, attr))
else:
return asc(getattr(self.mapped_class, attr))
def _query(self, request, filter=None):
""" Build a query based on the filter and the request params,
and send the query to the database. """
limit = None
offset = None
if 'maxfeatures' in request.params:
limit = int(request.params['maxfeatures'])
if 'limit' in request.params:
limit = int(request.params['limit'])
if 'offset' in request.params:
offset = int(request.params['offset'])
if filter is None:
filter = create_filter(request, self.mapped_class, self.geom_attr)
query = self.Session().query(self.mapped_class)
if filter is not None:
query = query.filter(filter)
order_by = self._get_order_by(request)
if order_by is not None:
query = query.order_by(order_by)
query = query.limit(limit).offset(offset)
return query.all()
def read(self, request, filter=None, id=None):
""" Build a query based on the filter or the idenfier, send the query
to the database, and return a Feature or a FeatureCollection. """
ret = None
if id is not None:
o = self.Session().query(self.mapped_class).get(id)
if o is None:
return HTTPNotFound()
# FIXME: we return a Feature here, not a mapped object, do
# we really want that?
ret = self._filter_attrs(o.__geo_interface__, request)
else:
objs = self._query(request, filter)
ret = FeatureCollection(
[self._filter_attrs(o.__geo_interface__, request)
for o in objs if o is not None])
return ret
def create(self, request):
""" Read the GeoJSON feature collection from the request body and
create new objects in the database. """
if self.readonly:
return HTTPMethodNotAllowed(headers={'Allow': 'GET, HEAD'})
collection = loads(request.body, object_hook=GeoJSON.to_instance)
if not isinstance(collection, FeatureCollection):
return HTTPBadRequest()
session = self.Session()
objects = []
for feature in collection.features:
create = False
obj = None
if hasattr(feature, 'id') and feature.id is not None:
obj = session.query(self.mapped_class).get(feature.id)
if self.before_create is not None:
self.before_create(request, feature, obj)
if obj is None:
obj = self.mapped_class(feature)
create = True
else:
obj.__update__(feature)
if create:
session.add(obj)
objects.append(obj)
session.flush()
collection = FeatureCollection(objects) if len(objects) > 0 else None
request.response.status_int = 201
return collection
def update(self, request, id):
""" Read the GeoJSON feature from the request body and update the
corresponding object in the database. """
if self.readonly:
return HTTPMethodNotAllowed(headers={'Allow': 'GET, HEAD'})
session = self.Session()
obj = session.query(self.mapped_class).get(id)
if obj is None:
return HTTPNotFound()
feature = loads(request.body, object_hook=GeoJSON.to_instance)
if not isinstance(feature, Feature):
return HTTPBadRequest()
if self.before_update is not None:
self.before_update(request, feature, obj)
obj.__update__(feature)
session.flush()
request.response.status_int = 200
return obj
def delete(self, request, id):
""" Remove the targeted feature from the database """
if self.readonly:
return HTTPMethodNotAllowed(headers={'Allow': 'GET, HEAD'})
session = self.Session()
obj = session.query(self.mapped_class).get(id)
if obj is None:
return HTTPNotFound()
if self.before_delete is not None:
self.before_delete(request, obj)
session.delete(obj)
return Response(status_int=204)
|
elemoine/papyrus
|
papyrus/protocol.py
|
Protocol.read
|
python
|
def read(self, request, filter=None, id=None):
ret = None
if id is not None:
o = self.Session().query(self.mapped_class).get(id)
if o is None:
return HTTPNotFound()
# FIXME: we return a Feature here, not a mapped object, do
# we really want that?
ret = self._filter_attrs(o.__geo_interface__, request)
else:
objs = self._query(request, filter)
ret = FeatureCollection(
[self._filter_attrs(o.__geo_interface__, request)
for o in objs if o is not None])
return ret
|
Build a query based on the filter or the idenfier, send the query
to the database, and return a Feature or a FeatureCollection.
|
train
|
https://github.com/elemoine/papyrus/blob/764fb2326105df74fbd3dbcd7e58f4cb21956005/papyrus/protocol.py#L289-L305
|
[
"def _filter_attrs(self, feature, request):\n \"\"\" Remove some attributes from the feature and set the geometry to None\n in the feature based ``attrs`` and the ``no_geom`` parameters. \"\"\"\n if 'attrs' in request.params:\n attrs = request.params['attrs'].split(',')\n props = feature.properties\n new_props = {}\n for name in attrs:\n if name in props:\n new_props[name] = props[name]\n feature.properties = new_props\n if asbool(request.params.get('no_geom', False)):\n feature.geometry = None\n return feature\n",
"def _query(self, request, filter=None):\n \"\"\" Build a query based on the filter and the request params,\n and send the query to the database. \"\"\"\n limit = None\n offset = None\n if 'maxfeatures' in request.params:\n limit = int(request.params['maxfeatures'])\n if 'limit' in request.params:\n limit = int(request.params['limit'])\n if 'offset' in request.params:\n offset = int(request.params['offset'])\n if filter is None:\n filter = create_filter(request, self.mapped_class, self.geom_attr)\n query = self.Session().query(self.mapped_class)\n if filter is not None:\n query = query.filter(filter)\n order_by = self._get_order_by(request)\n if order_by is not None:\n query = query.order_by(order_by)\n query = query.limit(limit).offset(offset)\n return query.all()\n"
] |
class Protocol(object):
""" Protocol class.
Session
an SQLAlchemy ``Session`` class.
mapped_class
the class mapped to a database table in the ORM.
geom_attr
the key of the geometry property as defined in the SQLAlchemy
mapper. If you use ``declarative_base`` this is the name of
the geometry attribute as defined in the mapped class.
readonly
``True`` if this protocol is read-only, ``False`` otherwise. If
``True``, the methods ``create()``, ``update()`` and ``delete()``
will set 405 (Method Not Allowed) as the response status and
return right away.
\\**kwargs
before_create
a callback function called before a feature is inserted
in the database table, the function receives the request,
the feature read from the GeoJSON document sent in the
request, and the database object to be updated. The
latter is None if this is is an actual insertion.
before_update
a callback function called before a feature is updated
in the database table, the function receives the request,
the feature read from the GeoJSON document sent in the
request, and the database object to be updated.
before_delete
a callback function called before a feature is deleted
in the database table, the function receives the request
and the database object about to be deleted.
"""
def __init__(self, Session, mapped_class, geom_attr, readonly=False,
**kwargs):
self.Session = Session
self.mapped_class = mapped_class
self.geom_attr = geom_attr
self.readonly = readonly
self.before_create = kwargs.get('before_create')
self.before_update = kwargs.get('before_update')
self.before_delete = kwargs.get('before_delete')
def _filter_attrs(self, feature, request):
""" Remove some attributes from the feature and set the geometry to None
in the feature based ``attrs`` and the ``no_geom`` parameters. """
if 'attrs' in request.params:
attrs = request.params['attrs'].split(',')
props = feature.properties
new_props = {}
for name in attrs:
if name in props:
new_props[name] = props[name]
feature.properties = new_props
if asbool(request.params.get('no_geom', False)):
feature.geometry = None
return feature
def _get_order_by(self, request):
""" Return an SA order_by """
attr = request.params.get('sort', request.params.get('order_by'))
if attr is None or not hasattr(self.mapped_class, attr):
return None
if request.params.get('dir', '').upper() == 'DESC':
return desc(getattr(self.mapped_class, attr))
else:
return asc(getattr(self.mapped_class, attr))
def _query(self, request, filter=None):
""" Build a query based on the filter and the request params,
and send the query to the database. """
limit = None
offset = None
if 'maxfeatures' in request.params:
limit = int(request.params['maxfeatures'])
if 'limit' in request.params:
limit = int(request.params['limit'])
if 'offset' in request.params:
offset = int(request.params['offset'])
if filter is None:
filter = create_filter(request, self.mapped_class, self.geom_attr)
query = self.Session().query(self.mapped_class)
if filter is not None:
query = query.filter(filter)
order_by = self._get_order_by(request)
if order_by is not None:
query = query.order_by(order_by)
query = query.limit(limit).offset(offset)
return query.all()
def count(self, request, filter=None):
""" Return the number of records matching the given filter. """
if filter is None:
filter = create_filter(request, self.mapped_class, self.geom_attr)
query = self.Session().query(self.mapped_class)
if filter is not None:
query = query.filter(filter)
return query.count()
def create(self, request):
""" Read the GeoJSON feature collection from the request body and
create new objects in the database. """
if self.readonly:
return HTTPMethodNotAllowed(headers={'Allow': 'GET, HEAD'})
collection = loads(request.body, object_hook=GeoJSON.to_instance)
if not isinstance(collection, FeatureCollection):
return HTTPBadRequest()
session = self.Session()
objects = []
for feature in collection.features:
create = False
obj = None
if hasattr(feature, 'id') and feature.id is not None:
obj = session.query(self.mapped_class).get(feature.id)
if self.before_create is not None:
self.before_create(request, feature, obj)
if obj is None:
obj = self.mapped_class(feature)
create = True
else:
obj.__update__(feature)
if create:
session.add(obj)
objects.append(obj)
session.flush()
collection = FeatureCollection(objects) if len(objects) > 0 else None
request.response.status_int = 201
return collection
def update(self, request, id):
""" Read the GeoJSON feature from the request body and update the
corresponding object in the database. """
if self.readonly:
return HTTPMethodNotAllowed(headers={'Allow': 'GET, HEAD'})
session = self.Session()
obj = session.query(self.mapped_class).get(id)
if obj is None:
return HTTPNotFound()
feature = loads(request.body, object_hook=GeoJSON.to_instance)
if not isinstance(feature, Feature):
return HTTPBadRequest()
if self.before_update is not None:
self.before_update(request, feature, obj)
obj.__update__(feature)
session.flush()
request.response.status_int = 200
return obj
def delete(self, request, id):
""" Remove the targeted feature from the database """
if self.readonly:
return HTTPMethodNotAllowed(headers={'Allow': 'GET, HEAD'})
session = self.Session()
obj = session.query(self.mapped_class).get(id)
if obj is None:
return HTTPNotFound()
if self.before_delete is not None:
self.before_delete(request, obj)
session.delete(obj)
return Response(status_int=204)
|
elemoine/papyrus
|
papyrus/protocol.py
|
Protocol.create
|
python
|
def create(self, request):
if self.readonly:
return HTTPMethodNotAllowed(headers={'Allow': 'GET, HEAD'})
collection = loads(request.body, object_hook=GeoJSON.to_instance)
if not isinstance(collection, FeatureCollection):
return HTTPBadRequest()
session = self.Session()
objects = []
for feature in collection.features:
create = False
obj = None
if hasattr(feature, 'id') and feature.id is not None:
obj = session.query(self.mapped_class).get(feature.id)
if self.before_create is not None:
self.before_create(request, feature, obj)
if obj is None:
obj = self.mapped_class(feature)
create = True
else:
obj.__update__(feature)
if create:
session.add(obj)
objects.append(obj)
session.flush()
collection = FeatureCollection(objects) if len(objects) > 0 else None
request.response.status_int = 201
return collection
|
Read the GeoJSON feature collection from the request body and
create new objects in the database.
|
train
|
https://github.com/elemoine/papyrus/blob/764fb2326105df74fbd3dbcd7e58f4cb21956005/papyrus/protocol.py#L307-L335
| null |
class Protocol(object):
""" Protocol class.
Session
an SQLAlchemy ``Session`` class.
mapped_class
the class mapped to a database table in the ORM.
geom_attr
the key of the geometry property as defined in the SQLAlchemy
mapper. If you use ``declarative_base`` this is the name of
the geometry attribute as defined in the mapped class.
readonly
``True`` if this protocol is read-only, ``False`` otherwise. If
``True``, the methods ``create()``, ``update()`` and ``delete()``
will set 405 (Method Not Allowed) as the response status and
return right away.
\\**kwargs
before_create
a callback function called before a feature is inserted
in the database table, the function receives the request,
the feature read from the GeoJSON document sent in the
request, and the database object to be updated. The
latter is None if this is is an actual insertion.
before_update
a callback function called before a feature is updated
in the database table, the function receives the request,
the feature read from the GeoJSON document sent in the
request, and the database object to be updated.
before_delete
a callback function called before a feature is deleted
in the database table, the function receives the request
and the database object about to be deleted.
"""
def __init__(self, Session, mapped_class, geom_attr, readonly=False,
**kwargs):
self.Session = Session
self.mapped_class = mapped_class
self.geom_attr = geom_attr
self.readonly = readonly
self.before_create = kwargs.get('before_create')
self.before_update = kwargs.get('before_update')
self.before_delete = kwargs.get('before_delete')
def _filter_attrs(self, feature, request):
""" Remove some attributes from the feature and set the geometry to None
in the feature based ``attrs`` and the ``no_geom`` parameters. """
if 'attrs' in request.params:
attrs = request.params['attrs'].split(',')
props = feature.properties
new_props = {}
for name in attrs:
if name in props:
new_props[name] = props[name]
feature.properties = new_props
if asbool(request.params.get('no_geom', False)):
feature.geometry = None
return feature
def _get_order_by(self, request):
""" Return an SA order_by """
attr = request.params.get('sort', request.params.get('order_by'))
if attr is None or not hasattr(self.mapped_class, attr):
return None
if request.params.get('dir', '').upper() == 'DESC':
return desc(getattr(self.mapped_class, attr))
else:
return asc(getattr(self.mapped_class, attr))
def _query(self, request, filter=None):
""" Build a query based on the filter and the request params,
and send the query to the database. """
limit = None
offset = None
if 'maxfeatures' in request.params:
limit = int(request.params['maxfeatures'])
if 'limit' in request.params:
limit = int(request.params['limit'])
if 'offset' in request.params:
offset = int(request.params['offset'])
if filter is None:
filter = create_filter(request, self.mapped_class, self.geom_attr)
query = self.Session().query(self.mapped_class)
if filter is not None:
query = query.filter(filter)
order_by = self._get_order_by(request)
if order_by is not None:
query = query.order_by(order_by)
query = query.limit(limit).offset(offset)
return query.all()
def count(self, request, filter=None):
""" Return the number of records matching the given filter. """
if filter is None:
filter = create_filter(request, self.mapped_class, self.geom_attr)
query = self.Session().query(self.mapped_class)
if filter is not None:
query = query.filter(filter)
return query.count()
def read(self, request, filter=None, id=None):
""" Build a query based on the filter or the idenfier, send the query
to the database, and return a Feature or a FeatureCollection. """
ret = None
if id is not None:
o = self.Session().query(self.mapped_class).get(id)
if o is None:
return HTTPNotFound()
# FIXME: we return a Feature here, not a mapped object, do
# we really want that?
ret = self._filter_attrs(o.__geo_interface__, request)
else:
objs = self._query(request, filter)
ret = FeatureCollection(
[self._filter_attrs(o.__geo_interface__, request)
for o in objs if o is not None])
return ret
def update(self, request, id):
""" Read the GeoJSON feature from the request body and update the
corresponding object in the database. """
if self.readonly:
return HTTPMethodNotAllowed(headers={'Allow': 'GET, HEAD'})
session = self.Session()
obj = session.query(self.mapped_class).get(id)
if obj is None:
return HTTPNotFound()
feature = loads(request.body, object_hook=GeoJSON.to_instance)
if not isinstance(feature, Feature):
return HTTPBadRequest()
if self.before_update is not None:
self.before_update(request, feature, obj)
obj.__update__(feature)
session.flush()
request.response.status_int = 200
return obj
def delete(self, request, id):
""" Remove the targeted feature from the database """
if self.readonly:
return HTTPMethodNotAllowed(headers={'Allow': 'GET, HEAD'})
session = self.Session()
obj = session.query(self.mapped_class).get(id)
if obj is None:
return HTTPNotFound()
if self.before_delete is not None:
self.before_delete(request, obj)
session.delete(obj)
return Response(status_int=204)
|
elemoine/papyrus
|
papyrus/protocol.py
|
Protocol.update
|
python
|
def update(self, request, id):
if self.readonly:
return HTTPMethodNotAllowed(headers={'Allow': 'GET, HEAD'})
session = self.Session()
obj = session.query(self.mapped_class).get(id)
if obj is None:
return HTTPNotFound()
feature = loads(request.body, object_hook=GeoJSON.to_instance)
if not isinstance(feature, Feature):
return HTTPBadRequest()
if self.before_update is not None:
self.before_update(request, feature, obj)
obj.__update__(feature)
session.flush()
request.response.status_int = 200
return obj
|
Read the GeoJSON feature from the request body and update the
corresponding object in the database.
|
train
|
https://github.com/elemoine/papyrus/blob/764fb2326105df74fbd3dbcd7e58f4cb21956005/papyrus/protocol.py#L337-L354
| null |
class Protocol(object):
""" Protocol class.
Session
an SQLAlchemy ``Session`` class.
mapped_class
the class mapped to a database table in the ORM.
geom_attr
the key of the geometry property as defined in the SQLAlchemy
mapper. If you use ``declarative_base`` this is the name of
the geometry attribute as defined in the mapped class.
readonly
``True`` if this protocol is read-only, ``False`` otherwise. If
``True``, the methods ``create()``, ``update()`` and ``delete()``
will set 405 (Method Not Allowed) as the response status and
return right away.
\\**kwargs
before_create
a callback function called before a feature is inserted
in the database table, the function receives the request,
the feature read from the GeoJSON document sent in the
request, and the database object to be updated. The
latter is None if this is is an actual insertion.
before_update
a callback function called before a feature is updated
in the database table, the function receives the request,
the feature read from the GeoJSON document sent in the
request, and the database object to be updated.
before_delete
a callback function called before a feature is deleted
in the database table, the function receives the request
and the database object about to be deleted.
"""
def __init__(self, Session, mapped_class, geom_attr, readonly=False,
**kwargs):
self.Session = Session
self.mapped_class = mapped_class
self.geom_attr = geom_attr
self.readonly = readonly
self.before_create = kwargs.get('before_create')
self.before_update = kwargs.get('before_update')
self.before_delete = kwargs.get('before_delete')
def _filter_attrs(self, feature, request):
""" Remove some attributes from the feature and set the geometry to None
in the feature based ``attrs`` and the ``no_geom`` parameters. """
if 'attrs' in request.params:
attrs = request.params['attrs'].split(',')
props = feature.properties
new_props = {}
for name in attrs:
if name in props:
new_props[name] = props[name]
feature.properties = new_props
if asbool(request.params.get('no_geom', False)):
feature.geometry = None
return feature
def _get_order_by(self, request):
""" Return an SA order_by """
attr = request.params.get('sort', request.params.get('order_by'))
if attr is None or not hasattr(self.mapped_class, attr):
return None
if request.params.get('dir', '').upper() == 'DESC':
return desc(getattr(self.mapped_class, attr))
else:
return asc(getattr(self.mapped_class, attr))
def _query(self, request, filter=None):
""" Build a query based on the filter and the request params,
and send the query to the database. """
limit = None
offset = None
if 'maxfeatures' in request.params:
limit = int(request.params['maxfeatures'])
if 'limit' in request.params:
limit = int(request.params['limit'])
if 'offset' in request.params:
offset = int(request.params['offset'])
if filter is None:
filter = create_filter(request, self.mapped_class, self.geom_attr)
query = self.Session().query(self.mapped_class)
if filter is not None:
query = query.filter(filter)
order_by = self._get_order_by(request)
if order_by is not None:
query = query.order_by(order_by)
query = query.limit(limit).offset(offset)
return query.all()
def count(self, request, filter=None):
""" Return the number of records matching the given filter. """
if filter is None:
filter = create_filter(request, self.mapped_class, self.geom_attr)
query = self.Session().query(self.mapped_class)
if filter is not None:
query = query.filter(filter)
return query.count()
def read(self, request, filter=None, id=None):
""" Build a query based on the filter or the idenfier, send the query
to the database, and return a Feature or a FeatureCollection. """
ret = None
if id is not None:
o = self.Session().query(self.mapped_class).get(id)
if o is None:
return HTTPNotFound()
# FIXME: we return a Feature here, not a mapped object, do
# we really want that?
ret = self._filter_attrs(o.__geo_interface__, request)
else:
objs = self._query(request, filter)
ret = FeatureCollection(
[self._filter_attrs(o.__geo_interface__, request)
for o in objs if o is not None])
return ret
def create(self, request):
""" Read the GeoJSON feature collection from the request body and
create new objects in the database. """
if self.readonly:
return HTTPMethodNotAllowed(headers={'Allow': 'GET, HEAD'})
collection = loads(request.body, object_hook=GeoJSON.to_instance)
if not isinstance(collection, FeatureCollection):
return HTTPBadRequest()
session = self.Session()
objects = []
for feature in collection.features:
create = False
obj = None
if hasattr(feature, 'id') and feature.id is not None:
obj = session.query(self.mapped_class).get(feature.id)
if self.before_create is not None:
self.before_create(request, feature, obj)
if obj is None:
obj = self.mapped_class(feature)
create = True
else:
obj.__update__(feature)
if create:
session.add(obj)
objects.append(obj)
session.flush()
collection = FeatureCollection(objects) if len(objects) > 0 else None
request.response.status_int = 201
return collection
def delete(self, request, id):
""" Remove the targeted feature from the database """
if self.readonly:
return HTTPMethodNotAllowed(headers={'Allow': 'GET, HEAD'})
session = self.Session()
obj = session.query(self.mapped_class).get(id)
if obj is None:
return HTTPNotFound()
if self.before_delete is not None:
self.before_delete(request, obj)
session.delete(obj)
return Response(status_int=204)
|
elemoine/papyrus
|
papyrus/protocol.py
|
Protocol.delete
|
python
|
def delete(self, request, id):
if self.readonly:
return HTTPMethodNotAllowed(headers={'Allow': 'GET, HEAD'})
session = self.Session()
obj = session.query(self.mapped_class).get(id)
if obj is None:
return HTTPNotFound()
if self.before_delete is not None:
self.before_delete(request, obj)
session.delete(obj)
return Response(status_int=204)
|
Remove the targeted feature from the database
|
train
|
https://github.com/elemoine/papyrus/blob/764fb2326105df74fbd3dbcd7e58f4cb21956005/papyrus/protocol.py#L356-L367
| null |
class Protocol(object):
""" Protocol class.
Session
an SQLAlchemy ``Session`` class.
mapped_class
the class mapped to a database table in the ORM.
geom_attr
the key of the geometry property as defined in the SQLAlchemy
mapper. If you use ``declarative_base`` this is the name of
the geometry attribute as defined in the mapped class.
readonly
``True`` if this protocol is read-only, ``False`` otherwise. If
``True``, the methods ``create()``, ``update()`` and ``delete()``
will set 405 (Method Not Allowed) as the response status and
return right away.
\\**kwargs
before_create
a callback function called before a feature is inserted
in the database table, the function receives the request,
the feature read from the GeoJSON document sent in the
request, and the database object to be updated. The
latter is None if this is is an actual insertion.
before_update
a callback function called before a feature is updated
in the database table, the function receives the request,
the feature read from the GeoJSON document sent in the
request, and the database object to be updated.
before_delete
a callback function called before a feature is deleted
in the database table, the function receives the request
and the database object about to be deleted.
"""
def __init__(self, Session, mapped_class, geom_attr, readonly=False,
**kwargs):
self.Session = Session
self.mapped_class = mapped_class
self.geom_attr = geom_attr
self.readonly = readonly
self.before_create = kwargs.get('before_create')
self.before_update = kwargs.get('before_update')
self.before_delete = kwargs.get('before_delete')
def _filter_attrs(self, feature, request):
""" Remove some attributes from the feature and set the geometry to None
in the feature based ``attrs`` and the ``no_geom`` parameters. """
if 'attrs' in request.params:
attrs = request.params['attrs'].split(',')
props = feature.properties
new_props = {}
for name in attrs:
if name in props:
new_props[name] = props[name]
feature.properties = new_props
if asbool(request.params.get('no_geom', False)):
feature.geometry = None
return feature
def _get_order_by(self, request):
""" Return an SA order_by """
attr = request.params.get('sort', request.params.get('order_by'))
if attr is None or not hasattr(self.mapped_class, attr):
return None
if request.params.get('dir', '').upper() == 'DESC':
return desc(getattr(self.mapped_class, attr))
else:
return asc(getattr(self.mapped_class, attr))
def _query(self, request, filter=None):
""" Build a query based on the filter and the request params,
and send the query to the database. """
limit = None
offset = None
if 'maxfeatures' in request.params:
limit = int(request.params['maxfeatures'])
if 'limit' in request.params:
limit = int(request.params['limit'])
if 'offset' in request.params:
offset = int(request.params['offset'])
if filter is None:
filter = create_filter(request, self.mapped_class, self.geom_attr)
query = self.Session().query(self.mapped_class)
if filter is not None:
query = query.filter(filter)
order_by = self._get_order_by(request)
if order_by is not None:
query = query.order_by(order_by)
query = query.limit(limit).offset(offset)
return query.all()
def count(self, request, filter=None):
""" Return the number of records matching the given filter. """
if filter is None:
filter = create_filter(request, self.mapped_class, self.geom_attr)
query = self.Session().query(self.mapped_class)
if filter is not None:
query = query.filter(filter)
return query.count()
def read(self, request, filter=None, id=None):
""" Build a query based on the filter or the idenfier, send the query
to the database, and return a Feature or a FeatureCollection. """
ret = None
if id is not None:
o = self.Session().query(self.mapped_class).get(id)
if o is None:
return HTTPNotFound()
# FIXME: we return a Feature here, not a mapped object, do
# we really want that?
ret = self._filter_attrs(o.__geo_interface__, request)
else:
objs = self._query(request, filter)
ret = FeatureCollection(
[self._filter_attrs(o.__geo_interface__, request)
for o in objs if o is not None])
return ret
def create(self, request):
""" Read the GeoJSON feature collection from the request body and
create new objects in the database. """
if self.readonly:
return HTTPMethodNotAllowed(headers={'Allow': 'GET, HEAD'})
collection = loads(request.body, object_hook=GeoJSON.to_instance)
if not isinstance(collection, FeatureCollection):
return HTTPBadRequest()
session = self.Session()
objects = []
for feature in collection.features:
create = False
obj = None
if hasattr(feature, 'id') and feature.id is not None:
obj = session.query(self.mapped_class).get(feature.id)
if self.before_create is not None:
self.before_create(request, feature, obj)
if obj is None:
obj = self.mapped_class(feature)
create = True
else:
obj.__update__(feature)
if create:
session.add(obj)
objects.append(obj)
session.flush()
collection = FeatureCollection(objects) if len(objects) > 0 else None
request.response.status_int = 201
return collection
def update(self, request, id):
""" Read the GeoJSON feature from the request body and update the
corresponding object in the database. """
if self.readonly:
return HTTPMethodNotAllowed(headers={'Allow': 'GET, HEAD'})
session = self.Session()
obj = session.query(self.mapped_class).get(id)
if obj is None:
return HTTPNotFound()
feature = loads(request.body, object_hook=GeoJSON.to_instance)
if not isinstance(feature, Feature):
return HTTPBadRequest()
if self.before_update is not None:
self.before_update(request, feature, obj)
obj.__update__(feature)
session.flush()
request.response.status_int = 200
return obj
|
elemoine/papyrus
|
papyrus/__init__.py
|
add_papyrus_handler
|
python
|
def add_papyrus_handler(self, route_name_prefix, base_url, handler):
route_name = route_name_prefix + '_read_many'
self.add_handler(route_name, base_url, handler,
action='read_many', request_method='GET')
route_name = route_name_prefix + '_read_one'
self.add_handler(route_name, base_url + '/{id}', handler,
action='read_one', request_method='GET')
route_name = route_name_prefix + '_count'
self.add_handler(route_name, base_url + '/count', handler,
action='count', request_method='GET')
route_name = route_name_prefix + '_create'
self.add_handler(route_name, base_url, handler,
action='create', request_method='POST')
route_name = route_name_prefix + '_update'
self.add_handler(route_name, base_url + '/{id}', handler,
action='update', request_method='PUT')
route_name = route_name_prefix + '_delete'
self.add_handler(route_name, base_url + '/{id}', handler,
action='delete', request_method='DELETE')
|
Add a Papyrus handler, i.e. a handler defining the MapFish
HTTP interface.
Example::
import papyrus
config.include(papyrus)
config.add_papyrus_handler(
'spots', '/spots', 'mypackage.handlers.SpotHandler')
Arguments:
``route_name_prefix`` The prefix used for the route names
passed to ``config.add_handler``.
``base_url`` The web service's base URL, e.g. ``/spots``. No
trailing slash!
``handler`` a dotted name or a reference to a handler class,
e.g. ``'mypackage.handlers.MyHandler'``.
|
train
|
https://github.com/elemoine/papyrus/blob/764fb2326105df74fbd3dbcd7e58f4cb21956005/papyrus/__init__.py#L2-L41
| null |
def add_papyrus_routes(self, route_name_prefix, base_url):
""" A helper method that adds routes to view callables that, together,
implement the MapFish HTTP interface.
Example::
import papyrus
config.include(papyrus)
config.add_papyrus_routes('spots', '/spots')
config.scan()
Arguments:
``route_name_prefix' The prefix used for the route names
passed to ``config.add_route``.
``base_url`` The web service's base URL, e.g. ``/spots``. No
trailing slash!
"""
route_name = route_name_prefix + '_read_many'
self.add_route(route_name, base_url, request_method='GET')
route_name = route_name_prefix + '_read_one'
self.add_route(route_name, base_url + '/{id}', request_method='GET')
route_name = route_name_prefix + '_count'
self.add_route(route_name, base_url + '/count', request_method='GET')
route_name = route_name_prefix + '_create'
self.add_route(route_name, base_url, request_method='POST')
route_name = route_name_prefix + '_update'
self.add_route(route_name, base_url + '/{id}', request_method='PUT')
route_name = route_name_prefix + '_delete'
self.add_route(route_name, base_url + '/{id}', request_method='DELETE')
def includeme(config):
""" The function to pass to ``config.include``. Requires the
``pyramid_handlers`` module. """
config.add_directive('add_papyrus_handler', add_papyrus_handler)
config.add_directive('add_papyrus_routes', add_papyrus_routes)
|
elemoine/papyrus
|
papyrus/__init__.py
|
add_papyrus_routes
|
python
|
def add_papyrus_routes(self, route_name_prefix, base_url):
route_name = route_name_prefix + '_read_many'
self.add_route(route_name, base_url, request_method='GET')
route_name = route_name_prefix + '_read_one'
self.add_route(route_name, base_url + '/{id}', request_method='GET')
route_name = route_name_prefix + '_count'
self.add_route(route_name, base_url + '/count', request_method='GET')
route_name = route_name_prefix + '_create'
self.add_route(route_name, base_url, request_method='POST')
route_name = route_name_prefix + '_update'
self.add_route(route_name, base_url + '/{id}', request_method='PUT')
route_name = route_name_prefix + '_delete'
self.add_route(route_name, base_url + '/{id}', request_method='DELETE')
|
A helper method that adds routes to view callables that, together,
implement the MapFish HTTP interface.
Example::
import papyrus
config.include(papyrus)
config.add_papyrus_routes('spots', '/spots')
config.scan()
Arguments:
``route_name_prefix' The prefix used for the route names
passed to ``config.add_route``.
``base_url`` The web service's base URL, e.g. ``/spots``. No
trailing slash!
|
train
|
https://github.com/elemoine/papyrus/blob/764fb2326105df74fbd3dbcd7e58f4cb21956005/papyrus/__init__.py#L44-L74
| null |
def add_papyrus_handler(self, route_name_prefix, base_url, handler):
""" Add a Papyrus handler, i.e. a handler defining the MapFish
HTTP interface.
Example::
import papyrus
config.include(papyrus)
config.add_papyrus_handler(
'spots', '/spots', 'mypackage.handlers.SpotHandler')
Arguments:
``route_name_prefix`` The prefix used for the route names
passed to ``config.add_handler``.
``base_url`` The web service's base URL, e.g. ``/spots``. No
trailing slash!
``handler`` a dotted name or a reference to a handler class,
e.g. ``'mypackage.handlers.MyHandler'``.
"""
route_name = route_name_prefix + '_read_many'
self.add_handler(route_name, base_url, handler,
action='read_many', request_method='GET')
route_name = route_name_prefix + '_read_one'
self.add_handler(route_name, base_url + '/{id}', handler,
action='read_one', request_method='GET')
route_name = route_name_prefix + '_count'
self.add_handler(route_name, base_url + '/count', handler,
action='count', request_method='GET')
route_name = route_name_prefix + '_create'
self.add_handler(route_name, base_url, handler,
action='create', request_method='POST')
route_name = route_name_prefix + '_update'
self.add_handler(route_name, base_url + '/{id}', handler,
action='update', request_method='PUT')
route_name = route_name_prefix + '_delete'
self.add_handler(route_name, base_url + '/{id}', handler,
action='delete', request_method='DELETE')
def includeme(config):
""" The function to pass to ``config.include``. Requires the
``pyramid_handlers`` module. """
config.add_directive('add_papyrus_handler', add_papyrus_handler)
config.add_directive('add_papyrus_routes', add_papyrus_routes)
|
sacherjj/array_devices
|
array_devices/array3710.py
|
ProgramStep.setting
|
python
|
def setting(self):
prog_type = self.__program.program_type
return self._setting / self.SETTING_DIVIDES[prog_type]
|
Load setting (Amps, Watts, or Ohms depending on program mode)
|
train
|
https://github.com/sacherjj/array_devices/blob/ba93a081e555321125ead33cf6fc5197569ef08f/array_devices/array3710.py#L51-L56
| null |
class ProgramStep(object):
"""
Represents a single step in an Array3710Program
"""
# Max Settings based on PROG_TYPE modes as index
# 1: 30A, 2: 200W, 3: 500ohms
MAX_SETTINGS = (0, 30, 200, 500)
# Display units
SETTING_UNITS = ('', 'amps', 'watts', 'ohms')
# Conversions between internal and external representations.
# 1: 30000 -> 30A, 2: 2000 -> 200W, 3: 50000 -> 500ohms
SETTING_DIVIDES = (1, 1000, 10, 100)
def __init__(self, program, setting=0, duration=0):
self.__program = program
self._setting = 0
self._duration = 0
self.setting = setting
self.duration = duration
@property
@setting.setter
def setting(self, value):
prog_type = self.__program.program_type
if 0 <= value <= self.MAX_SETTINGS[prog_type]:
self._setting = value * self.SETTING_DIVIDES[prog_type]
else:
raise ValueError("Setting outside of valid range: 0-{} {}".format(
self.MAX_SETTINGS[prog_type], self.SETTING_UNITS[prog_type]))
@property
def duration(self):
"""
Duration of program step in seconds
"""
return self._duration
@duration.setter
def duration(self, value):
if 0 < value <= 60000:
self._duration = value
else:
raise ValueError("Duration should be between 1-60000 seconds")
@property
def raw_data(self):
"""
Raw data from step to be encoded into buffer as 2-byte integers
"""
return self._setting, self._duration
|
sacherjj/array_devices
|
array_devices/array3710.py
|
Program.partial_steps_data
|
python
|
def partial_steps_data(self, start=0):
cnt = 0
if len(self._prog_steps) >= start:
# yields actual steps for encoding
for step in self._prog_steps[start:start+5]:
yield((step.raw_data))
cnt += 1
while cnt < 5:
yield((0, 0))
cnt += 1
|
Iterates 5 steps from start position and
provides tuple for packing into buffer.
returns (0, 0) if stpe doesn't exist.
:param start: Position to start from (typically 0 or 5)
:yield: (setting, duration)
|
train
|
https://github.com/sacherjj/array_devices/blob/ba93a081e555321125ead33cf6fc5197569ef08f/array_devices/array3710.py#L136-L154
| null |
class Program(object):
"""
Represents a 10 step program for the load
"""
PROG_TYPE_CURRENT = 0x01
PROG_TYPE_POWER = 0x02
PROG_TYPE_RESISTANCE = 0x03
RUN_ONCE = 0x00
RUN_REPEAT = 0x01
def __init__(self, program_type=0x01, program_mode=0x00):
if not program_type in (self.PROG_TYPE_CURRENT, self.PROG_TYPE_POWER, self.PROG_TYPE_RESISTANCE):
raise ValueError("Illegal Program Type")
self._program_type = program_type
self._prog_steps = []
self._program_mode = 0
self.program_mode = program_mode
@property
def program_type(self):
"""
Type of load control for entire program.
This is read-only, because valid setting ranges change with
different types.
"""
return self._program_type
@property
def program_mode(self):
"""
Sets Run Once or Repeat
"""
return self._program_mode
@program_mode.setter
def program_mode(self, value):
if not value in (self.RUN_ONCE, self.RUN_REPEAT):
raise ValueError("Illegal Program Mode")
self._program_mode = value
@property
def steps(self):
for step in self._prog_steps:
yield(step)
def add_step(self, setting, duration):
"""
Adds steps to a program.
:param setting: Current, Wattage or Resistance, depending on program mode.
:param duration: Length of step in seconds.
:return: None
"""
if len(self._prog_steps) < 10:
self._prog_steps.append(ProgramStep(self, setting, duration))
else:
raise IndexError("Maximum of 10 steps are allowed")
def delete_step(self, position=-1):
"""
Removes step at position, or -1 to remove last step
"""
del self._prog_steps[position]
def load_buffer_one_to_five(self, out_buffer):
"""
Loads first program buffer (0x93) with everything but
first three bytes and checksum
"""
struct.pack_into(b"< 2B", out_buffer, 3, self._program_type, len(self._prog_steps))
offset = 5
for ind, step in enumerate(self.partial_steps_data(0)):
struct.pack_into(b"< 2H", out_buffer, offset + ind*4, step[0], step[1])
def load_buffer_six_to_ten(self, out_buffer):
"""
Loads second program buffer (0x94) with everything but
first three bytes and checksum
"""
offset = 3
for ind, step in enumerate(self.partial_steps_data(5)):
struct.pack_into(b"< 2H", out_buffer, offset + ind*4, step[0], step[1])
struct.pack_into(b"< B x", out_buffer, 23, self._program_mode)
|
sacherjj/array_devices
|
array_devices/array3710.py
|
Program.add_step
|
python
|
def add_step(self, setting, duration):
if len(self._prog_steps) < 10:
self._prog_steps.append(ProgramStep(self, setting, duration))
else:
raise IndexError("Maximum of 10 steps are allowed")
|
Adds steps to a program.
:param setting: Current, Wattage or Resistance, depending on program mode.
:param duration: Length of step in seconds.
:return: None
|
train
|
https://github.com/sacherjj/array_devices/blob/ba93a081e555321125ead33cf6fc5197569ef08f/array_devices/array3710.py#L156-L166
| null |
class Program(object):
"""
Represents a 10 step program for the load
"""
PROG_TYPE_CURRENT = 0x01
PROG_TYPE_POWER = 0x02
PROG_TYPE_RESISTANCE = 0x03
RUN_ONCE = 0x00
RUN_REPEAT = 0x01
def __init__(self, program_type=0x01, program_mode=0x00):
if not program_type in (self.PROG_TYPE_CURRENT, self.PROG_TYPE_POWER, self.PROG_TYPE_RESISTANCE):
raise ValueError("Illegal Program Type")
self._program_type = program_type
self._prog_steps = []
self._program_mode = 0
self.program_mode = program_mode
@property
def program_type(self):
"""
Type of load control for entire program.
This is read-only, because valid setting ranges change with
different types.
"""
return self._program_type
@property
def program_mode(self):
"""
Sets Run Once or Repeat
"""
return self._program_mode
@program_mode.setter
def program_mode(self, value):
if not value in (self.RUN_ONCE, self.RUN_REPEAT):
raise ValueError("Illegal Program Mode")
self._program_mode = value
@property
def steps(self):
for step in self._prog_steps:
yield(step)
def partial_steps_data(self, start=0):
"""
Iterates 5 steps from start position and
provides tuple for packing into buffer.
returns (0, 0) if stpe doesn't exist.
:param start: Position to start from (typically 0 or 5)
:yield: (setting, duration)
"""
cnt = 0
if len(self._prog_steps) >= start:
# yields actual steps for encoding
for step in self._prog_steps[start:start+5]:
yield((step.raw_data))
cnt += 1
while cnt < 5:
yield((0, 0))
cnt += 1
def delete_step(self, position=-1):
"""
Removes step at position, or -1 to remove last step
"""
del self._prog_steps[position]
def load_buffer_one_to_five(self, out_buffer):
"""
Loads first program buffer (0x93) with everything but
first three bytes and checksum
"""
struct.pack_into(b"< 2B", out_buffer, 3, self._program_type, len(self._prog_steps))
offset = 5
for ind, step in enumerate(self.partial_steps_data(0)):
struct.pack_into(b"< 2H", out_buffer, offset + ind*4, step[0], step[1])
def load_buffer_six_to_ten(self, out_buffer):
"""
Loads second program buffer (0x94) with everything but
first three bytes and checksum
"""
offset = 3
for ind, step in enumerate(self.partial_steps_data(5)):
struct.pack_into(b"< 2H", out_buffer, offset + ind*4, step[0], step[1])
struct.pack_into(b"< B x", out_buffer, 23, self._program_mode)
|
sacherjj/array_devices
|
array_devices/array3710.py
|
Program.load_buffer_one_to_five
|
python
|
def load_buffer_one_to_five(self, out_buffer):
struct.pack_into(b"< 2B", out_buffer, 3, self._program_type, len(self._prog_steps))
offset = 5
for ind, step in enumerate(self.partial_steps_data(0)):
struct.pack_into(b"< 2H", out_buffer, offset + ind*4, step[0], step[1])
|
Loads first program buffer (0x93) with everything but
first three bytes and checksum
|
train
|
https://github.com/sacherjj/array_devices/blob/ba93a081e555321125ead33cf6fc5197569ef08f/array_devices/array3710.py#L174-L182
|
[
"def partial_steps_data(self, start=0):\n \"\"\"\n Iterates 5 steps from start position and\n provides tuple for packing into buffer.\n\n returns (0, 0) if stpe doesn't exist.\n\n :param start: Position to start from (typically 0 or 5)\n :yield: (setting, duration)\n \"\"\"\n cnt = 0\n if len(self._prog_steps) >= start:\n # yields actual steps for encoding\n for step in self._prog_steps[start:start+5]:\n yield((step.raw_data))\n cnt += 1\n while cnt < 5:\n yield((0, 0))\n cnt += 1\n"
] |
class Program(object):
"""
Represents a 10 step program for the load
"""
PROG_TYPE_CURRENT = 0x01
PROG_TYPE_POWER = 0x02
PROG_TYPE_RESISTANCE = 0x03
RUN_ONCE = 0x00
RUN_REPEAT = 0x01
def __init__(self, program_type=0x01, program_mode=0x00):
if not program_type in (self.PROG_TYPE_CURRENT, self.PROG_TYPE_POWER, self.PROG_TYPE_RESISTANCE):
raise ValueError("Illegal Program Type")
self._program_type = program_type
self._prog_steps = []
self._program_mode = 0
self.program_mode = program_mode
@property
def program_type(self):
"""
Type of load control for entire program.
This is read-only, because valid setting ranges change with
different types.
"""
return self._program_type
@property
def program_mode(self):
"""
Sets Run Once or Repeat
"""
return self._program_mode
@program_mode.setter
def program_mode(self, value):
if not value in (self.RUN_ONCE, self.RUN_REPEAT):
raise ValueError("Illegal Program Mode")
self._program_mode = value
@property
def steps(self):
for step in self._prog_steps:
yield(step)
def partial_steps_data(self, start=0):
"""
Iterates 5 steps from start position and
provides tuple for packing into buffer.
returns (0, 0) if stpe doesn't exist.
:param start: Position to start from (typically 0 or 5)
:yield: (setting, duration)
"""
cnt = 0
if len(self._prog_steps) >= start:
# yields actual steps for encoding
for step in self._prog_steps[start:start+5]:
yield((step.raw_data))
cnt += 1
while cnt < 5:
yield((0, 0))
cnt += 1
def add_step(self, setting, duration):
"""
Adds steps to a program.
:param setting: Current, Wattage or Resistance, depending on program mode.
:param duration: Length of step in seconds.
:return: None
"""
if len(self._prog_steps) < 10:
self._prog_steps.append(ProgramStep(self, setting, duration))
else:
raise IndexError("Maximum of 10 steps are allowed")
def delete_step(self, position=-1):
"""
Removes step at position, or -1 to remove last step
"""
del self._prog_steps[position]
def load_buffer_six_to_ten(self, out_buffer):
"""
Loads second program buffer (0x94) with everything but
first three bytes and checksum
"""
offset = 3
for ind, step in enumerate(self.partial_steps_data(5)):
struct.pack_into(b"< 2H", out_buffer, offset + ind*4, step[0], step[1])
struct.pack_into(b"< B x", out_buffer, 23, self._program_mode)
|
sacherjj/array_devices
|
array_devices/array3710.py
|
Program.load_buffer_six_to_ten
|
python
|
def load_buffer_six_to_ten(self, out_buffer):
offset = 3
for ind, step in enumerate(self.partial_steps_data(5)):
struct.pack_into(b"< 2H", out_buffer, offset + ind*4, step[0], step[1])
struct.pack_into(b"< B x", out_buffer, 23, self._program_mode)
|
Loads second program buffer (0x94) with everything but
first three bytes and checksum
|
train
|
https://github.com/sacherjj/array_devices/blob/ba93a081e555321125ead33cf6fc5197569ef08f/array_devices/array3710.py#L184-L192
|
[
"def partial_steps_data(self, start=0):\n \"\"\"\n Iterates 5 steps from start position and\n provides tuple for packing into buffer.\n\n returns (0, 0) if stpe doesn't exist.\n\n :param start: Position to start from (typically 0 or 5)\n :yield: (setting, duration)\n \"\"\"\n cnt = 0\n if len(self._prog_steps) >= start:\n # yields actual steps for encoding\n for step in self._prog_steps[start:start+5]:\n yield((step.raw_data))\n cnt += 1\n while cnt < 5:\n yield((0, 0))\n cnt += 1\n"
] |
class Program(object):
"""
Represents a 10 step program for the load
"""
PROG_TYPE_CURRENT = 0x01
PROG_TYPE_POWER = 0x02
PROG_TYPE_RESISTANCE = 0x03
RUN_ONCE = 0x00
RUN_REPEAT = 0x01
def __init__(self, program_type=0x01, program_mode=0x00):
if not program_type in (self.PROG_TYPE_CURRENT, self.PROG_TYPE_POWER, self.PROG_TYPE_RESISTANCE):
raise ValueError("Illegal Program Type")
self._program_type = program_type
self._prog_steps = []
self._program_mode = 0
self.program_mode = program_mode
@property
def program_type(self):
"""
Type of load control for entire program.
This is read-only, because valid setting ranges change with
different types.
"""
return self._program_type
@property
def program_mode(self):
"""
Sets Run Once or Repeat
"""
return self._program_mode
@program_mode.setter
def program_mode(self, value):
if not value in (self.RUN_ONCE, self.RUN_REPEAT):
raise ValueError("Illegal Program Mode")
self._program_mode = value
@property
def steps(self):
for step in self._prog_steps:
yield(step)
def partial_steps_data(self, start=0):
"""
Iterates 5 steps from start position and
provides tuple for packing into buffer.
returns (0, 0) if stpe doesn't exist.
:param start: Position to start from (typically 0 or 5)
:yield: (setting, duration)
"""
cnt = 0
if len(self._prog_steps) >= start:
# yields actual steps for encoding
for step in self._prog_steps[start:start+5]:
yield((step.raw_data))
cnt += 1
while cnt < 5:
yield((0, 0))
cnt += 1
def add_step(self, setting, duration):
"""
Adds steps to a program.
:param setting: Current, Wattage or Resistance, depending on program mode.
:param duration: Length of step in seconds.
:return: None
"""
if len(self._prog_steps) < 10:
self._prog_steps.append(ProgramStep(self, setting, duration))
else:
raise IndexError("Maximum of 10 steps are allowed")
def delete_step(self, position=-1):
"""
Removes step at position, or -1 to remove last step
"""
del self._prog_steps[position]
def load_buffer_one_to_five(self, out_buffer):
"""
Loads first program buffer (0x93) with everything but
first three bytes and checksum
"""
struct.pack_into(b"< 2B", out_buffer, 3, self._program_type, len(self._prog_steps))
offset = 5
for ind, step in enumerate(self.partial_steps_data(0)):
struct.pack_into(b"< 2H", out_buffer, offset + ind*4, step[0], step[1])
|
sacherjj/array_devices
|
array_devices/array3710.py
|
Load.set_load_resistance
|
python
|
def set_load_resistance(self, resistance):
new_val = int(round(resistance * 100))
if not 0 <= new_val <= 50000:
raise ValueError("Load Resistance should be between 0-500 ohms")
self._load_mode = self.SET_TYPE_RESISTANCE
self._load_value = new_val
self.__set_parameters()
|
Changes load to resistance mode and sets resistance value.
Rounds to nearest 0.01 Ohms
:param resistance: Load Resistance in Ohms (0-500 ohms)
:return: None
|
train
|
https://github.com/sacherjj/array_devices/blob/ba93a081e555321125ead33cf6fc5197569ef08f/array_devices/array3710.py#L309-L322
| null |
class Load(object):
"""
Handles remote control of Array 3710A DC Electronic Load.
Also sold under Gossen, Tekpower, Circuit Specialists with same 3710A model number.
"""
DEBUG_MODE = False
# Packet command values
CMD_SET_PARAMETERS = 0x90
CMD_READ_VALUES = 0x91
CMD_LOAD_STATE = 0x92
CMD_DEFINE_PROG_1_5 = 0x93
CMD_DEFINE_PROG_6_10 = 0x94
CMD_START_PROG = 0x95
CMD_STOP_PROG = 0x96
SET_TYPE_CURRENT = 0x01
SET_TYPE_POWER = 0x02
SET_TYPE_RESISTANCE = 0x03
FRAME_LENGTH = 26
# Description of data structures for various packet types
STRUCT_FRONT = struct.Struct(b'< 3B 23x')
STRUCT_SET_PARAMETERS = struct.Struct(b'< 2H 2B H 14x')
STRUCT_READ_VALUES_OUT = struct.Struct(b'< 22x')
STRUCT_READ_VALUES_IN = struct.Struct(b'< 3B H I 4H B 7x B')
STRUCT_LOAD_STATE = struct.Struct(b'< B 21x')
STRUCT_DEFINE_PROG_LOW = struct.Struct(b'< 2B 10H')
STRUCT_DEFINE_PROG_HIGH = struct.Struct(b'< 10H B x')
STRUCT_START_PROGRAM = struct.Struct(b'< 22x')
STRUCT_STOP_PROGRAM = struct.Struct(b'< 22x')
STRUCT_CHECKSUM = struct.Struct(b'< B')
# Offsets for packing partial structs
OFFSET_FRONT = 0
OFFSET_PAYLOAD = 3
OFFSET_CHECKSUM = 25
def __init__(self, address, serial_connection, print_errors=True):
"""
Require passing in serial_connection, because multiple Loads can exist
with different addresses on a single serial port.
:param address: Load address (0x00-0xFE)
:param serial_connection: Serial Connection from serial.Serial()
:return: None
"""
# Serial Comm Packets are all 26 byte frames.
# out_buffer for building data to send, in_buffer for consuming responses.
self.__out_buffer = ctypes.create_string_buffer(self.FRAME_LENGTH)
self.__in_buffer = ctypes.create_string_buffer(self.FRAME_LENGTH)
self.address = address
self.serial = serial_connection
self._max_current = 30000
self._max_power = 2000
self._load_mode = self.SET_TYPE_RESISTANCE
self._load_value = 500
self._current = 0
self._power = 0
self._voltage = 0
self._resistance = 0
self._remote_control = 0
self._load_on = 0
self.wrong_polarity = 0
self.excessive_temp = 0
self.excessive_voltage = 0
self.excessive_power = 0
self.print_errors = print_errors
self.update_status()
# Note: Internally, all values are stored as integer values
# in the format of the load interface.
#
# Ex: current is stored in mA, but public IO is Amps
# power is stored in tenths of Watts, but public IO is Watts.
#
# Conversion is done on getter and setter methods.
@property
def max_current(self):
"""
Max Current (in Amps) allowed to be set by load.
Rounds to nearest mA.
"""
return self._max_current / 1000
@max_current.setter
def max_current(self, current_amps):
new_val = int(round(current_amps * 1000, 0))
if not 0 <= new_val <= 30000:
raise ValueError("Max Current should be between 0-30A")
self._max_current = new_val
self.__set_parameters()
@property
def max_power(self):
"""
Max Power (in Watts) allowed to be set by load.
Rounds to nearest 0.1W
"""
return self._max_power / 10
@max_power.setter
def max_power(self, power_watts):
new_val = int(round(power_watts * 10, 0))
if not 0 <= new_val <= 2000:
raise ValueError("Max Power should be between 0-200W")
self._max_power = new_val
self.__set_parameters()
def set_load_power(self, power_watts):
"""
Changes load to power mode and sets power value.
Rounds to nearest 0.1W.
:param power_watts: Power in Watts (0-200)
:return:
"""
new_val = int(round(power_watts * 10))
if not 0 <= new_val <= 2000:
raise ValueError("Load Power should be between 0-200 W")
self._load_mode = self.SET_TYPE_POWER
self._load_value = new_val
self.__set_parameters()
def set_load_current(self, current_amps):
"""
Changes load to current mode and sets current value.
Rounds to nearest mA.
:param current_amps: Current in Amps (0-30A)
:return: None
"""
new_val = int(round(current_amps * 1000))
if not 0 <= new_val <= 30000:
raise ValueError("Load Current should be between 0-30A")
self._load_mode = self.SET_TYPE_CURRENT
self._load_value = new_val
self.__set_parameters()
@property
def current(self):
"""
Current value (in Amps) obtained during last update_status call.
"""
return self._current / 1000
@property
def power(self):
"""
Power value (in Watts) obtained during last update_status call.
"""
return self._power / 10
@property
def resistance(self):
"""
Resistance value (in ohms) obtained during last update_status call.
"""
return self._resistance / 100
@property
def voltage(self):
"""
Voltage value (in Volts) obtained during last update_status call.
"""
return self._voltage / 1000
@property
def remote_control(self):
"""
Remote control enabled
"""
return self._remote_control == 1
@remote_control.setter
def remote_control(self, value):
new_val = 0
if value:
new_val = 1
if new_val != self._remote_control:
self._remote_control = new_val
self.__set_load_state()
@property
def load_on(self):
"""
Load enabled state
"""
return self._load_on == 1
@load_on.setter
def load_on(self, value):
new_val = 0
if value:
new_val = 1
if new_val != self._load_on:
self._load_on = new_val
self.__set_load_state()
def __set_buffer_start(self, command):
"""
This sets the first three bytes and clears the other 23 bytes.
:param command: Command Code to set
:return: None
"""
self.STRUCT_FRONT.pack_into(self.__out_buffer, self.OFFSET_FRONT, 0xAA, self.address, command)
@staticmethod
def __get_checksum(byte_str):
"""
Calculates checksum of string, excluding last character.
Checksum is generated by summing all byte values, except last,
and taking lowest byte of result.
:param byte_str: string to checksum, plus extra character on end
:return: checksum value as int
"""
return sum(byte2int(x) for x in byte_str[:-1]) % 256
def __set_checksum(self):
"""
Sets the checksum on the last byte of buffer,
based on values in the buffer
:return: None
"""
checksum = self.__get_checksum(self.__out_buffer.raw)
self.STRUCT_CHECKSUM.pack_into(self.__out_buffer, self.OFFSET_CHECKSUM, checksum)
def __is_valid_checksum(self, byte_str):
"""
Verifies last byte checksum of full packet
:param byte_str: byte string message
:return: boolean
"""
return byte2int(byte_str[-1]) == self.__get_checksum(byte_str)
def __clear_in_buffer(self):
"""
Zeros out the in buffer
:return: None
"""
self.__in_buffer.value = bytes(b'\0' * len(self.__in_buffer))
def __send_buffer(self):
"""
Sends the contents of self.__out_buffer to serial device
:return: Number of bytes written
"""
bytes_written = self.serial.write(self.__out_buffer.raw)
if self.DEBUG_MODE:
print("Wrote: '{}'".format(binascii.hexlify(self.__out_buffer.raw)))
if bytes_written != len(self.__out_buffer):
raise IOError("{} bytes written for output buffer of size {}".format(bytes_written,
len(self.__out_buffer)))
return bytes_written
def __send_receive_buffer(self):
"""
Performs a send of self.__out_buffer and then an immediate read into self.__in_buffer
:return: None
"""
self.__clear_in_buffer()
self.__send_buffer()
read_string = self.serial.read(len(self.__in_buffer))
if self.DEBUG_MODE:
print("Read: '{}'".format(binascii.hexlify(read_string)))
if len(read_string) != len(self.__in_buffer):
raise IOError("{} bytes received for input buffer of size {}".format(len(read_string),
len(self.__in_buffer)))
if not self.__is_valid_checksum(read_string):
raise IOError("Checksum validation failed on received data")
self.__in_buffer.value = read_string
def __set_parameters(self):
"""
Sets Load Parameters from class values, including:
Max Current, Max Power, Address, Load Mode, Load Value
:return: None
"""
self.__set_buffer_start(self.CMD_SET_PARAMETERS)
# Can I send 0xFF as address to not change it each time?
# Worry about writing to EEPROM or Flash with each address change.
# Would then implement a separate address only change function.
self.STRUCT_SET_PARAMETERS.pack_into(self.__out_buffer, self.OFFSET_PAYLOAD,
self._max_current, self._max_power, self.address,
self._load_mode, self._load_value)
self.__set_checksum()
self.__send_buffer()
self.update_status()
def update_status(self, retry_count=2):
"""
Updates current values from load.
Must be called to get latest values for the following properties of class:
current
voltage
power
max current
max power
resistance
local_control
load_on
wrong_polarity
excessive_temp
excessive_voltage
excessive_power
:param retry_count: Number of times to ignore IOErrors and retry update
:return: None
"""
# I think retry should be in here.
# Throw exceptions in __update_status and handle here
cur_count = max(retry_count, 0)
while cur_count >= 0:
try:
self.__update_status()
except IOError as err:
if self.print_errors:
print("IOError: {}".format(err))
else:
if not self.__is_valid_checksum(self.__in_buffer.raw):
if self.print_errors:
raise IOError("Checksum validation failed.")
values = self.STRUCT_READ_VALUES_IN.unpack_from(self.__in_buffer, self.OFFSET_FRONT)
(self._current,
self._voltage,
self._power,
self._max_current,
self._max_power,
self._resistance,
output_state) = values[3:-1]
self._remote_control = (output_state & 0b00000001) > 0
self._load_on = (output_state & 0b00000010) > 0
self.wrong_polarity = (output_state & 0b00000100) > 0
self.excessive_temp = (output_state & 0b00001000) > 0
self.excessive_voltage = (output_state & 0b00010000) > 0
self.excessive_power = (output_state & 0b00100000) > 0
return None
cur_count -= 1
raise IOError("Retry count exceeded with serial IO.")
def __update_status(self):
self.__set_buffer_start(self.CMD_READ_VALUES)
self.STRUCT_READ_VALUES_OUT.pack_into(self.__out_buffer, 3)
self.__set_checksum()
self.__send_receive_buffer()
def __set_load_state(self):
# Remote Control is bit 2
flags = self._remote_control << 1
# Load On is bit 1
flags |= self._load_on
self.__set_buffer_start(self.CMD_LOAD_STATE)
self.STRUCT_LOAD_STATE.pack_into(self.__out_buffer, self.OFFSET_PAYLOAD, flags)
self.__set_checksum()
self.__send_buffer()
def set_program_sequence(self, array_program):
"""
Sets program up in load.
:param array_program: Populated Array3710Program object
:return: None
"""
self.__set_buffer_start(self.CMD_DEFINE_PROG_1_5)
array_program.load_buffer_one_to_five(self.__out_buffer)
self.__set_checksum()
self.__send_buffer()
self.__set_buffer_start(self.CMD_DEFINE_PROG_6_10)
array_program.load_buffer_six_to_ten(self.__out_buffer)
self.__set_checksum()
self.__send_buffer()
def start_program(self, turn_on_load=True):
"""
Starts running programmed test sequence
:return: None
"""
self.__set_buffer_start(self.CMD_START_PROG)
self.__set_checksum()
self.__send_buffer()
# Turn on Load if not on
if turn_on_load and not self.load_on:
self.load_on = True
def stop_program(self, turn_off_load=True):
"""
Stops running programmed test sequence
:return: None
"""
self.__set_buffer_start(self.CMD_STOP_PROG)
self.__set_checksum()
self.__send_buffer()
if turn_off_load and self.load_on:
self.load_on = False
|
sacherjj/array_devices
|
array_devices/array3710.py
|
Load.set_load_power
|
python
|
def set_load_power(self, power_watts):
new_val = int(round(power_watts * 10))
if not 0 <= new_val <= 2000:
raise ValueError("Load Power should be between 0-200 W")
self._load_mode = self.SET_TYPE_POWER
self._load_value = new_val
self.__set_parameters()
|
Changes load to power mode and sets power value.
Rounds to nearest 0.1W.
:param power_watts: Power in Watts (0-200)
:return:
|
train
|
https://github.com/sacherjj/array_devices/blob/ba93a081e555321125ead33cf6fc5197569ef08f/array_devices/array3710.py#L324-L337
| null |
class Load(object):
"""
Handles remote control of Array 3710A DC Electronic Load.
Also sold under Gossen, Tekpower, Circuit Specialists with same 3710A model number.
"""
DEBUG_MODE = False
# Packet command values
CMD_SET_PARAMETERS = 0x90
CMD_READ_VALUES = 0x91
CMD_LOAD_STATE = 0x92
CMD_DEFINE_PROG_1_5 = 0x93
CMD_DEFINE_PROG_6_10 = 0x94
CMD_START_PROG = 0x95
CMD_STOP_PROG = 0x96
SET_TYPE_CURRENT = 0x01
SET_TYPE_POWER = 0x02
SET_TYPE_RESISTANCE = 0x03
FRAME_LENGTH = 26
# Description of data structures for various packet types
STRUCT_FRONT = struct.Struct(b'< 3B 23x')
STRUCT_SET_PARAMETERS = struct.Struct(b'< 2H 2B H 14x')
STRUCT_READ_VALUES_OUT = struct.Struct(b'< 22x')
STRUCT_READ_VALUES_IN = struct.Struct(b'< 3B H I 4H B 7x B')
STRUCT_LOAD_STATE = struct.Struct(b'< B 21x')
STRUCT_DEFINE_PROG_LOW = struct.Struct(b'< 2B 10H')
STRUCT_DEFINE_PROG_HIGH = struct.Struct(b'< 10H B x')
STRUCT_START_PROGRAM = struct.Struct(b'< 22x')
STRUCT_STOP_PROGRAM = struct.Struct(b'< 22x')
STRUCT_CHECKSUM = struct.Struct(b'< B')
# Offsets for packing partial structs
OFFSET_FRONT = 0
OFFSET_PAYLOAD = 3
OFFSET_CHECKSUM = 25
def __init__(self, address, serial_connection, print_errors=True):
"""
Require passing in serial_connection, because multiple Loads can exist
with different addresses on a single serial port.
:param address: Load address (0x00-0xFE)
:param serial_connection: Serial Connection from serial.Serial()
:return: None
"""
# Serial Comm Packets are all 26 byte frames.
# out_buffer for building data to send, in_buffer for consuming responses.
self.__out_buffer = ctypes.create_string_buffer(self.FRAME_LENGTH)
self.__in_buffer = ctypes.create_string_buffer(self.FRAME_LENGTH)
self.address = address
self.serial = serial_connection
self._max_current = 30000
self._max_power = 2000
self._load_mode = self.SET_TYPE_RESISTANCE
self._load_value = 500
self._current = 0
self._power = 0
self._voltage = 0
self._resistance = 0
self._remote_control = 0
self._load_on = 0
self.wrong_polarity = 0
self.excessive_temp = 0
self.excessive_voltage = 0
self.excessive_power = 0
self.print_errors = print_errors
self.update_status()
# Note: Internally, all values are stored as integer values
# in the format of the load interface.
#
# Ex: current is stored in mA, but public IO is Amps
# power is stored in tenths of Watts, but public IO is Watts.
#
# Conversion is done on getter and setter methods.
@property
def max_current(self):
"""
Max Current (in Amps) allowed to be set by load.
Rounds to nearest mA.
"""
return self._max_current / 1000
@max_current.setter
def max_current(self, current_amps):
new_val = int(round(current_amps * 1000, 0))
if not 0 <= new_val <= 30000:
raise ValueError("Max Current should be between 0-30A")
self._max_current = new_val
self.__set_parameters()
@property
def max_power(self):
"""
Max Power (in Watts) allowed to be set by load.
Rounds to nearest 0.1W
"""
return self._max_power / 10
@max_power.setter
def max_power(self, power_watts):
new_val = int(round(power_watts * 10, 0))
if not 0 <= new_val <= 2000:
raise ValueError("Max Power should be between 0-200W")
self._max_power = new_val
self.__set_parameters()
def set_load_resistance(self, resistance):
"""
Changes load to resistance mode and sets resistance value.
Rounds to nearest 0.01 Ohms
:param resistance: Load Resistance in Ohms (0-500 ohms)
:return: None
"""
new_val = int(round(resistance * 100))
if not 0 <= new_val <= 50000:
raise ValueError("Load Resistance should be between 0-500 ohms")
self._load_mode = self.SET_TYPE_RESISTANCE
self._load_value = new_val
self.__set_parameters()
def set_load_current(self, current_amps):
"""
Changes load to current mode and sets current value.
Rounds to nearest mA.
:param current_amps: Current in Amps (0-30A)
:return: None
"""
new_val = int(round(current_amps * 1000))
if not 0 <= new_val <= 30000:
raise ValueError("Load Current should be between 0-30A")
self._load_mode = self.SET_TYPE_CURRENT
self._load_value = new_val
self.__set_parameters()
@property
def current(self):
"""
Current value (in Amps) obtained during last update_status call.
"""
return self._current / 1000
@property
def power(self):
"""
Power value (in Watts) obtained during last update_status call.
"""
return self._power / 10
@property
def resistance(self):
"""
Resistance value (in ohms) obtained during last update_status call.
"""
return self._resistance / 100
@property
def voltage(self):
"""
Voltage value (in Volts) obtained during last update_status call.
"""
return self._voltage / 1000
@property
def remote_control(self):
"""
Remote control enabled
"""
return self._remote_control == 1
@remote_control.setter
def remote_control(self, value):
new_val = 0
if value:
new_val = 1
if new_val != self._remote_control:
self._remote_control = new_val
self.__set_load_state()
@property
def load_on(self):
"""
Load enabled state
"""
return self._load_on == 1
@load_on.setter
def load_on(self, value):
new_val = 0
if value:
new_val = 1
if new_val != self._load_on:
self._load_on = new_val
self.__set_load_state()
def __set_buffer_start(self, command):
"""
This sets the first three bytes and clears the other 23 bytes.
:param command: Command Code to set
:return: None
"""
self.STRUCT_FRONT.pack_into(self.__out_buffer, self.OFFSET_FRONT, 0xAA, self.address, command)
@staticmethod
def __get_checksum(byte_str):
"""
Calculates checksum of string, excluding last character.
Checksum is generated by summing all byte values, except last,
and taking lowest byte of result.
:param byte_str: string to checksum, plus extra character on end
:return: checksum value as int
"""
return sum(byte2int(x) for x in byte_str[:-1]) % 256
def __set_checksum(self):
"""
Sets the checksum on the last byte of buffer,
based on values in the buffer
:return: None
"""
checksum = self.__get_checksum(self.__out_buffer.raw)
self.STRUCT_CHECKSUM.pack_into(self.__out_buffer, self.OFFSET_CHECKSUM, checksum)
def __is_valid_checksum(self, byte_str):
"""
Verifies last byte checksum of full packet
:param byte_str: byte string message
:return: boolean
"""
return byte2int(byte_str[-1]) == self.__get_checksum(byte_str)
def __clear_in_buffer(self):
"""
Zeros out the in buffer
:return: None
"""
self.__in_buffer.value = bytes(b'\0' * len(self.__in_buffer))
def __send_buffer(self):
"""
Sends the contents of self.__out_buffer to serial device
:return: Number of bytes written
"""
bytes_written = self.serial.write(self.__out_buffer.raw)
if self.DEBUG_MODE:
print("Wrote: '{}'".format(binascii.hexlify(self.__out_buffer.raw)))
if bytes_written != len(self.__out_buffer):
raise IOError("{} bytes written for output buffer of size {}".format(bytes_written,
len(self.__out_buffer)))
return bytes_written
def __send_receive_buffer(self):
"""
Performs a send of self.__out_buffer and then an immediate read into self.__in_buffer
:return: None
"""
self.__clear_in_buffer()
self.__send_buffer()
read_string = self.serial.read(len(self.__in_buffer))
if self.DEBUG_MODE:
print("Read: '{}'".format(binascii.hexlify(read_string)))
if len(read_string) != len(self.__in_buffer):
raise IOError("{} bytes received for input buffer of size {}".format(len(read_string),
len(self.__in_buffer)))
if not self.__is_valid_checksum(read_string):
raise IOError("Checksum validation failed on received data")
self.__in_buffer.value = read_string
def __set_parameters(self):
"""
Sets Load Parameters from class values, including:
Max Current, Max Power, Address, Load Mode, Load Value
:return: None
"""
self.__set_buffer_start(self.CMD_SET_PARAMETERS)
# Can I send 0xFF as address to not change it each time?
# Worry about writing to EEPROM or Flash with each address change.
# Would then implement a separate address only change function.
self.STRUCT_SET_PARAMETERS.pack_into(self.__out_buffer, self.OFFSET_PAYLOAD,
self._max_current, self._max_power, self.address,
self._load_mode, self._load_value)
self.__set_checksum()
self.__send_buffer()
self.update_status()
def update_status(self, retry_count=2):
"""
Updates current values from load.
Must be called to get latest values for the following properties of class:
current
voltage
power
max current
max power
resistance
local_control
load_on
wrong_polarity
excessive_temp
excessive_voltage
excessive_power
:param retry_count: Number of times to ignore IOErrors and retry update
:return: None
"""
# I think retry should be in here.
# Throw exceptions in __update_status and handle here
cur_count = max(retry_count, 0)
while cur_count >= 0:
try:
self.__update_status()
except IOError as err:
if self.print_errors:
print("IOError: {}".format(err))
else:
if not self.__is_valid_checksum(self.__in_buffer.raw):
if self.print_errors:
raise IOError("Checksum validation failed.")
values = self.STRUCT_READ_VALUES_IN.unpack_from(self.__in_buffer, self.OFFSET_FRONT)
(self._current,
self._voltage,
self._power,
self._max_current,
self._max_power,
self._resistance,
output_state) = values[3:-1]
self._remote_control = (output_state & 0b00000001) > 0
self._load_on = (output_state & 0b00000010) > 0
self.wrong_polarity = (output_state & 0b00000100) > 0
self.excessive_temp = (output_state & 0b00001000) > 0
self.excessive_voltage = (output_state & 0b00010000) > 0
self.excessive_power = (output_state & 0b00100000) > 0
return None
cur_count -= 1
raise IOError("Retry count exceeded with serial IO.")
def __update_status(self):
self.__set_buffer_start(self.CMD_READ_VALUES)
self.STRUCT_READ_VALUES_OUT.pack_into(self.__out_buffer, 3)
self.__set_checksum()
self.__send_receive_buffer()
def __set_load_state(self):
# Remote Control is bit 2
flags = self._remote_control << 1
# Load On is bit 1
flags |= self._load_on
self.__set_buffer_start(self.CMD_LOAD_STATE)
self.STRUCT_LOAD_STATE.pack_into(self.__out_buffer, self.OFFSET_PAYLOAD, flags)
self.__set_checksum()
self.__send_buffer()
def set_program_sequence(self, array_program):
"""
Sets program up in load.
:param array_program: Populated Array3710Program object
:return: None
"""
self.__set_buffer_start(self.CMD_DEFINE_PROG_1_5)
array_program.load_buffer_one_to_five(self.__out_buffer)
self.__set_checksum()
self.__send_buffer()
self.__set_buffer_start(self.CMD_DEFINE_PROG_6_10)
array_program.load_buffer_six_to_ten(self.__out_buffer)
self.__set_checksum()
self.__send_buffer()
def start_program(self, turn_on_load=True):
"""
Starts running programmed test sequence
:return: None
"""
self.__set_buffer_start(self.CMD_START_PROG)
self.__set_checksum()
self.__send_buffer()
# Turn on Load if not on
if turn_on_load and not self.load_on:
self.load_on = True
def stop_program(self, turn_off_load=True):
"""
Stops running programmed test sequence
:return: None
"""
self.__set_buffer_start(self.CMD_STOP_PROG)
self.__set_checksum()
self.__send_buffer()
if turn_off_load and self.load_on:
self.load_on = False
|
sacherjj/array_devices
|
array_devices/array3710.py
|
Load.set_load_current
|
python
|
def set_load_current(self, current_amps):
new_val = int(round(current_amps * 1000))
if not 0 <= new_val <= 30000:
raise ValueError("Load Current should be between 0-30A")
self._load_mode = self.SET_TYPE_CURRENT
self._load_value = new_val
self.__set_parameters()
|
Changes load to current mode and sets current value.
Rounds to nearest mA.
:param current_amps: Current in Amps (0-30A)
:return: None
|
train
|
https://github.com/sacherjj/array_devices/blob/ba93a081e555321125ead33cf6fc5197569ef08f/array_devices/array3710.py#L339-L352
| null |
class Load(object):
"""
Handles remote control of Array 3710A DC Electronic Load.
Also sold under Gossen, Tekpower, Circuit Specialists with same 3710A model number.
"""
DEBUG_MODE = False
# Packet command values
CMD_SET_PARAMETERS = 0x90
CMD_READ_VALUES = 0x91
CMD_LOAD_STATE = 0x92
CMD_DEFINE_PROG_1_5 = 0x93
CMD_DEFINE_PROG_6_10 = 0x94
CMD_START_PROG = 0x95
CMD_STOP_PROG = 0x96
SET_TYPE_CURRENT = 0x01
SET_TYPE_POWER = 0x02
SET_TYPE_RESISTANCE = 0x03
FRAME_LENGTH = 26
# Description of data structures for various packet types
STRUCT_FRONT = struct.Struct(b'< 3B 23x')
STRUCT_SET_PARAMETERS = struct.Struct(b'< 2H 2B H 14x')
STRUCT_READ_VALUES_OUT = struct.Struct(b'< 22x')
STRUCT_READ_VALUES_IN = struct.Struct(b'< 3B H I 4H B 7x B')
STRUCT_LOAD_STATE = struct.Struct(b'< B 21x')
STRUCT_DEFINE_PROG_LOW = struct.Struct(b'< 2B 10H')
STRUCT_DEFINE_PROG_HIGH = struct.Struct(b'< 10H B x')
STRUCT_START_PROGRAM = struct.Struct(b'< 22x')
STRUCT_STOP_PROGRAM = struct.Struct(b'< 22x')
STRUCT_CHECKSUM = struct.Struct(b'< B')
# Offsets for packing partial structs
OFFSET_FRONT = 0
OFFSET_PAYLOAD = 3
OFFSET_CHECKSUM = 25
def __init__(self, address, serial_connection, print_errors=True):
"""
Require passing in serial_connection, because multiple Loads can exist
with different addresses on a single serial port.
:param address: Load address (0x00-0xFE)
:param serial_connection: Serial Connection from serial.Serial()
:return: None
"""
# Serial Comm Packets are all 26 byte frames.
# out_buffer for building data to send, in_buffer for consuming responses.
self.__out_buffer = ctypes.create_string_buffer(self.FRAME_LENGTH)
self.__in_buffer = ctypes.create_string_buffer(self.FRAME_LENGTH)
self.address = address
self.serial = serial_connection
self._max_current = 30000
self._max_power = 2000
self._load_mode = self.SET_TYPE_RESISTANCE
self._load_value = 500
self._current = 0
self._power = 0
self._voltage = 0
self._resistance = 0
self._remote_control = 0
self._load_on = 0
self.wrong_polarity = 0
self.excessive_temp = 0
self.excessive_voltage = 0
self.excessive_power = 0
self.print_errors = print_errors
self.update_status()
# Note: Internally, all values are stored as integer values
# in the format of the load interface.
#
# Ex: current is stored in mA, but public IO is Amps
# power is stored in tenths of Watts, but public IO is Watts.
#
# Conversion is done on getter and setter methods.
@property
def max_current(self):
"""
Max Current (in Amps) allowed to be set by load.
Rounds to nearest mA.
"""
return self._max_current / 1000
@max_current.setter
def max_current(self, current_amps):
new_val = int(round(current_amps * 1000, 0))
if not 0 <= new_val <= 30000:
raise ValueError("Max Current should be between 0-30A")
self._max_current = new_val
self.__set_parameters()
@property
def max_power(self):
"""
Max Power (in Watts) allowed to be set by load.
Rounds to nearest 0.1W
"""
return self._max_power / 10
@max_power.setter
def max_power(self, power_watts):
new_val = int(round(power_watts * 10, 0))
if not 0 <= new_val <= 2000:
raise ValueError("Max Power should be between 0-200W")
self._max_power = new_val
self.__set_parameters()
def set_load_resistance(self, resistance):
"""
Changes load to resistance mode and sets resistance value.
Rounds to nearest 0.01 Ohms
:param resistance: Load Resistance in Ohms (0-500 ohms)
:return: None
"""
new_val = int(round(resistance * 100))
if not 0 <= new_val <= 50000:
raise ValueError("Load Resistance should be between 0-500 ohms")
self._load_mode = self.SET_TYPE_RESISTANCE
self._load_value = new_val
self.__set_parameters()
def set_load_power(self, power_watts):
"""
Changes load to power mode and sets power value.
Rounds to nearest 0.1W.
:param power_watts: Power in Watts (0-200)
:return:
"""
new_val = int(round(power_watts * 10))
if not 0 <= new_val <= 2000:
raise ValueError("Load Power should be between 0-200 W")
self._load_mode = self.SET_TYPE_POWER
self._load_value = new_val
self.__set_parameters()
@property
def current(self):
"""
Current value (in Amps) obtained during last update_status call.
"""
return self._current / 1000
@property
def power(self):
"""
Power value (in Watts) obtained during last update_status call.
"""
return self._power / 10
@property
def resistance(self):
"""
Resistance value (in ohms) obtained during last update_status call.
"""
return self._resistance / 100
@property
def voltage(self):
"""
Voltage value (in Volts) obtained during last update_status call.
"""
return self._voltage / 1000
@property
def remote_control(self):
"""
Remote control enabled
"""
return self._remote_control == 1
@remote_control.setter
def remote_control(self, value):
new_val = 0
if value:
new_val = 1
if new_val != self._remote_control:
self._remote_control = new_val
self.__set_load_state()
@property
def load_on(self):
"""
Load enabled state
"""
return self._load_on == 1
@load_on.setter
def load_on(self, value):
new_val = 0
if value:
new_val = 1
if new_val != self._load_on:
self._load_on = new_val
self.__set_load_state()
def __set_buffer_start(self, command):
"""
This sets the first three bytes and clears the other 23 bytes.
:param command: Command Code to set
:return: None
"""
self.STRUCT_FRONT.pack_into(self.__out_buffer, self.OFFSET_FRONT, 0xAA, self.address, command)
@staticmethod
def __get_checksum(byte_str):
"""
Calculates checksum of string, excluding last character.
Checksum is generated by summing all byte values, except last,
and taking lowest byte of result.
:param byte_str: string to checksum, plus extra character on end
:return: checksum value as int
"""
return sum(byte2int(x) for x in byte_str[:-1]) % 256
def __set_checksum(self):
"""
Sets the checksum on the last byte of buffer,
based on values in the buffer
:return: None
"""
checksum = self.__get_checksum(self.__out_buffer.raw)
self.STRUCT_CHECKSUM.pack_into(self.__out_buffer, self.OFFSET_CHECKSUM, checksum)
def __is_valid_checksum(self, byte_str):
"""
Verifies last byte checksum of full packet
:param byte_str: byte string message
:return: boolean
"""
return byte2int(byte_str[-1]) == self.__get_checksum(byte_str)
def __clear_in_buffer(self):
"""
Zeros out the in buffer
:return: None
"""
self.__in_buffer.value = bytes(b'\0' * len(self.__in_buffer))
def __send_buffer(self):
"""
Sends the contents of self.__out_buffer to serial device
:return: Number of bytes written
"""
bytes_written = self.serial.write(self.__out_buffer.raw)
if self.DEBUG_MODE:
print("Wrote: '{}'".format(binascii.hexlify(self.__out_buffer.raw)))
if bytes_written != len(self.__out_buffer):
raise IOError("{} bytes written for output buffer of size {}".format(bytes_written,
len(self.__out_buffer)))
return bytes_written
def __send_receive_buffer(self):
"""
Performs a send of self.__out_buffer and then an immediate read into self.__in_buffer
:return: None
"""
self.__clear_in_buffer()
self.__send_buffer()
read_string = self.serial.read(len(self.__in_buffer))
if self.DEBUG_MODE:
print("Read: '{}'".format(binascii.hexlify(read_string)))
if len(read_string) != len(self.__in_buffer):
raise IOError("{} bytes received for input buffer of size {}".format(len(read_string),
len(self.__in_buffer)))
if not self.__is_valid_checksum(read_string):
raise IOError("Checksum validation failed on received data")
self.__in_buffer.value = read_string
def __set_parameters(self):
"""
Sets Load Parameters from class values, including:
Max Current, Max Power, Address, Load Mode, Load Value
:return: None
"""
self.__set_buffer_start(self.CMD_SET_PARAMETERS)
# Can I send 0xFF as address to not change it each time?
# Worry about writing to EEPROM or Flash with each address change.
# Would then implement a separate address only change function.
self.STRUCT_SET_PARAMETERS.pack_into(self.__out_buffer, self.OFFSET_PAYLOAD,
self._max_current, self._max_power, self.address,
self._load_mode, self._load_value)
self.__set_checksum()
self.__send_buffer()
self.update_status()
def update_status(self, retry_count=2):
"""
Updates current values from load.
Must be called to get latest values for the following properties of class:
current
voltage
power
max current
max power
resistance
local_control
load_on
wrong_polarity
excessive_temp
excessive_voltage
excessive_power
:param retry_count: Number of times to ignore IOErrors and retry update
:return: None
"""
# I think retry should be in here.
# Throw exceptions in __update_status and handle here
cur_count = max(retry_count, 0)
while cur_count >= 0:
try:
self.__update_status()
except IOError as err:
if self.print_errors:
print("IOError: {}".format(err))
else:
if not self.__is_valid_checksum(self.__in_buffer.raw):
if self.print_errors:
raise IOError("Checksum validation failed.")
values = self.STRUCT_READ_VALUES_IN.unpack_from(self.__in_buffer, self.OFFSET_FRONT)
(self._current,
self._voltage,
self._power,
self._max_current,
self._max_power,
self._resistance,
output_state) = values[3:-1]
self._remote_control = (output_state & 0b00000001) > 0
self._load_on = (output_state & 0b00000010) > 0
self.wrong_polarity = (output_state & 0b00000100) > 0
self.excessive_temp = (output_state & 0b00001000) > 0
self.excessive_voltage = (output_state & 0b00010000) > 0
self.excessive_power = (output_state & 0b00100000) > 0
return None
cur_count -= 1
raise IOError("Retry count exceeded with serial IO.")
def __update_status(self):
self.__set_buffer_start(self.CMD_READ_VALUES)
self.STRUCT_READ_VALUES_OUT.pack_into(self.__out_buffer, 3)
self.__set_checksum()
self.__send_receive_buffer()
def __set_load_state(self):
# Remote Control is bit 2
flags = self._remote_control << 1
# Load On is bit 1
flags |= self._load_on
self.__set_buffer_start(self.CMD_LOAD_STATE)
self.STRUCT_LOAD_STATE.pack_into(self.__out_buffer, self.OFFSET_PAYLOAD, flags)
self.__set_checksum()
self.__send_buffer()
def set_program_sequence(self, array_program):
"""
Sets program up in load.
:param array_program: Populated Array3710Program object
:return: None
"""
self.__set_buffer_start(self.CMD_DEFINE_PROG_1_5)
array_program.load_buffer_one_to_five(self.__out_buffer)
self.__set_checksum()
self.__send_buffer()
self.__set_buffer_start(self.CMD_DEFINE_PROG_6_10)
array_program.load_buffer_six_to_ten(self.__out_buffer)
self.__set_checksum()
self.__send_buffer()
def start_program(self, turn_on_load=True):
"""
Starts running programmed test sequence
:return: None
"""
self.__set_buffer_start(self.CMD_START_PROG)
self.__set_checksum()
self.__send_buffer()
# Turn on Load if not on
if turn_on_load and not self.load_on:
self.load_on = True
def stop_program(self, turn_off_load=True):
"""
Stops running programmed test sequence
:return: None
"""
self.__set_buffer_start(self.CMD_STOP_PROG)
self.__set_checksum()
self.__send_buffer()
if turn_off_load and self.load_on:
self.load_on = False
|
sacherjj/array_devices
|
array_devices/array3710.py
|
Load.__set_buffer_start
|
python
|
def __set_buffer_start(self, command):
self.STRUCT_FRONT.pack_into(self.__out_buffer, self.OFFSET_FRONT, 0xAA, self.address, command)
|
This sets the first three bytes and clears the other 23 bytes.
:param command: Command Code to set
:return: None
|
train
|
https://github.com/sacherjj/array_devices/blob/ba93a081e555321125ead33cf6fc5197569ef08f/array_devices/array3710.py#L414-L420
| null |
class Load(object):
"""
Handles remote control of Array 3710A DC Electronic Load.
Also sold under Gossen, Tekpower, Circuit Specialists with same 3710A model number.
"""
DEBUG_MODE = False
# Packet command values
CMD_SET_PARAMETERS = 0x90
CMD_READ_VALUES = 0x91
CMD_LOAD_STATE = 0x92
CMD_DEFINE_PROG_1_5 = 0x93
CMD_DEFINE_PROG_6_10 = 0x94
CMD_START_PROG = 0x95
CMD_STOP_PROG = 0x96
SET_TYPE_CURRENT = 0x01
SET_TYPE_POWER = 0x02
SET_TYPE_RESISTANCE = 0x03
FRAME_LENGTH = 26
# Description of data structures for various packet types
STRUCT_FRONT = struct.Struct(b'< 3B 23x')
STRUCT_SET_PARAMETERS = struct.Struct(b'< 2H 2B H 14x')
STRUCT_READ_VALUES_OUT = struct.Struct(b'< 22x')
STRUCT_READ_VALUES_IN = struct.Struct(b'< 3B H I 4H B 7x B')
STRUCT_LOAD_STATE = struct.Struct(b'< B 21x')
STRUCT_DEFINE_PROG_LOW = struct.Struct(b'< 2B 10H')
STRUCT_DEFINE_PROG_HIGH = struct.Struct(b'< 10H B x')
STRUCT_START_PROGRAM = struct.Struct(b'< 22x')
STRUCT_STOP_PROGRAM = struct.Struct(b'< 22x')
STRUCT_CHECKSUM = struct.Struct(b'< B')
# Offsets for packing partial structs
OFFSET_FRONT = 0
OFFSET_PAYLOAD = 3
OFFSET_CHECKSUM = 25
def __init__(self, address, serial_connection, print_errors=True):
"""
Require passing in serial_connection, because multiple Loads can exist
with different addresses on a single serial port.
:param address: Load address (0x00-0xFE)
:param serial_connection: Serial Connection from serial.Serial()
:return: None
"""
# Serial Comm Packets are all 26 byte frames.
# out_buffer for building data to send, in_buffer for consuming responses.
self.__out_buffer = ctypes.create_string_buffer(self.FRAME_LENGTH)
self.__in_buffer = ctypes.create_string_buffer(self.FRAME_LENGTH)
self.address = address
self.serial = serial_connection
self._max_current = 30000
self._max_power = 2000
self._load_mode = self.SET_TYPE_RESISTANCE
self._load_value = 500
self._current = 0
self._power = 0
self._voltage = 0
self._resistance = 0
self._remote_control = 0
self._load_on = 0
self.wrong_polarity = 0
self.excessive_temp = 0
self.excessive_voltage = 0
self.excessive_power = 0
self.print_errors = print_errors
self.update_status()
# Note: Internally, all values are stored as integer values
# in the format of the load interface.
#
# Ex: current is stored in mA, but public IO is Amps
# power is stored in tenths of Watts, but public IO is Watts.
#
# Conversion is done on getter and setter methods.
@property
def max_current(self):
"""
Max Current (in Amps) allowed to be set by load.
Rounds to nearest mA.
"""
return self._max_current / 1000
@max_current.setter
def max_current(self, current_amps):
new_val = int(round(current_amps * 1000, 0))
if not 0 <= new_val <= 30000:
raise ValueError("Max Current should be between 0-30A")
self._max_current = new_val
self.__set_parameters()
@property
def max_power(self):
"""
Max Power (in Watts) allowed to be set by load.
Rounds to nearest 0.1W
"""
return self._max_power / 10
@max_power.setter
def max_power(self, power_watts):
new_val = int(round(power_watts * 10, 0))
if not 0 <= new_val <= 2000:
raise ValueError("Max Power should be between 0-200W")
self._max_power = new_val
self.__set_parameters()
def set_load_resistance(self, resistance):
"""
Changes load to resistance mode and sets resistance value.
Rounds to nearest 0.01 Ohms
:param resistance: Load Resistance in Ohms (0-500 ohms)
:return: None
"""
new_val = int(round(resistance * 100))
if not 0 <= new_val <= 50000:
raise ValueError("Load Resistance should be between 0-500 ohms")
self._load_mode = self.SET_TYPE_RESISTANCE
self._load_value = new_val
self.__set_parameters()
def set_load_power(self, power_watts):
"""
Changes load to power mode and sets power value.
Rounds to nearest 0.1W.
:param power_watts: Power in Watts (0-200)
:return:
"""
new_val = int(round(power_watts * 10))
if not 0 <= new_val <= 2000:
raise ValueError("Load Power should be between 0-200 W")
self._load_mode = self.SET_TYPE_POWER
self._load_value = new_val
self.__set_parameters()
def set_load_current(self, current_amps):
"""
Changes load to current mode and sets current value.
Rounds to nearest mA.
:param current_amps: Current in Amps (0-30A)
:return: None
"""
new_val = int(round(current_amps * 1000))
if not 0 <= new_val <= 30000:
raise ValueError("Load Current should be between 0-30A")
self._load_mode = self.SET_TYPE_CURRENT
self._load_value = new_val
self.__set_parameters()
@property
def current(self):
"""
Current value (in Amps) obtained during last update_status call.
"""
return self._current / 1000
@property
def power(self):
"""
Power value (in Watts) obtained during last update_status call.
"""
return self._power / 10
@property
def resistance(self):
"""
Resistance value (in ohms) obtained during last update_status call.
"""
return self._resistance / 100
@property
def voltage(self):
"""
Voltage value (in Volts) obtained during last update_status call.
"""
return self._voltage / 1000
@property
def remote_control(self):
"""
Remote control enabled
"""
return self._remote_control == 1
@remote_control.setter
def remote_control(self, value):
new_val = 0
if value:
new_val = 1
if new_val != self._remote_control:
self._remote_control = new_val
self.__set_load_state()
@property
def load_on(self):
"""
Load enabled state
"""
return self._load_on == 1
@load_on.setter
def load_on(self, value):
new_val = 0
if value:
new_val = 1
if new_val != self._load_on:
self._load_on = new_val
self.__set_load_state()
@staticmethod
def __get_checksum(byte_str):
"""
Calculates checksum of string, excluding last character.
Checksum is generated by summing all byte values, except last,
and taking lowest byte of result.
:param byte_str: string to checksum, plus extra character on end
:return: checksum value as int
"""
return sum(byte2int(x) for x in byte_str[:-1]) % 256
def __set_checksum(self):
"""
Sets the checksum on the last byte of buffer,
based on values in the buffer
:return: None
"""
checksum = self.__get_checksum(self.__out_buffer.raw)
self.STRUCT_CHECKSUM.pack_into(self.__out_buffer, self.OFFSET_CHECKSUM, checksum)
def __is_valid_checksum(self, byte_str):
"""
Verifies last byte checksum of full packet
:param byte_str: byte string message
:return: boolean
"""
return byte2int(byte_str[-1]) == self.__get_checksum(byte_str)
def __clear_in_buffer(self):
"""
Zeros out the in buffer
:return: None
"""
self.__in_buffer.value = bytes(b'\0' * len(self.__in_buffer))
def __send_buffer(self):
"""
Sends the contents of self.__out_buffer to serial device
:return: Number of bytes written
"""
bytes_written = self.serial.write(self.__out_buffer.raw)
if self.DEBUG_MODE:
print("Wrote: '{}'".format(binascii.hexlify(self.__out_buffer.raw)))
if bytes_written != len(self.__out_buffer):
raise IOError("{} bytes written for output buffer of size {}".format(bytes_written,
len(self.__out_buffer)))
return bytes_written
def __send_receive_buffer(self):
"""
Performs a send of self.__out_buffer and then an immediate read into self.__in_buffer
:return: None
"""
self.__clear_in_buffer()
self.__send_buffer()
read_string = self.serial.read(len(self.__in_buffer))
if self.DEBUG_MODE:
print("Read: '{}'".format(binascii.hexlify(read_string)))
if len(read_string) != len(self.__in_buffer):
raise IOError("{} bytes received for input buffer of size {}".format(len(read_string),
len(self.__in_buffer)))
if not self.__is_valid_checksum(read_string):
raise IOError("Checksum validation failed on received data")
self.__in_buffer.value = read_string
def __set_parameters(self):
"""
Sets Load Parameters from class values, including:
Max Current, Max Power, Address, Load Mode, Load Value
:return: None
"""
self.__set_buffer_start(self.CMD_SET_PARAMETERS)
# Can I send 0xFF as address to not change it each time?
# Worry about writing to EEPROM or Flash with each address change.
# Would then implement a separate address only change function.
self.STRUCT_SET_PARAMETERS.pack_into(self.__out_buffer, self.OFFSET_PAYLOAD,
self._max_current, self._max_power, self.address,
self._load_mode, self._load_value)
self.__set_checksum()
self.__send_buffer()
self.update_status()
def update_status(self, retry_count=2):
"""
Updates current values from load.
Must be called to get latest values for the following properties of class:
current
voltage
power
max current
max power
resistance
local_control
load_on
wrong_polarity
excessive_temp
excessive_voltage
excessive_power
:param retry_count: Number of times to ignore IOErrors and retry update
:return: None
"""
# I think retry should be in here.
# Throw exceptions in __update_status and handle here
cur_count = max(retry_count, 0)
while cur_count >= 0:
try:
self.__update_status()
except IOError as err:
if self.print_errors:
print("IOError: {}".format(err))
else:
if not self.__is_valid_checksum(self.__in_buffer.raw):
if self.print_errors:
raise IOError("Checksum validation failed.")
values = self.STRUCT_READ_VALUES_IN.unpack_from(self.__in_buffer, self.OFFSET_FRONT)
(self._current,
self._voltage,
self._power,
self._max_current,
self._max_power,
self._resistance,
output_state) = values[3:-1]
self._remote_control = (output_state & 0b00000001) > 0
self._load_on = (output_state & 0b00000010) > 0
self.wrong_polarity = (output_state & 0b00000100) > 0
self.excessive_temp = (output_state & 0b00001000) > 0
self.excessive_voltage = (output_state & 0b00010000) > 0
self.excessive_power = (output_state & 0b00100000) > 0
return None
cur_count -= 1
raise IOError("Retry count exceeded with serial IO.")
def __update_status(self):
self.__set_buffer_start(self.CMD_READ_VALUES)
self.STRUCT_READ_VALUES_OUT.pack_into(self.__out_buffer, 3)
self.__set_checksum()
self.__send_receive_buffer()
def __set_load_state(self):
# Remote Control is bit 2
flags = self._remote_control << 1
# Load On is bit 1
flags |= self._load_on
self.__set_buffer_start(self.CMD_LOAD_STATE)
self.STRUCT_LOAD_STATE.pack_into(self.__out_buffer, self.OFFSET_PAYLOAD, flags)
self.__set_checksum()
self.__send_buffer()
def set_program_sequence(self, array_program):
"""
Sets program up in load.
:param array_program: Populated Array3710Program object
:return: None
"""
self.__set_buffer_start(self.CMD_DEFINE_PROG_1_5)
array_program.load_buffer_one_to_five(self.__out_buffer)
self.__set_checksum()
self.__send_buffer()
self.__set_buffer_start(self.CMD_DEFINE_PROG_6_10)
array_program.load_buffer_six_to_ten(self.__out_buffer)
self.__set_checksum()
self.__send_buffer()
def start_program(self, turn_on_load=True):
"""
Starts running programmed test sequence
:return: None
"""
self.__set_buffer_start(self.CMD_START_PROG)
self.__set_checksum()
self.__send_buffer()
# Turn on Load if not on
if turn_on_load and not self.load_on:
self.load_on = True
def stop_program(self, turn_off_load=True):
"""
Stops running programmed test sequence
:return: None
"""
self.__set_buffer_start(self.CMD_STOP_PROG)
self.__set_checksum()
self.__send_buffer()
if turn_off_load and self.load_on:
self.load_on = False
|
sacherjj/array_devices
|
array_devices/array3710.py
|
Load.__set_checksum
|
python
|
def __set_checksum(self):
checksum = self.__get_checksum(self.__out_buffer.raw)
self.STRUCT_CHECKSUM.pack_into(self.__out_buffer, self.OFFSET_CHECKSUM, checksum)
|
Sets the checksum on the last byte of buffer,
based on values in the buffer
:return: None
|
train
|
https://github.com/sacherjj/array_devices/blob/ba93a081e555321125ead33cf6fc5197569ef08f/array_devices/array3710.py#L434-L441
|
[
"def __get_checksum(byte_str):\n \"\"\"\n Calculates checksum of string, excluding last character.\n Checksum is generated by summing all byte values, except last,\n and taking lowest byte of result.\n\n :param byte_str: string to checksum, plus extra character on end\n :return: checksum value as int\n \"\"\"\n return sum(byte2int(x) for x in byte_str[:-1]) % 256\n"
] |
class Load(object):
"""
Handles remote control of Array 3710A DC Electronic Load.
Also sold under Gossen, Tekpower, Circuit Specialists with same 3710A model number.
"""
DEBUG_MODE = False
# Packet command values
CMD_SET_PARAMETERS = 0x90
CMD_READ_VALUES = 0x91
CMD_LOAD_STATE = 0x92
CMD_DEFINE_PROG_1_5 = 0x93
CMD_DEFINE_PROG_6_10 = 0x94
CMD_START_PROG = 0x95
CMD_STOP_PROG = 0x96
SET_TYPE_CURRENT = 0x01
SET_TYPE_POWER = 0x02
SET_TYPE_RESISTANCE = 0x03
FRAME_LENGTH = 26
# Description of data structures for various packet types
STRUCT_FRONT = struct.Struct(b'< 3B 23x')
STRUCT_SET_PARAMETERS = struct.Struct(b'< 2H 2B H 14x')
STRUCT_READ_VALUES_OUT = struct.Struct(b'< 22x')
STRUCT_READ_VALUES_IN = struct.Struct(b'< 3B H I 4H B 7x B')
STRUCT_LOAD_STATE = struct.Struct(b'< B 21x')
STRUCT_DEFINE_PROG_LOW = struct.Struct(b'< 2B 10H')
STRUCT_DEFINE_PROG_HIGH = struct.Struct(b'< 10H B x')
STRUCT_START_PROGRAM = struct.Struct(b'< 22x')
STRUCT_STOP_PROGRAM = struct.Struct(b'< 22x')
STRUCT_CHECKSUM = struct.Struct(b'< B')
# Offsets for packing partial structs
OFFSET_FRONT = 0
OFFSET_PAYLOAD = 3
OFFSET_CHECKSUM = 25
def __init__(self, address, serial_connection, print_errors=True):
"""
Require passing in serial_connection, because multiple Loads can exist
with different addresses on a single serial port.
:param address: Load address (0x00-0xFE)
:param serial_connection: Serial Connection from serial.Serial()
:return: None
"""
# Serial Comm Packets are all 26 byte frames.
# out_buffer for building data to send, in_buffer for consuming responses.
self.__out_buffer = ctypes.create_string_buffer(self.FRAME_LENGTH)
self.__in_buffer = ctypes.create_string_buffer(self.FRAME_LENGTH)
self.address = address
self.serial = serial_connection
self._max_current = 30000
self._max_power = 2000
self._load_mode = self.SET_TYPE_RESISTANCE
self._load_value = 500
self._current = 0
self._power = 0
self._voltage = 0
self._resistance = 0
self._remote_control = 0
self._load_on = 0
self.wrong_polarity = 0
self.excessive_temp = 0
self.excessive_voltage = 0
self.excessive_power = 0
self.print_errors = print_errors
self.update_status()
# Note: Internally, all values are stored as integer values
# in the format of the load interface.
#
# Ex: current is stored in mA, but public IO is Amps
# power is stored in tenths of Watts, but public IO is Watts.
#
# Conversion is done on getter and setter methods.
@property
def max_current(self):
"""
Max Current (in Amps) allowed to be set by load.
Rounds to nearest mA.
"""
return self._max_current / 1000
@max_current.setter
def max_current(self, current_amps):
new_val = int(round(current_amps * 1000, 0))
if not 0 <= new_val <= 30000:
raise ValueError("Max Current should be between 0-30A")
self._max_current = new_val
self.__set_parameters()
@property
def max_power(self):
"""
Max Power (in Watts) allowed to be set by load.
Rounds to nearest 0.1W
"""
return self._max_power / 10
@max_power.setter
def max_power(self, power_watts):
new_val = int(round(power_watts * 10, 0))
if not 0 <= new_val <= 2000:
raise ValueError("Max Power should be between 0-200W")
self._max_power = new_val
self.__set_parameters()
def set_load_resistance(self, resistance):
"""
Changes load to resistance mode and sets resistance value.
Rounds to nearest 0.01 Ohms
:param resistance: Load Resistance in Ohms (0-500 ohms)
:return: None
"""
new_val = int(round(resistance * 100))
if not 0 <= new_val <= 50000:
raise ValueError("Load Resistance should be between 0-500 ohms")
self._load_mode = self.SET_TYPE_RESISTANCE
self._load_value = new_val
self.__set_parameters()
def set_load_power(self, power_watts):
"""
Changes load to power mode and sets power value.
Rounds to nearest 0.1W.
:param power_watts: Power in Watts (0-200)
:return:
"""
new_val = int(round(power_watts * 10))
if not 0 <= new_val <= 2000:
raise ValueError("Load Power should be between 0-200 W")
self._load_mode = self.SET_TYPE_POWER
self._load_value = new_val
self.__set_parameters()
def set_load_current(self, current_amps):
"""
Changes load to current mode and sets current value.
Rounds to nearest mA.
:param current_amps: Current in Amps (0-30A)
:return: None
"""
new_val = int(round(current_amps * 1000))
if not 0 <= new_val <= 30000:
raise ValueError("Load Current should be between 0-30A")
self._load_mode = self.SET_TYPE_CURRENT
self._load_value = new_val
self.__set_parameters()
@property
def current(self):
"""
Current value (in Amps) obtained during last update_status call.
"""
return self._current / 1000
@property
def power(self):
"""
Power value (in Watts) obtained during last update_status call.
"""
return self._power / 10
@property
def resistance(self):
"""
Resistance value (in ohms) obtained during last update_status call.
"""
return self._resistance / 100
@property
def voltage(self):
"""
Voltage value (in Volts) obtained during last update_status call.
"""
return self._voltage / 1000
@property
def remote_control(self):
"""
Remote control enabled
"""
return self._remote_control == 1
@remote_control.setter
def remote_control(self, value):
new_val = 0
if value:
new_val = 1
if new_val != self._remote_control:
self._remote_control = new_val
self.__set_load_state()
@property
def load_on(self):
"""
Load enabled state
"""
return self._load_on == 1
@load_on.setter
def load_on(self, value):
new_val = 0
if value:
new_val = 1
if new_val != self._load_on:
self._load_on = new_val
self.__set_load_state()
def __set_buffer_start(self, command):
"""
This sets the first three bytes and clears the other 23 bytes.
:param command: Command Code to set
:return: None
"""
self.STRUCT_FRONT.pack_into(self.__out_buffer, self.OFFSET_FRONT, 0xAA, self.address, command)
@staticmethod
def __get_checksum(byte_str):
"""
Calculates checksum of string, excluding last character.
Checksum is generated by summing all byte values, except last,
and taking lowest byte of result.
:param byte_str: string to checksum, plus extra character on end
:return: checksum value as int
"""
return sum(byte2int(x) for x in byte_str[:-1]) % 256
def __is_valid_checksum(self, byte_str):
"""
Verifies last byte checksum of full packet
:param byte_str: byte string message
:return: boolean
"""
return byte2int(byte_str[-1]) == self.__get_checksum(byte_str)
def __clear_in_buffer(self):
"""
Zeros out the in buffer
:return: None
"""
self.__in_buffer.value = bytes(b'\0' * len(self.__in_buffer))
def __send_buffer(self):
"""
Sends the contents of self.__out_buffer to serial device
:return: Number of bytes written
"""
bytes_written = self.serial.write(self.__out_buffer.raw)
if self.DEBUG_MODE:
print("Wrote: '{}'".format(binascii.hexlify(self.__out_buffer.raw)))
if bytes_written != len(self.__out_buffer):
raise IOError("{} bytes written for output buffer of size {}".format(bytes_written,
len(self.__out_buffer)))
return bytes_written
def __send_receive_buffer(self):
"""
Performs a send of self.__out_buffer and then an immediate read into self.__in_buffer
:return: None
"""
self.__clear_in_buffer()
self.__send_buffer()
read_string = self.serial.read(len(self.__in_buffer))
if self.DEBUG_MODE:
print("Read: '{}'".format(binascii.hexlify(read_string)))
if len(read_string) != len(self.__in_buffer):
raise IOError("{} bytes received for input buffer of size {}".format(len(read_string),
len(self.__in_buffer)))
if not self.__is_valid_checksum(read_string):
raise IOError("Checksum validation failed on received data")
self.__in_buffer.value = read_string
def __set_parameters(self):
"""
Sets Load Parameters from class values, including:
Max Current, Max Power, Address, Load Mode, Load Value
:return: None
"""
self.__set_buffer_start(self.CMD_SET_PARAMETERS)
# Can I send 0xFF as address to not change it each time?
# Worry about writing to EEPROM or Flash with each address change.
# Would then implement a separate address only change function.
self.STRUCT_SET_PARAMETERS.pack_into(self.__out_buffer, self.OFFSET_PAYLOAD,
self._max_current, self._max_power, self.address,
self._load_mode, self._load_value)
self.__set_checksum()
self.__send_buffer()
self.update_status()
def update_status(self, retry_count=2):
"""
Updates current values from load.
Must be called to get latest values for the following properties of class:
current
voltage
power
max current
max power
resistance
local_control
load_on
wrong_polarity
excessive_temp
excessive_voltage
excessive_power
:param retry_count: Number of times to ignore IOErrors and retry update
:return: None
"""
# I think retry should be in here.
# Throw exceptions in __update_status and handle here
cur_count = max(retry_count, 0)
while cur_count >= 0:
try:
self.__update_status()
except IOError as err:
if self.print_errors:
print("IOError: {}".format(err))
else:
if not self.__is_valid_checksum(self.__in_buffer.raw):
if self.print_errors:
raise IOError("Checksum validation failed.")
values = self.STRUCT_READ_VALUES_IN.unpack_from(self.__in_buffer, self.OFFSET_FRONT)
(self._current,
self._voltage,
self._power,
self._max_current,
self._max_power,
self._resistance,
output_state) = values[3:-1]
self._remote_control = (output_state & 0b00000001) > 0
self._load_on = (output_state & 0b00000010) > 0
self.wrong_polarity = (output_state & 0b00000100) > 0
self.excessive_temp = (output_state & 0b00001000) > 0
self.excessive_voltage = (output_state & 0b00010000) > 0
self.excessive_power = (output_state & 0b00100000) > 0
return None
cur_count -= 1
raise IOError("Retry count exceeded with serial IO.")
def __update_status(self):
self.__set_buffer_start(self.CMD_READ_VALUES)
self.STRUCT_READ_VALUES_OUT.pack_into(self.__out_buffer, 3)
self.__set_checksum()
self.__send_receive_buffer()
def __set_load_state(self):
# Remote Control is bit 2
flags = self._remote_control << 1
# Load On is bit 1
flags |= self._load_on
self.__set_buffer_start(self.CMD_LOAD_STATE)
self.STRUCT_LOAD_STATE.pack_into(self.__out_buffer, self.OFFSET_PAYLOAD, flags)
self.__set_checksum()
self.__send_buffer()
def set_program_sequence(self, array_program):
"""
Sets program up in load.
:param array_program: Populated Array3710Program object
:return: None
"""
self.__set_buffer_start(self.CMD_DEFINE_PROG_1_5)
array_program.load_buffer_one_to_five(self.__out_buffer)
self.__set_checksum()
self.__send_buffer()
self.__set_buffer_start(self.CMD_DEFINE_PROG_6_10)
array_program.load_buffer_six_to_ten(self.__out_buffer)
self.__set_checksum()
self.__send_buffer()
def start_program(self, turn_on_load=True):
"""
Starts running programmed test sequence
:return: None
"""
self.__set_buffer_start(self.CMD_START_PROG)
self.__set_checksum()
self.__send_buffer()
# Turn on Load if not on
if turn_on_load and not self.load_on:
self.load_on = True
def stop_program(self, turn_off_load=True):
"""
Stops running programmed test sequence
:return: None
"""
self.__set_buffer_start(self.CMD_STOP_PROG)
self.__set_checksum()
self.__send_buffer()
if turn_off_load and self.load_on:
self.load_on = False
|
sacherjj/array_devices
|
array_devices/array3710.py
|
Load.__clear_in_buffer
|
python
|
def __clear_in_buffer(self):
self.__in_buffer.value = bytes(b'\0' * len(self.__in_buffer))
|
Zeros out the in buffer
:return: None
|
train
|
https://github.com/sacherjj/array_devices/blob/ba93a081e555321125ead33cf6fc5197569ef08f/array_devices/array3710.py#L451-L456
| null |
class Load(object):
"""
Handles remote control of Array 3710A DC Electronic Load.
Also sold under Gossen, Tekpower, Circuit Specialists with same 3710A model number.
"""
DEBUG_MODE = False
# Packet command values
CMD_SET_PARAMETERS = 0x90
CMD_READ_VALUES = 0x91
CMD_LOAD_STATE = 0x92
CMD_DEFINE_PROG_1_5 = 0x93
CMD_DEFINE_PROG_6_10 = 0x94
CMD_START_PROG = 0x95
CMD_STOP_PROG = 0x96
SET_TYPE_CURRENT = 0x01
SET_TYPE_POWER = 0x02
SET_TYPE_RESISTANCE = 0x03
FRAME_LENGTH = 26
# Description of data structures for various packet types
STRUCT_FRONT = struct.Struct(b'< 3B 23x')
STRUCT_SET_PARAMETERS = struct.Struct(b'< 2H 2B H 14x')
STRUCT_READ_VALUES_OUT = struct.Struct(b'< 22x')
STRUCT_READ_VALUES_IN = struct.Struct(b'< 3B H I 4H B 7x B')
STRUCT_LOAD_STATE = struct.Struct(b'< B 21x')
STRUCT_DEFINE_PROG_LOW = struct.Struct(b'< 2B 10H')
STRUCT_DEFINE_PROG_HIGH = struct.Struct(b'< 10H B x')
STRUCT_START_PROGRAM = struct.Struct(b'< 22x')
STRUCT_STOP_PROGRAM = struct.Struct(b'< 22x')
STRUCT_CHECKSUM = struct.Struct(b'< B')
# Offsets for packing partial structs
OFFSET_FRONT = 0
OFFSET_PAYLOAD = 3
OFFSET_CHECKSUM = 25
def __init__(self, address, serial_connection, print_errors=True):
"""
Require passing in serial_connection, because multiple Loads can exist
with different addresses on a single serial port.
:param address: Load address (0x00-0xFE)
:param serial_connection: Serial Connection from serial.Serial()
:return: None
"""
# Serial Comm Packets are all 26 byte frames.
# out_buffer for building data to send, in_buffer for consuming responses.
self.__out_buffer = ctypes.create_string_buffer(self.FRAME_LENGTH)
self.__in_buffer = ctypes.create_string_buffer(self.FRAME_LENGTH)
self.address = address
self.serial = serial_connection
self._max_current = 30000
self._max_power = 2000
self._load_mode = self.SET_TYPE_RESISTANCE
self._load_value = 500
self._current = 0
self._power = 0
self._voltage = 0
self._resistance = 0
self._remote_control = 0
self._load_on = 0
self.wrong_polarity = 0
self.excessive_temp = 0
self.excessive_voltage = 0
self.excessive_power = 0
self.print_errors = print_errors
self.update_status()
# Note: Internally, all values are stored as integer values
# in the format of the load interface.
#
# Ex: current is stored in mA, but public IO is Amps
# power is stored in tenths of Watts, but public IO is Watts.
#
# Conversion is done on getter and setter methods.
@property
def max_current(self):
"""
Max Current (in Amps) allowed to be set by load.
Rounds to nearest mA.
"""
return self._max_current / 1000
@max_current.setter
def max_current(self, current_amps):
new_val = int(round(current_amps * 1000, 0))
if not 0 <= new_val <= 30000:
raise ValueError("Max Current should be between 0-30A")
self._max_current = new_val
self.__set_parameters()
@property
def max_power(self):
"""
Max Power (in Watts) allowed to be set by load.
Rounds to nearest 0.1W
"""
return self._max_power / 10
@max_power.setter
def max_power(self, power_watts):
new_val = int(round(power_watts * 10, 0))
if not 0 <= new_val <= 2000:
raise ValueError("Max Power should be between 0-200W")
self._max_power = new_val
self.__set_parameters()
def set_load_resistance(self, resistance):
"""
Changes load to resistance mode and sets resistance value.
Rounds to nearest 0.01 Ohms
:param resistance: Load Resistance in Ohms (0-500 ohms)
:return: None
"""
new_val = int(round(resistance * 100))
if not 0 <= new_val <= 50000:
raise ValueError("Load Resistance should be between 0-500 ohms")
self._load_mode = self.SET_TYPE_RESISTANCE
self._load_value = new_val
self.__set_parameters()
def set_load_power(self, power_watts):
"""
Changes load to power mode and sets power value.
Rounds to nearest 0.1W.
:param power_watts: Power in Watts (0-200)
:return:
"""
new_val = int(round(power_watts * 10))
if not 0 <= new_val <= 2000:
raise ValueError("Load Power should be between 0-200 W")
self._load_mode = self.SET_TYPE_POWER
self._load_value = new_val
self.__set_parameters()
def set_load_current(self, current_amps):
"""
Changes load to current mode and sets current value.
Rounds to nearest mA.
:param current_amps: Current in Amps (0-30A)
:return: None
"""
new_val = int(round(current_amps * 1000))
if not 0 <= new_val <= 30000:
raise ValueError("Load Current should be between 0-30A")
self._load_mode = self.SET_TYPE_CURRENT
self._load_value = new_val
self.__set_parameters()
@property
def current(self):
"""
Current value (in Amps) obtained during last update_status call.
"""
return self._current / 1000
@property
def power(self):
"""
Power value (in Watts) obtained during last update_status call.
"""
return self._power / 10
@property
def resistance(self):
"""
Resistance value (in ohms) obtained during last update_status call.
"""
return self._resistance / 100
@property
def voltage(self):
"""
Voltage value (in Volts) obtained during last update_status call.
"""
return self._voltage / 1000
@property
def remote_control(self):
"""
Remote control enabled
"""
return self._remote_control == 1
@remote_control.setter
def remote_control(self, value):
new_val = 0
if value:
new_val = 1
if new_val != self._remote_control:
self._remote_control = new_val
self.__set_load_state()
@property
def load_on(self):
"""
Load enabled state
"""
return self._load_on == 1
@load_on.setter
def load_on(self, value):
new_val = 0
if value:
new_val = 1
if new_val != self._load_on:
self._load_on = new_val
self.__set_load_state()
def __set_buffer_start(self, command):
"""
This sets the first three bytes and clears the other 23 bytes.
:param command: Command Code to set
:return: None
"""
self.STRUCT_FRONT.pack_into(self.__out_buffer, self.OFFSET_FRONT, 0xAA, self.address, command)
@staticmethod
def __get_checksum(byte_str):
"""
Calculates checksum of string, excluding last character.
Checksum is generated by summing all byte values, except last,
and taking lowest byte of result.
:param byte_str: string to checksum, plus extra character on end
:return: checksum value as int
"""
return sum(byte2int(x) for x in byte_str[:-1]) % 256
def __set_checksum(self):
"""
Sets the checksum on the last byte of buffer,
based on values in the buffer
:return: None
"""
checksum = self.__get_checksum(self.__out_buffer.raw)
self.STRUCT_CHECKSUM.pack_into(self.__out_buffer, self.OFFSET_CHECKSUM, checksum)
def __is_valid_checksum(self, byte_str):
"""
Verifies last byte checksum of full packet
:param byte_str: byte string message
:return: boolean
"""
return byte2int(byte_str[-1]) == self.__get_checksum(byte_str)
def __send_buffer(self):
"""
Sends the contents of self.__out_buffer to serial device
:return: Number of bytes written
"""
bytes_written = self.serial.write(self.__out_buffer.raw)
if self.DEBUG_MODE:
print("Wrote: '{}'".format(binascii.hexlify(self.__out_buffer.raw)))
if bytes_written != len(self.__out_buffer):
raise IOError("{} bytes written for output buffer of size {}".format(bytes_written,
len(self.__out_buffer)))
return bytes_written
def __send_receive_buffer(self):
"""
Performs a send of self.__out_buffer and then an immediate read into self.__in_buffer
:return: None
"""
self.__clear_in_buffer()
self.__send_buffer()
read_string = self.serial.read(len(self.__in_buffer))
if self.DEBUG_MODE:
print("Read: '{}'".format(binascii.hexlify(read_string)))
if len(read_string) != len(self.__in_buffer):
raise IOError("{} bytes received for input buffer of size {}".format(len(read_string),
len(self.__in_buffer)))
if not self.__is_valid_checksum(read_string):
raise IOError("Checksum validation failed on received data")
self.__in_buffer.value = read_string
def __set_parameters(self):
"""
Sets Load Parameters from class values, including:
Max Current, Max Power, Address, Load Mode, Load Value
:return: None
"""
self.__set_buffer_start(self.CMD_SET_PARAMETERS)
# Can I send 0xFF as address to not change it each time?
# Worry about writing to EEPROM or Flash with each address change.
# Would then implement a separate address only change function.
self.STRUCT_SET_PARAMETERS.pack_into(self.__out_buffer, self.OFFSET_PAYLOAD,
self._max_current, self._max_power, self.address,
self._load_mode, self._load_value)
self.__set_checksum()
self.__send_buffer()
self.update_status()
def update_status(self, retry_count=2):
"""
Updates current values from load.
Must be called to get latest values for the following properties of class:
current
voltage
power
max current
max power
resistance
local_control
load_on
wrong_polarity
excessive_temp
excessive_voltage
excessive_power
:param retry_count: Number of times to ignore IOErrors and retry update
:return: None
"""
# I think retry should be in here.
# Throw exceptions in __update_status and handle here
cur_count = max(retry_count, 0)
while cur_count >= 0:
try:
self.__update_status()
except IOError as err:
if self.print_errors:
print("IOError: {}".format(err))
else:
if not self.__is_valid_checksum(self.__in_buffer.raw):
if self.print_errors:
raise IOError("Checksum validation failed.")
values = self.STRUCT_READ_VALUES_IN.unpack_from(self.__in_buffer, self.OFFSET_FRONT)
(self._current,
self._voltage,
self._power,
self._max_current,
self._max_power,
self._resistance,
output_state) = values[3:-1]
self._remote_control = (output_state & 0b00000001) > 0
self._load_on = (output_state & 0b00000010) > 0
self.wrong_polarity = (output_state & 0b00000100) > 0
self.excessive_temp = (output_state & 0b00001000) > 0
self.excessive_voltage = (output_state & 0b00010000) > 0
self.excessive_power = (output_state & 0b00100000) > 0
return None
cur_count -= 1
raise IOError("Retry count exceeded with serial IO.")
def __update_status(self):
self.__set_buffer_start(self.CMD_READ_VALUES)
self.STRUCT_READ_VALUES_OUT.pack_into(self.__out_buffer, 3)
self.__set_checksum()
self.__send_receive_buffer()
def __set_load_state(self):
# Remote Control is bit 2
flags = self._remote_control << 1
# Load On is bit 1
flags |= self._load_on
self.__set_buffer_start(self.CMD_LOAD_STATE)
self.STRUCT_LOAD_STATE.pack_into(self.__out_buffer, self.OFFSET_PAYLOAD, flags)
self.__set_checksum()
self.__send_buffer()
def set_program_sequence(self, array_program):
"""
Sets program up in load.
:param array_program: Populated Array3710Program object
:return: None
"""
self.__set_buffer_start(self.CMD_DEFINE_PROG_1_5)
array_program.load_buffer_one_to_five(self.__out_buffer)
self.__set_checksum()
self.__send_buffer()
self.__set_buffer_start(self.CMD_DEFINE_PROG_6_10)
array_program.load_buffer_six_to_ten(self.__out_buffer)
self.__set_checksum()
self.__send_buffer()
def start_program(self, turn_on_load=True):
"""
Starts running programmed test sequence
:return: None
"""
self.__set_buffer_start(self.CMD_START_PROG)
self.__set_checksum()
self.__send_buffer()
# Turn on Load if not on
if turn_on_load and not self.load_on:
self.load_on = True
def stop_program(self, turn_off_load=True):
"""
Stops running programmed test sequence
:return: None
"""
self.__set_buffer_start(self.CMD_STOP_PROG)
self.__set_checksum()
self.__send_buffer()
if turn_off_load and self.load_on:
self.load_on = False
|
sacherjj/array_devices
|
array_devices/array3710.py
|
Load.__send_buffer
|
python
|
def __send_buffer(self):
bytes_written = self.serial.write(self.__out_buffer.raw)
if self.DEBUG_MODE:
print("Wrote: '{}'".format(binascii.hexlify(self.__out_buffer.raw)))
if bytes_written != len(self.__out_buffer):
raise IOError("{} bytes written for output buffer of size {}".format(bytes_written,
len(self.__out_buffer)))
return bytes_written
|
Sends the contents of self.__out_buffer to serial device
:return: Number of bytes written
|
train
|
https://github.com/sacherjj/array_devices/blob/ba93a081e555321125ead33cf6fc5197569ef08f/array_devices/array3710.py#L458-L469
| null |
class Load(object):
"""
Handles remote control of Array 3710A DC Electronic Load.
Also sold under Gossen, Tekpower, Circuit Specialists with same 3710A model number.
"""
DEBUG_MODE = False
# Packet command values
CMD_SET_PARAMETERS = 0x90
CMD_READ_VALUES = 0x91
CMD_LOAD_STATE = 0x92
CMD_DEFINE_PROG_1_5 = 0x93
CMD_DEFINE_PROG_6_10 = 0x94
CMD_START_PROG = 0x95
CMD_STOP_PROG = 0x96
SET_TYPE_CURRENT = 0x01
SET_TYPE_POWER = 0x02
SET_TYPE_RESISTANCE = 0x03
FRAME_LENGTH = 26
# Description of data structures for various packet types
STRUCT_FRONT = struct.Struct(b'< 3B 23x')
STRUCT_SET_PARAMETERS = struct.Struct(b'< 2H 2B H 14x')
STRUCT_READ_VALUES_OUT = struct.Struct(b'< 22x')
STRUCT_READ_VALUES_IN = struct.Struct(b'< 3B H I 4H B 7x B')
STRUCT_LOAD_STATE = struct.Struct(b'< B 21x')
STRUCT_DEFINE_PROG_LOW = struct.Struct(b'< 2B 10H')
STRUCT_DEFINE_PROG_HIGH = struct.Struct(b'< 10H B x')
STRUCT_START_PROGRAM = struct.Struct(b'< 22x')
STRUCT_STOP_PROGRAM = struct.Struct(b'< 22x')
STRUCT_CHECKSUM = struct.Struct(b'< B')
# Offsets for packing partial structs
OFFSET_FRONT = 0
OFFSET_PAYLOAD = 3
OFFSET_CHECKSUM = 25
def __init__(self, address, serial_connection, print_errors=True):
"""
Require passing in serial_connection, because multiple Loads can exist
with different addresses on a single serial port.
:param address: Load address (0x00-0xFE)
:param serial_connection: Serial Connection from serial.Serial()
:return: None
"""
# Serial Comm Packets are all 26 byte frames.
# out_buffer for building data to send, in_buffer for consuming responses.
self.__out_buffer = ctypes.create_string_buffer(self.FRAME_LENGTH)
self.__in_buffer = ctypes.create_string_buffer(self.FRAME_LENGTH)
self.address = address
self.serial = serial_connection
self._max_current = 30000
self._max_power = 2000
self._load_mode = self.SET_TYPE_RESISTANCE
self._load_value = 500
self._current = 0
self._power = 0
self._voltage = 0
self._resistance = 0
self._remote_control = 0
self._load_on = 0
self.wrong_polarity = 0
self.excessive_temp = 0
self.excessive_voltage = 0
self.excessive_power = 0
self.print_errors = print_errors
self.update_status()
# Note: Internally, all values are stored as integer values
# in the format of the load interface.
#
# Ex: current is stored in mA, but public IO is Amps
# power is stored in tenths of Watts, but public IO is Watts.
#
# Conversion is done on getter and setter methods.
@property
def max_current(self):
"""
Max Current (in Amps) allowed to be set by load.
Rounds to nearest mA.
"""
return self._max_current / 1000
@max_current.setter
def max_current(self, current_amps):
new_val = int(round(current_amps * 1000, 0))
if not 0 <= new_val <= 30000:
raise ValueError("Max Current should be between 0-30A")
self._max_current = new_val
self.__set_parameters()
@property
def max_power(self):
"""
Max Power (in Watts) allowed to be set by load.
Rounds to nearest 0.1W
"""
return self._max_power / 10
@max_power.setter
def max_power(self, power_watts):
new_val = int(round(power_watts * 10, 0))
if not 0 <= new_val <= 2000:
raise ValueError("Max Power should be between 0-200W")
self._max_power = new_val
self.__set_parameters()
def set_load_resistance(self, resistance):
"""
Changes load to resistance mode and sets resistance value.
Rounds to nearest 0.01 Ohms
:param resistance: Load Resistance in Ohms (0-500 ohms)
:return: None
"""
new_val = int(round(resistance * 100))
if not 0 <= new_val <= 50000:
raise ValueError("Load Resistance should be between 0-500 ohms")
self._load_mode = self.SET_TYPE_RESISTANCE
self._load_value = new_val
self.__set_parameters()
def set_load_power(self, power_watts):
"""
Changes load to power mode and sets power value.
Rounds to nearest 0.1W.
:param power_watts: Power in Watts (0-200)
:return:
"""
new_val = int(round(power_watts * 10))
if not 0 <= new_val <= 2000:
raise ValueError("Load Power should be between 0-200 W")
self._load_mode = self.SET_TYPE_POWER
self._load_value = new_val
self.__set_parameters()
def set_load_current(self, current_amps):
"""
Changes load to current mode and sets current value.
Rounds to nearest mA.
:param current_amps: Current in Amps (0-30A)
:return: None
"""
new_val = int(round(current_amps * 1000))
if not 0 <= new_val <= 30000:
raise ValueError("Load Current should be between 0-30A")
self._load_mode = self.SET_TYPE_CURRENT
self._load_value = new_val
self.__set_parameters()
@property
def current(self):
"""
Current value (in Amps) obtained during last update_status call.
"""
return self._current / 1000
@property
def power(self):
"""
Power value (in Watts) obtained during last update_status call.
"""
return self._power / 10
@property
def resistance(self):
"""
Resistance value (in ohms) obtained during last update_status call.
"""
return self._resistance / 100
@property
def voltage(self):
"""
Voltage value (in Volts) obtained during last update_status call.
"""
return self._voltage / 1000
@property
def remote_control(self):
"""
Remote control enabled
"""
return self._remote_control == 1
@remote_control.setter
def remote_control(self, value):
new_val = 0
if value:
new_val = 1
if new_val != self._remote_control:
self._remote_control = new_val
self.__set_load_state()
@property
def load_on(self):
"""
Load enabled state
"""
return self._load_on == 1
@load_on.setter
def load_on(self, value):
new_val = 0
if value:
new_val = 1
if new_val != self._load_on:
self._load_on = new_val
self.__set_load_state()
def __set_buffer_start(self, command):
"""
This sets the first three bytes and clears the other 23 bytes.
:param command: Command Code to set
:return: None
"""
self.STRUCT_FRONT.pack_into(self.__out_buffer, self.OFFSET_FRONT, 0xAA, self.address, command)
@staticmethod
def __get_checksum(byte_str):
"""
Calculates checksum of string, excluding last character.
Checksum is generated by summing all byte values, except last,
and taking lowest byte of result.
:param byte_str: string to checksum, plus extra character on end
:return: checksum value as int
"""
return sum(byte2int(x) for x in byte_str[:-1]) % 256
def __set_checksum(self):
"""
Sets the checksum on the last byte of buffer,
based on values in the buffer
:return: None
"""
checksum = self.__get_checksum(self.__out_buffer.raw)
self.STRUCT_CHECKSUM.pack_into(self.__out_buffer, self.OFFSET_CHECKSUM, checksum)
def __is_valid_checksum(self, byte_str):
"""
Verifies last byte checksum of full packet
:param byte_str: byte string message
:return: boolean
"""
return byte2int(byte_str[-1]) == self.__get_checksum(byte_str)
def __clear_in_buffer(self):
"""
Zeros out the in buffer
:return: None
"""
self.__in_buffer.value = bytes(b'\0' * len(self.__in_buffer))
def __send_receive_buffer(self):
"""
Performs a send of self.__out_buffer and then an immediate read into self.__in_buffer
:return: None
"""
self.__clear_in_buffer()
self.__send_buffer()
read_string = self.serial.read(len(self.__in_buffer))
if self.DEBUG_MODE:
print("Read: '{}'".format(binascii.hexlify(read_string)))
if len(read_string) != len(self.__in_buffer):
raise IOError("{} bytes received for input buffer of size {}".format(len(read_string),
len(self.__in_buffer)))
if not self.__is_valid_checksum(read_string):
raise IOError("Checksum validation failed on received data")
self.__in_buffer.value = read_string
def __set_parameters(self):
"""
Sets Load Parameters from class values, including:
Max Current, Max Power, Address, Load Mode, Load Value
:return: None
"""
self.__set_buffer_start(self.CMD_SET_PARAMETERS)
# Can I send 0xFF as address to not change it each time?
# Worry about writing to EEPROM or Flash with each address change.
# Would then implement a separate address only change function.
self.STRUCT_SET_PARAMETERS.pack_into(self.__out_buffer, self.OFFSET_PAYLOAD,
self._max_current, self._max_power, self.address,
self._load_mode, self._load_value)
self.__set_checksum()
self.__send_buffer()
self.update_status()
def update_status(self, retry_count=2):
"""
Updates current values from load.
Must be called to get latest values for the following properties of class:
current
voltage
power
max current
max power
resistance
local_control
load_on
wrong_polarity
excessive_temp
excessive_voltage
excessive_power
:param retry_count: Number of times to ignore IOErrors and retry update
:return: None
"""
# I think retry should be in here.
# Throw exceptions in __update_status and handle here
cur_count = max(retry_count, 0)
while cur_count >= 0:
try:
self.__update_status()
except IOError as err:
if self.print_errors:
print("IOError: {}".format(err))
else:
if not self.__is_valid_checksum(self.__in_buffer.raw):
if self.print_errors:
raise IOError("Checksum validation failed.")
values = self.STRUCT_READ_VALUES_IN.unpack_from(self.__in_buffer, self.OFFSET_FRONT)
(self._current,
self._voltage,
self._power,
self._max_current,
self._max_power,
self._resistance,
output_state) = values[3:-1]
self._remote_control = (output_state & 0b00000001) > 0
self._load_on = (output_state & 0b00000010) > 0
self.wrong_polarity = (output_state & 0b00000100) > 0
self.excessive_temp = (output_state & 0b00001000) > 0
self.excessive_voltage = (output_state & 0b00010000) > 0
self.excessive_power = (output_state & 0b00100000) > 0
return None
cur_count -= 1
raise IOError("Retry count exceeded with serial IO.")
def __update_status(self):
self.__set_buffer_start(self.CMD_READ_VALUES)
self.STRUCT_READ_VALUES_OUT.pack_into(self.__out_buffer, 3)
self.__set_checksum()
self.__send_receive_buffer()
def __set_load_state(self):
# Remote Control is bit 2
flags = self._remote_control << 1
# Load On is bit 1
flags |= self._load_on
self.__set_buffer_start(self.CMD_LOAD_STATE)
self.STRUCT_LOAD_STATE.pack_into(self.__out_buffer, self.OFFSET_PAYLOAD, flags)
self.__set_checksum()
self.__send_buffer()
def set_program_sequence(self, array_program):
"""
Sets program up in load.
:param array_program: Populated Array3710Program object
:return: None
"""
self.__set_buffer_start(self.CMD_DEFINE_PROG_1_5)
array_program.load_buffer_one_to_five(self.__out_buffer)
self.__set_checksum()
self.__send_buffer()
self.__set_buffer_start(self.CMD_DEFINE_PROG_6_10)
array_program.load_buffer_six_to_ten(self.__out_buffer)
self.__set_checksum()
self.__send_buffer()
def start_program(self, turn_on_load=True):
"""
Starts running programmed test sequence
:return: None
"""
self.__set_buffer_start(self.CMD_START_PROG)
self.__set_checksum()
self.__send_buffer()
# Turn on Load if not on
if turn_on_load and not self.load_on:
self.load_on = True
def stop_program(self, turn_off_load=True):
"""
Stops running programmed test sequence
:return: None
"""
self.__set_buffer_start(self.CMD_STOP_PROG)
self.__set_checksum()
self.__send_buffer()
if turn_off_load and self.load_on:
self.load_on = False
|
sacherjj/array_devices
|
array_devices/array3710.py
|
Load.__send_receive_buffer
|
python
|
def __send_receive_buffer(self):
self.__clear_in_buffer()
self.__send_buffer()
read_string = self.serial.read(len(self.__in_buffer))
if self.DEBUG_MODE:
print("Read: '{}'".format(binascii.hexlify(read_string)))
if len(read_string) != len(self.__in_buffer):
raise IOError("{} bytes received for input buffer of size {}".format(len(read_string),
len(self.__in_buffer)))
if not self.__is_valid_checksum(read_string):
raise IOError("Checksum validation failed on received data")
self.__in_buffer.value = read_string
|
Performs a send of self.__out_buffer and then an immediate read into self.__in_buffer
:return: None
|
train
|
https://github.com/sacherjj/array_devices/blob/ba93a081e555321125ead33cf6fc5197569ef08f/array_devices/array3710.py#L471-L487
| null |
class Load(object):
"""
Handles remote control of Array 3710A DC Electronic Load.
Also sold under Gossen, Tekpower, Circuit Specialists with same 3710A model number.
"""
DEBUG_MODE = False
# Packet command values
CMD_SET_PARAMETERS = 0x90
CMD_READ_VALUES = 0x91
CMD_LOAD_STATE = 0x92
CMD_DEFINE_PROG_1_5 = 0x93
CMD_DEFINE_PROG_6_10 = 0x94
CMD_START_PROG = 0x95
CMD_STOP_PROG = 0x96
SET_TYPE_CURRENT = 0x01
SET_TYPE_POWER = 0x02
SET_TYPE_RESISTANCE = 0x03
FRAME_LENGTH = 26
# Description of data structures for various packet types
STRUCT_FRONT = struct.Struct(b'< 3B 23x')
STRUCT_SET_PARAMETERS = struct.Struct(b'< 2H 2B H 14x')
STRUCT_READ_VALUES_OUT = struct.Struct(b'< 22x')
STRUCT_READ_VALUES_IN = struct.Struct(b'< 3B H I 4H B 7x B')
STRUCT_LOAD_STATE = struct.Struct(b'< B 21x')
STRUCT_DEFINE_PROG_LOW = struct.Struct(b'< 2B 10H')
STRUCT_DEFINE_PROG_HIGH = struct.Struct(b'< 10H B x')
STRUCT_START_PROGRAM = struct.Struct(b'< 22x')
STRUCT_STOP_PROGRAM = struct.Struct(b'< 22x')
STRUCT_CHECKSUM = struct.Struct(b'< B')
# Offsets for packing partial structs
OFFSET_FRONT = 0
OFFSET_PAYLOAD = 3
OFFSET_CHECKSUM = 25
def __init__(self, address, serial_connection, print_errors=True):
"""
Require passing in serial_connection, because multiple Loads can exist
with different addresses on a single serial port.
:param address: Load address (0x00-0xFE)
:param serial_connection: Serial Connection from serial.Serial()
:return: None
"""
# Serial Comm Packets are all 26 byte frames.
# out_buffer for building data to send, in_buffer for consuming responses.
self.__out_buffer = ctypes.create_string_buffer(self.FRAME_LENGTH)
self.__in_buffer = ctypes.create_string_buffer(self.FRAME_LENGTH)
self.address = address
self.serial = serial_connection
self._max_current = 30000
self._max_power = 2000
self._load_mode = self.SET_TYPE_RESISTANCE
self._load_value = 500
self._current = 0
self._power = 0
self._voltage = 0
self._resistance = 0
self._remote_control = 0
self._load_on = 0
self.wrong_polarity = 0
self.excessive_temp = 0
self.excessive_voltage = 0
self.excessive_power = 0
self.print_errors = print_errors
self.update_status()
# Note: Internally, all values are stored as integer values
# in the format of the load interface.
#
# Ex: current is stored in mA, but public IO is Amps
# power is stored in tenths of Watts, but public IO is Watts.
#
# Conversion is done on getter and setter methods.
@property
def max_current(self):
"""
Max Current (in Amps) allowed to be set by load.
Rounds to nearest mA.
"""
return self._max_current / 1000
@max_current.setter
def max_current(self, current_amps):
new_val = int(round(current_amps * 1000, 0))
if not 0 <= new_val <= 30000:
raise ValueError("Max Current should be between 0-30A")
self._max_current = new_val
self.__set_parameters()
@property
def max_power(self):
"""
Max Power (in Watts) allowed to be set by load.
Rounds to nearest 0.1W
"""
return self._max_power / 10
@max_power.setter
def max_power(self, power_watts):
new_val = int(round(power_watts * 10, 0))
if not 0 <= new_val <= 2000:
raise ValueError("Max Power should be between 0-200W")
self._max_power = new_val
self.__set_parameters()
def set_load_resistance(self, resistance):
"""
Changes load to resistance mode and sets resistance value.
Rounds to nearest 0.01 Ohms
:param resistance: Load Resistance in Ohms (0-500 ohms)
:return: None
"""
new_val = int(round(resistance * 100))
if not 0 <= new_val <= 50000:
raise ValueError("Load Resistance should be between 0-500 ohms")
self._load_mode = self.SET_TYPE_RESISTANCE
self._load_value = new_val
self.__set_parameters()
def set_load_power(self, power_watts):
"""
Changes load to power mode and sets power value.
Rounds to nearest 0.1W.
:param power_watts: Power in Watts (0-200)
:return:
"""
new_val = int(round(power_watts * 10))
if not 0 <= new_val <= 2000:
raise ValueError("Load Power should be between 0-200 W")
self._load_mode = self.SET_TYPE_POWER
self._load_value = new_val
self.__set_parameters()
def set_load_current(self, current_amps):
"""
Changes load to current mode and sets current value.
Rounds to nearest mA.
:param current_amps: Current in Amps (0-30A)
:return: None
"""
new_val = int(round(current_amps * 1000))
if not 0 <= new_val <= 30000:
raise ValueError("Load Current should be between 0-30A")
self._load_mode = self.SET_TYPE_CURRENT
self._load_value = new_val
self.__set_parameters()
@property
def current(self):
"""
Current value (in Amps) obtained during last update_status call.
"""
return self._current / 1000
@property
def power(self):
"""
Power value (in Watts) obtained during last update_status call.
"""
return self._power / 10
@property
def resistance(self):
"""
Resistance value (in ohms) obtained during last update_status call.
"""
return self._resistance / 100
@property
def voltage(self):
"""
Voltage value (in Volts) obtained during last update_status call.
"""
return self._voltage / 1000
@property
def remote_control(self):
"""
Remote control enabled
"""
return self._remote_control == 1
@remote_control.setter
def remote_control(self, value):
new_val = 0
if value:
new_val = 1
if new_val != self._remote_control:
self._remote_control = new_val
self.__set_load_state()
@property
def load_on(self):
"""
Load enabled state
"""
return self._load_on == 1
@load_on.setter
def load_on(self, value):
new_val = 0
if value:
new_val = 1
if new_val != self._load_on:
self._load_on = new_val
self.__set_load_state()
def __set_buffer_start(self, command):
"""
This sets the first three bytes and clears the other 23 bytes.
:param command: Command Code to set
:return: None
"""
self.STRUCT_FRONT.pack_into(self.__out_buffer, self.OFFSET_FRONT, 0xAA, self.address, command)
@staticmethod
def __get_checksum(byte_str):
"""
Calculates checksum of string, excluding last character.
Checksum is generated by summing all byte values, except last,
and taking lowest byte of result.
:param byte_str: string to checksum, plus extra character on end
:return: checksum value as int
"""
return sum(byte2int(x) for x in byte_str[:-1]) % 256
def __set_checksum(self):
"""
Sets the checksum on the last byte of buffer,
based on values in the buffer
:return: None
"""
checksum = self.__get_checksum(self.__out_buffer.raw)
self.STRUCT_CHECKSUM.pack_into(self.__out_buffer, self.OFFSET_CHECKSUM, checksum)
def __is_valid_checksum(self, byte_str):
"""
Verifies last byte checksum of full packet
:param byte_str: byte string message
:return: boolean
"""
return byte2int(byte_str[-1]) == self.__get_checksum(byte_str)
def __clear_in_buffer(self):
"""
Zeros out the in buffer
:return: None
"""
self.__in_buffer.value = bytes(b'\0' * len(self.__in_buffer))
def __send_buffer(self):
"""
Sends the contents of self.__out_buffer to serial device
:return: Number of bytes written
"""
bytes_written = self.serial.write(self.__out_buffer.raw)
if self.DEBUG_MODE:
print("Wrote: '{}'".format(binascii.hexlify(self.__out_buffer.raw)))
if bytes_written != len(self.__out_buffer):
raise IOError("{} bytes written for output buffer of size {}".format(bytes_written,
len(self.__out_buffer)))
return bytes_written
def __set_parameters(self):
"""
Sets Load Parameters from class values, including:
Max Current, Max Power, Address, Load Mode, Load Value
:return: None
"""
self.__set_buffer_start(self.CMD_SET_PARAMETERS)
# Can I send 0xFF as address to not change it each time?
# Worry about writing to EEPROM or Flash with each address change.
# Would then implement a separate address only change function.
self.STRUCT_SET_PARAMETERS.pack_into(self.__out_buffer, self.OFFSET_PAYLOAD,
self._max_current, self._max_power, self.address,
self._load_mode, self._load_value)
self.__set_checksum()
self.__send_buffer()
self.update_status()
def update_status(self, retry_count=2):
"""
Updates current values from load.
Must be called to get latest values for the following properties of class:
current
voltage
power
max current
max power
resistance
local_control
load_on
wrong_polarity
excessive_temp
excessive_voltage
excessive_power
:param retry_count: Number of times to ignore IOErrors and retry update
:return: None
"""
# I think retry should be in here.
# Throw exceptions in __update_status and handle here
cur_count = max(retry_count, 0)
while cur_count >= 0:
try:
self.__update_status()
except IOError as err:
if self.print_errors:
print("IOError: {}".format(err))
else:
if not self.__is_valid_checksum(self.__in_buffer.raw):
if self.print_errors:
raise IOError("Checksum validation failed.")
values = self.STRUCT_READ_VALUES_IN.unpack_from(self.__in_buffer, self.OFFSET_FRONT)
(self._current,
self._voltage,
self._power,
self._max_current,
self._max_power,
self._resistance,
output_state) = values[3:-1]
self._remote_control = (output_state & 0b00000001) > 0
self._load_on = (output_state & 0b00000010) > 0
self.wrong_polarity = (output_state & 0b00000100) > 0
self.excessive_temp = (output_state & 0b00001000) > 0
self.excessive_voltage = (output_state & 0b00010000) > 0
self.excessive_power = (output_state & 0b00100000) > 0
return None
cur_count -= 1
raise IOError("Retry count exceeded with serial IO.")
def __update_status(self):
self.__set_buffer_start(self.CMD_READ_VALUES)
self.STRUCT_READ_VALUES_OUT.pack_into(self.__out_buffer, 3)
self.__set_checksum()
self.__send_receive_buffer()
def __set_load_state(self):
# Remote Control is bit 2
flags = self._remote_control << 1
# Load On is bit 1
flags |= self._load_on
self.__set_buffer_start(self.CMD_LOAD_STATE)
self.STRUCT_LOAD_STATE.pack_into(self.__out_buffer, self.OFFSET_PAYLOAD, flags)
self.__set_checksum()
self.__send_buffer()
def set_program_sequence(self, array_program):
"""
Sets program up in load.
:param array_program: Populated Array3710Program object
:return: None
"""
self.__set_buffer_start(self.CMD_DEFINE_PROG_1_5)
array_program.load_buffer_one_to_five(self.__out_buffer)
self.__set_checksum()
self.__send_buffer()
self.__set_buffer_start(self.CMD_DEFINE_PROG_6_10)
array_program.load_buffer_six_to_ten(self.__out_buffer)
self.__set_checksum()
self.__send_buffer()
def start_program(self, turn_on_load=True):
"""
Starts running programmed test sequence
:return: None
"""
self.__set_buffer_start(self.CMD_START_PROG)
self.__set_checksum()
self.__send_buffer()
# Turn on Load if not on
if turn_on_load and not self.load_on:
self.load_on = True
def stop_program(self, turn_off_load=True):
"""
Stops running programmed test sequence
:return: None
"""
self.__set_buffer_start(self.CMD_STOP_PROG)
self.__set_checksum()
self.__send_buffer()
if turn_off_load and self.load_on:
self.load_on = False
|
sacherjj/array_devices
|
array_devices/array3710.py
|
Load.__set_parameters
|
python
|
def __set_parameters(self):
self.__set_buffer_start(self.CMD_SET_PARAMETERS)
# Can I send 0xFF as address to not change it each time?
# Worry about writing to EEPROM or Flash with each address change.
# Would then implement a separate address only change function.
self.STRUCT_SET_PARAMETERS.pack_into(self.__out_buffer, self.OFFSET_PAYLOAD,
self._max_current, self._max_power, self.address,
self._load_mode, self._load_value)
self.__set_checksum()
self.__send_buffer()
self.update_status()
|
Sets Load Parameters from class values, including:
Max Current, Max Power, Address, Load Mode, Load Value
:return: None
|
train
|
https://github.com/sacherjj/array_devices/blob/ba93a081e555321125ead33cf6fc5197569ef08f/array_devices/array3710.py#L489-L505
| null |
class Load(object):
"""
Handles remote control of Array 3710A DC Electronic Load.
Also sold under Gossen, Tekpower, Circuit Specialists with same 3710A model number.
"""
DEBUG_MODE = False
# Packet command values
CMD_SET_PARAMETERS = 0x90
CMD_READ_VALUES = 0x91
CMD_LOAD_STATE = 0x92
CMD_DEFINE_PROG_1_5 = 0x93
CMD_DEFINE_PROG_6_10 = 0x94
CMD_START_PROG = 0x95
CMD_STOP_PROG = 0x96
SET_TYPE_CURRENT = 0x01
SET_TYPE_POWER = 0x02
SET_TYPE_RESISTANCE = 0x03
FRAME_LENGTH = 26
# Description of data structures for various packet types
STRUCT_FRONT = struct.Struct(b'< 3B 23x')
STRUCT_SET_PARAMETERS = struct.Struct(b'< 2H 2B H 14x')
STRUCT_READ_VALUES_OUT = struct.Struct(b'< 22x')
STRUCT_READ_VALUES_IN = struct.Struct(b'< 3B H I 4H B 7x B')
STRUCT_LOAD_STATE = struct.Struct(b'< B 21x')
STRUCT_DEFINE_PROG_LOW = struct.Struct(b'< 2B 10H')
STRUCT_DEFINE_PROG_HIGH = struct.Struct(b'< 10H B x')
STRUCT_START_PROGRAM = struct.Struct(b'< 22x')
STRUCT_STOP_PROGRAM = struct.Struct(b'< 22x')
STRUCT_CHECKSUM = struct.Struct(b'< B')
# Offsets for packing partial structs
OFFSET_FRONT = 0
OFFSET_PAYLOAD = 3
OFFSET_CHECKSUM = 25
def __init__(self, address, serial_connection, print_errors=True):
"""
Require passing in serial_connection, because multiple Loads can exist
with different addresses on a single serial port.
:param address: Load address (0x00-0xFE)
:param serial_connection: Serial Connection from serial.Serial()
:return: None
"""
# Serial Comm Packets are all 26 byte frames.
# out_buffer for building data to send, in_buffer for consuming responses.
self.__out_buffer = ctypes.create_string_buffer(self.FRAME_LENGTH)
self.__in_buffer = ctypes.create_string_buffer(self.FRAME_LENGTH)
self.address = address
self.serial = serial_connection
self._max_current = 30000
self._max_power = 2000
self._load_mode = self.SET_TYPE_RESISTANCE
self._load_value = 500
self._current = 0
self._power = 0
self._voltage = 0
self._resistance = 0
self._remote_control = 0
self._load_on = 0
self.wrong_polarity = 0
self.excessive_temp = 0
self.excessive_voltage = 0
self.excessive_power = 0
self.print_errors = print_errors
self.update_status()
# Note: Internally, all values are stored as integer values
# in the format of the load interface.
#
# Ex: current is stored in mA, but public IO is Amps
# power is stored in tenths of Watts, but public IO is Watts.
#
# Conversion is done on getter and setter methods.
@property
def max_current(self):
"""
Max Current (in Amps) allowed to be set by load.
Rounds to nearest mA.
"""
return self._max_current / 1000
@max_current.setter
def max_current(self, current_amps):
new_val = int(round(current_amps * 1000, 0))
if not 0 <= new_val <= 30000:
raise ValueError("Max Current should be between 0-30A")
self._max_current = new_val
self.__set_parameters()
@property
def max_power(self):
"""
Max Power (in Watts) allowed to be set by load.
Rounds to nearest 0.1W
"""
return self._max_power / 10
@max_power.setter
def max_power(self, power_watts):
new_val = int(round(power_watts * 10, 0))
if not 0 <= new_val <= 2000:
raise ValueError("Max Power should be between 0-200W")
self._max_power = new_val
self.__set_parameters()
def set_load_resistance(self, resistance):
"""
Changes load to resistance mode and sets resistance value.
Rounds to nearest 0.01 Ohms
:param resistance: Load Resistance in Ohms (0-500 ohms)
:return: None
"""
new_val = int(round(resistance * 100))
if not 0 <= new_val <= 50000:
raise ValueError("Load Resistance should be between 0-500 ohms")
self._load_mode = self.SET_TYPE_RESISTANCE
self._load_value = new_val
self.__set_parameters()
def set_load_power(self, power_watts):
"""
Changes load to power mode and sets power value.
Rounds to nearest 0.1W.
:param power_watts: Power in Watts (0-200)
:return:
"""
new_val = int(round(power_watts * 10))
if not 0 <= new_val <= 2000:
raise ValueError("Load Power should be between 0-200 W")
self._load_mode = self.SET_TYPE_POWER
self._load_value = new_val
self.__set_parameters()
def set_load_current(self, current_amps):
"""
Changes load to current mode and sets current value.
Rounds to nearest mA.
:param current_amps: Current in Amps (0-30A)
:return: None
"""
new_val = int(round(current_amps * 1000))
if not 0 <= new_val <= 30000:
raise ValueError("Load Current should be between 0-30A")
self._load_mode = self.SET_TYPE_CURRENT
self._load_value = new_val
self.__set_parameters()
@property
def current(self):
"""
Current value (in Amps) obtained during last update_status call.
"""
return self._current / 1000
@property
def power(self):
"""
Power value (in Watts) obtained during last update_status call.
"""
return self._power / 10
@property
def resistance(self):
"""
Resistance value (in ohms) obtained during last update_status call.
"""
return self._resistance / 100
@property
def voltage(self):
"""
Voltage value (in Volts) obtained during last update_status call.
"""
return self._voltage / 1000
@property
def remote_control(self):
"""
Remote control enabled
"""
return self._remote_control == 1
@remote_control.setter
def remote_control(self, value):
new_val = 0
if value:
new_val = 1
if new_val != self._remote_control:
self._remote_control = new_val
self.__set_load_state()
@property
def load_on(self):
"""
Load enabled state
"""
return self._load_on == 1
@load_on.setter
def load_on(self, value):
new_val = 0
if value:
new_val = 1
if new_val != self._load_on:
self._load_on = new_val
self.__set_load_state()
def __set_buffer_start(self, command):
"""
This sets the first three bytes and clears the other 23 bytes.
:param command: Command Code to set
:return: None
"""
self.STRUCT_FRONT.pack_into(self.__out_buffer, self.OFFSET_FRONT, 0xAA, self.address, command)
@staticmethod
def __get_checksum(byte_str):
"""
Calculates checksum of string, excluding last character.
Checksum is generated by summing all byte values, except last,
and taking lowest byte of result.
:param byte_str: string to checksum, plus extra character on end
:return: checksum value as int
"""
return sum(byte2int(x) for x in byte_str[:-1]) % 256
def __set_checksum(self):
"""
Sets the checksum on the last byte of buffer,
based on values in the buffer
:return: None
"""
checksum = self.__get_checksum(self.__out_buffer.raw)
self.STRUCT_CHECKSUM.pack_into(self.__out_buffer, self.OFFSET_CHECKSUM, checksum)
def __is_valid_checksum(self, byte_str):
"""
Verifies last byte checksum of full packet
:param byte_str: byte string message
:return: boolean
"""
return byte2int(byte_str[-1]) == self.__get_checksum(byte_str)
def __clear_in_buffer(self):
"""
Zeros out the in buffer
:return: None
"""
self.__in_buffer.value = bytes(b'\0' * len(self.__in_buffer))
def __send_buffer(self):
"""
Sends the contents of self.__out_buffer to serial device
:return: Number of bytes written
"""
bytes_written = self.serial.write(self.__out_buffer.raw)
if self.DEBUG_MODE:
print("Wrote: '{}'".format(binascii.hexlify(self.__out_buffer.raw)))
if bytes_written != len(self.__out_buffer):
raise IOError("{} bytes written for output buffer of size {}".format(bytes_written,
len(self.__out_buffer)))
return bytes_written
def __send_receive_buffer(self):
"""
Performs a send of self.__out_buffer and then an immediate read into self.__in_buffer
:return: None
"""
self.__clear_in_buffer()
self.__send_buffer()
read_string = self.serial.read(len(self.__in_buffer))
if self.DEBUG_MODE:
print("Read: '{}'".format(binascii.hexlify(read_string)))
if len(read_string) != len(self.__in_buffer):
raise IOError("{} bytes received for input buffer of size {}".format(len(read_string),
len(self.__in_buffer)))
if not self.__is_valid_checksum(read_string):
raise IOError("Checksum validation failed on received data")
self.__in_buffer.value = read_string
def update_status(self, retry_count=2):
"""
Updates current values from load.
Must be called to get latest values for the following properties of class:
current
voltage
power
max current
max power
resistance
local_control
load_on
wrong_polarity
excessive_temp
excessive_voltage
excessive_power
:param retry_count: Number of times to ignore IOErrors and retry update
:return: None
"""
# I think retry should be in here.
# Throw exceptions in __update_status and handle here
cur_count = max(retry_count, 0)
while cur_count >= 0:
try:
self.__update_status()
except IOError as err:
if self.print_errors:
print("IOError: {}".format(err))
else:
if not self.__is_valid_checksum(self.__in_buffer.raw):
if self.print_errors:
raise IOError("Checksum validation failed.")
values = self.STRUCT_READ_VALUES_IN.unpack_from(self.__in_buffer, self.OFFSET_FRONT)
(self._current,
self._voltage,
self._power,
self._max_current,
self._max_power,
self._resistance,
output_state) = values[3:-1]
self._remote_control = (output_state & 0b00000001) > 0
self._load_on = (output_state & 0b00000010) > 0
self.wrong_polarity = (output_state & 0b00000100) > 0
self.excessive_temp = (output_state & 0b00001000) > 0
self.excessive_voltage = (output_state & 0b00010000) > 0
self.excessive_power = (output_state & 0b00100000) > 0
return None
cur_count -= 1
raise IOError("Retry count exceeded with serial IO.")
def __update_status(self):
self.__set_buffer_start(self.CMD_READ_VALUES)
self.STRUCT_READ_VALUES_OUT.pack_into(self.__out_buffer, 3)
self.__set_checksum()
self.__send_receive_buffer()
def __set_load_state(self):
# Remote Control is bit 2
flags = self._remote_control << 1
# Load On is bit 1
flags |= self._load_on
self.__set_buffer_start(self.CMD_LOAD_STATE)
self.STRUCT_LOAD_STATE.pack_into(self.__out_buffer, self.OFFSET_PAYLOAD, flags)
self.__set_checksum()
self.__send_buffer()
def set_program_sequence(self, array_program):
"""
Sets program up in load.
:param array_program: Populated Array3710Program object
:return: None
"""
self.__set_buffer_start(self.CMD_DEFINE_PROG_1_5)
array_program.load_buffer_one_to_five(self.__out_buffer)
self.__set_checksum()
self.__send_buffer()
self.__set_buffer_start(self.CMD_DEFINE_PROG_6_10)
array_program.load_buffer_six_to_ten(self.__out_buffer)
self.__set_checksum()
self.__send_buffer()
def start_program(self, turn_on_load=True):
"""
Starts running programmed test sequence
:return: None
"""
self.__set_buffer_start(self.CMD_START_PROG)
self.__set_checksum()
self.__send_buffer()
# Turn on Load if not on
if turn_on_load and not self.load_on:
self.load_on = True
def stop_program(self, turn_off_load=True):
"""
Stops running programmed test sequence
:return: None
"""
self.__set_buffer_start(self.CMD_STOP_PROG)
self.__set_checksum()
self.__send_buffer()
if turn_off_load and self.load_on:
self.load_on = False
|
sacherjj/array_devices
|
array_devices/array3710.py
|
Load.update_status
|
python
|
def update_status(self, retry_count=2):
# I think retry should be in here.
# Throw exceptions in __update_status and handle here
cur_count = max(retry_count, 0)
while cur_count >= 0:
try:
self.__update_status()
except IOError as err:
if self.print_errors:
print("IOError: {}".format(err))
else:
if not self.__is_valid_checksum(self.__in_buffer.raw):
if self.print_errors:
raise IOError("Checksum validation failed.")
values = self.STRUCT_READ_VALUES_IN.unpack_from(self.__in_buffer, self.OFFSET_FRONT)
(self._current,
self._voltage,
self._power,
self._max_current,
self._max_power,
self._resistance,
output_state) = values[3:-1]
self._remote_control = (output_state & 0b00000001) > 0
self._load_on = (output_state & 0b00000010) > 0
self.wrong_polarity = (output_state & 0b00000100) > 0
self.excessive_temp = (output_state & 0b00001000) > 0
self.excessive_voltage = (output_state & 0b00010000) > 0
self.excessive_power = (output_state & 0b00100000) > 0
return None
cur_count -= 1
raise IOError("Retry count exceeded with serial IO.")
|
Updates current values from load.
Must be called to get latest values for the following properties of class:
current
voltage
power
max current
max power
resistance
local_control
load_on
wrong_polarity
excessive_temp
excessive_voltage
excessive_power
:param retry_count: Number of times to ignore IOErrors and retry update
:return: None
|
train
|
https://github.com/sacherjj/array_devices/blob/ba93a081e555321125ead33cf6fc5197569ef08f/array_devices/array3710.py#L507-L557
|
[
"def __is_valid_checksum(self, byte_str):\n \"\"\"\n Verifies last byte checksum of full packet\n :param byte_str: byte string message\n :return: boolean\n \"\"\"\n return byte2int(byte_str[-1]) == self.__get_checksum(byte_str)\n",
"def __update_status(self):\n self.__set_buffer_start(self.CMD_READ_VALUES)\n self.STRUCT_READ_VALUES_OUT.pack_into(self.__out_buffer, 3)\n self.__set_checksum()\n self.__send_receive_buffer()\n"
] |
class Load(object):
"""
Handles remote control of Array 3710A DC Electronic Load.
Also sold under Gossen, Tekpower, Circuit Specialists with same 3710A model number.
"""
DEBUG_MODE = False
# Packet command values
CMD_SET_PARAMETERS = 0x90
CMD_READ_VALUES = 0x91
CMD_LOAD_STATE = 0x92
CMD_DEFINE_PROG_1_5 = 0x93
CMD_DEFINE_PROG_6_10 = 0x94
CMD_START_PROG = 0x95
CMD_STOP_PROG = 0x96
SET_TYPE_CURRENT = 0x01
SET_TYPE_POWER = 0x02
SET_TYPE_RESISTANCE = 0x03
FRAME_LENGTH = 26
# Description of data structures for various packet types
STRUCT_FRONT = struct.Struct(b'< 3B 23x')
STRUCT_SET_PARAMETERS = struct.Struct(b'< 2H 2B H 14x')
STRUCT_READ_VALUES_OUT = struct.Struct(b'< 22x')
STRUCT_READ_VALUES_IN = struct.Struct(b'< 3B H I 4H B 7x B')
STRUCT_LOAD_STATE = struct.Struct(b'< B 21x')
STRUCT_DEFINE_PROG_LOW = struct.Struct(b'< 2B 10H')
STRUCT_DEFINE_PROG_HIGH = struct.Struct(b'< 10H B x')
STRUCT_START_PROGRAM = struct.Struct(b'< 22x')
STRUCT_STOP_PROGRAM = struct.Struct(b'< 22x')
STRUCT_CHECKSUM = struct.Struct(b'< B')
# Offsets for packing partial structs
OFFSET_FRONT = 0
OFFSET_PAYLOAD = 3
OFFSET_CHECKSUM = 25
def __init__(self, address, serial_connection, print_errors=True):
"""
Require passing in serial_connection, because multiple Loads can exist
with different addresses on a single serial port.
:param address: Load address (0x00-0xFE)
:param serial_connection: Serial Connection from serial.Serial()
:return: None
"""
# Serial Comm Packets are all 26 byte frames.
# out_buffer for building data to send, in_buffer for consuming responses.
self.__out_buffer = ctypes.create_string_buffer(self.FRAME_LENGTH)
self.__in_buffer = ctypes.create_string_buffer(self.FRAME_LENGTH)
self.address = address
self.serial = serial_connection
self._max_current = 30000
self._max_power = 2000
self._load_mode = self.SET_TYPE_RESISTANCE
self._load_value = 500
self._current = 0
self._power = 0
self._voltage = 0
self._resistance = 0
self._remote_control = 0
self._load_on = 0
self.wrong_polarity = 0
self.excessive_temp = 0
self.excessive_voltage = 0
self.excessive_power = 0
self.print_errors = print_errors
self.update_status()
# Note: Internally, all values are stored as integer values
# in the format of the load interface.
#
# Ex: current is stored in mA, but public IO is Amps
# power is stored in tenths of Watts, but public IO is Watts.
#
# Conversion is done on getter and setter methods.
@property
def max_current(self):
"""
Max Current (in Amps) allowed to be set by load.
Rounds to nearest mA.
"""
return self._max_current / 1000
@max_current.setter
def max_current(self, current_amps):
new_val = int(round(current_amps * 1000, 0))
if not 0 <= new_val <= 30000:
raise ValueError("Max Current should be between 0-30A")
self._max_current = new_val
self.__set_parameters()
@property
def max_power(self):
"""
Max Power (in Watts) allowed to be set by load.
Rounds to nearest 0.1W
"""
return self._max_power / 10
@max_power.setter
def max_power(self, power_watts):
new_val = int(round(power_watts * 10, 0))
if not 0 <= new_val <= 2000:
raise ValueError("Max Power should be between 0-200W")
self._max_power = new_val
self.__set_parameters()
def set_load_resistance(self, resistance):
"""
Changes load to resistance mode and sets resistance value.
Rounds to nearest 0.01 Ohms
:param resistance: Load Resistance in Ohms (0-500 ohms)
:return: None
"""
new_val = int(round(resistance * 100))
if not 0 <= new_val <= 50000:
raise ValueError("Load Resistance should be between 0-500 ohms")
self._load_mode = self.SET_TYPE_RESISTANCE
self._load_value = new_val
self.__set_parameters()
def set_load_power(self, power_watts):
"""
Changes load to power mode and sets power value.
Rounds to nearest 0.1W.
:param power_watts: Power in Watts (0-200)
:return:
"""
new_val = int(round(power_watts * 10))
if not 0 <= new_val <= 2000:
raise ValueError("Load Power should be between 0-200 W")
self._load_mode = self.SET_TYPE_POWER
self._load_value = new_val
self.__set_parameters()
def set_load_current(self, current_amps):
"""
Changes load to current mode and sets current value.
Rounds to nearest mA.
:param current_amps: Current in Amps (0-30A)
:return: None
"""
new_val = int(round(current_amps * 1000))
if not 0 <= new_val <= 30000:
raise ValueError("Load Current should be between 0-30A")
self._load_mode = self.SET_TYPE_CURRENT
self._load_value = new_val
self.__set_parameters()
@property
def current(self):
"""
Current value (in Amps) obtained during last update_status call.
"""
return self._current / 1000
@property
def power(self):
"""
Power value (in Watts) obtained during last update_status call.
"""
return self._power / 10
@property
def resistance(self):
"""
Resistance value (in ohms) obtained during last update_status call.
"""
return self._resistance / 100
@property
def voltage(self):
"""
Voltage value (in Volts) obtained during last update_status call.
"""
return self._voltage / 1000
@property
def remote_control(self):
"""
Remote control enabled
"""
return self._remote_control == 1
@remote_control.setter
def remote_control(self, value):
new_val = 0
if value:
new_val = 1
if new_val != self._remote_control:
self._remote_control = new_val
self.__set_load_state()
@property
def load_on(self):
"""
Load enabled state
"""
return self._load_on == 1
@load_on.setter
def load_on(self, value):
new_val = 0
if value:
new_val = 1
if new_val != self._load_on:
self._load_on = new_val
self.__set_load_state()
def __set_buffer_start(self, command):
"""
This sets the first three bytes and clears the other 23 bytes.
:param command: Command Code to set
:return: None
"""
self.STRUCT_FRONT.pack_into(self.__out_buffer, self.OFFSET_FRONT, 0xAA, self.address, command)
@staticmethod
def __get_checksum(byte_str):
"""
Calculates checksum of string, excluding last character.
Checksum is generated by summing all byte values, except last,
and taking lowest byte of result.
:param byte_str: string to checksum, plus extra character on end
:return: checksum value as int
"""
return sum(byte2int(x) for x in byte_str[:-1]) % 256
def __set_checksum(self):
"""
Sets the checksum on the last byte of buffer,
based on values in the buffer
:return: None
"""
checksum = self.__get_checksum(self.__out_buffer.raw)
self.STRUCT_CHECKSUM.pack_into(self.__out_buffer, self.OFFSET_CHECKSUM, checksum)
def __is_valid_checksum(self, byte_str):
"""
Verifies last byte checksum of full packet
:param byte_str: byte string message
:return: boolean
"""
return byte2int(byte_str[-1]) == self.__get_checksum(byte_str)
def __clear_in_buffer(self):
"""
Zeros out the in buffer
:return: None
"""
self.__in_buffer.value = bytes(b'\0' * len(self.__in_buffer))
def __send_buffer(self):
"""
Sends the contents of self.__out_buffer to serial device
:return: Number of bytes written
"""
bytes_written = self.serial.write(self.__out_buffer.raw)
if self.DEBUG_MODE:
print("Wrote: '{}'".format(binascii.hexlify(self.__out_buffer.raw)))
if bytes_written != len(self.__out_buffer):
raise IOError("{} bytes written for output buffer of size {}".format(bytes_written,
len(self.__out_buffer)))
return bytes_written
def __send_receive_buffer(self):
"""
Performs a send of self.__out_buffer and then an immediate read into self.__in_buffer
:return: None
"""
self.__clear_in_buffer()
self.__send_buffer()
read_string = self.serial.read(len(self.__in_buffer))
if self.DEBUG_MODE:
print("Read: '{}'".format(binascii.hexlify(read_string)))
if len(read_string) != len(self.__in_buffer):
raise IOError("{} bytes received for input buffer of size {}".format(len(read_string),
len(self.__in_buffer)))
if not self.__is_valid_checksum(read_string):
raise IOError("Checksum validation failed on received data")
self.__in_buffer.value = read_string
def __set_parameters(self):
"""
Sets Load Parameters from class values, including:
Max Current, Max Power, Address, Load Mode, Load Value
:return: None
"""
self.__set_buffer_start(self.CMD_SET_PARAMETERS)
# Can I send 0xFF as address to not change it each time?
# Worry about writing to EEPROM or Flash with each address change.
# Would then implement a separate address only change function.
self.STRUCT_SET_PARAMETERS.pack_into(self.__out_buffer, self.OFFSET_PAYLOAD,
self._max_current, self._max_power, self.address,
self._load_mode, self._load_value)
self.__set_checksum()
self.__send_buffer()
self.update_status()
def __update_status(self):
self.__set_buffer_start(self.CMD_READ_VALUES)
self.STRUCT_READ_VALUES_OUT.pack_into(self.__out_buffer, 3)
self.__set_checksum()
self.__send_receive_buffer()
def __set_load_state(self):
# Remote Control is bit 2
flags = self._remote_control << 1
# Load On is bit 1
flags |= self._load_on
self.__set_buffer_start(self.CMD_LOAD_STATE)
self.STRUCT_LOAD_STATE.pack_into(self.__out_buffer, self.OFFSET_PAYLOAD, flags)
self.__set_checksum()
self.__send_buffer()
def set_program_sequence(self, array_program):
"""
Sets program up in load.
:param array_program: Populated Array3710Program object
:return: None
"""
self.__set_buffer_start(self.CMD_DEFINE_PROG_1_5)
array_program.load_buffer_one_to_five(self.__out_buffer)
self.__set_checksum()
self.__send_buffer()
self.__set_buffer_start(self.CMD_DEFINE_PROG_6_10)
array_program.load_buffer_six_to_ten(self.__out_buffer)
self.__set_checksum()
self.__send_buffer()
def start_program(self, turn_on_load=True):
"""
Starts running programmed test sequence
:return: None
"""
self.__set_buffer_start(self.CMD_START_PROG)
self.__set_checksum()
self.__send_buffer()
# Turn on Load if not on
if turn_on_load and not self.load_on:
self.load_on = True
def stop_program(self, turn_off_load=True):
"""
Stops running programmed test sequence
:return: None
"""
self.__set_buffer_start(self.CMD_STOP_PROG)
self.__set_checksum()
self.__send_buffer()
if turn_off_load and self.load_on:
self.load_on = False
|
sacherjj/array_devices
|
array_devices/array3710.py
|
Load.set_program_sequence
|
python
|
def set_program_sequence(self, array_program):
self.__set_buffer_start(self.CMD_DEFINE_PROG_1_5)
array_program.load_buffer_one_to_five(self.__out_buffer)
self.__set_checksum()
self.__send_buffer()
self.__set_buffer_start(self.CMD_DEFINE_PROG_6_10)
array_program.load_buffer_six_to_ten(self.__out_buffer)
self.__set_checksum()
self.__send_buffer()
|
Sets program up in load.
:param array_program: Populated Array3710Program object
:return: None
|
train
|
https://github.com/sacherjj/array_devices/blob/ba93a081e555321125ead33cf6fc5197569ef08f/array_devices/array3710.py#L575-L589
|
[
"def load_buffer_one_to_five(self, out_buffer):\n \"\"\"\n Loads first program buffer (0x93) with everything but\n first three bytes and checksum\n \"\"\"\n struct.pack_into(b\"< 2B\", out_buffer, 3, self._program_type, len(self._prog_steps))\n offset = 5\n for ind, step in enumerate(self.partial_steps_data(0)):\n struct.pack_into(b\"< 2H\", out_buffer, offset + ind*4, step[0], step[1])\n",
"def load_buffer_six_to_ten(self, out_buffer):\n \"\"\"\n Loads second program buffer (0x94) with everything but\n first three bytes and checksum\n \"\"\"\n offset = 3\n for ind, step in enumerate(self.partial_steps_data(5)):\n struct.pack_into(b\"< 2H\", out_buffer, offset + ind*4, step[0], step[1])\n struct.pack_into(b\"< B x\", out_buffer, 23, self._program_mode)\n",
"def __set_buffer_start(self, command):\n \"\"\"\n This sets the first three bytes and clears the other 23 bytes.\n :param command: Command Code to set\n :return: None\n \"\"\"\n self.STRUCT_FRONT.pack_into(self.__out_buffer, self.OFFSET_FRONT, 0xAA, self.address, command)\n",
"def __set_checksum(self):\n \"\"\"\n Sets the checksum on the last byte of buffer,\n based on values in the buffer\n :return: None\n \"\"\"\n checksum = self.__get_checksum(self.__out_buffer.raw)\n self.STRUCT_CHECKSUM.pack_into(self.__out_buffer, self.OFFSET_CHECKSUM, checksum)\n",
"def __send_buffer(self):\n \"\"\"\n Sends the contents of self.__out_buffer to serial device\n :return: Number of bytes written\n \"\"\"\n bytes_written = self.serial.write(self.__out_buffer.raw)\n if self.DEBUG_MODE:\n print(\"Wrote: '{}'\".format(binascii.hexlify(self.__out_buffer.raw)))\n if bytes_written != len(self.__out_buffer):\n raise IOError(\"{} bytes written for output buffer of size {}\".format(bytes_written,\n len(self.__out_buffer)))\n return bytes_written\n"
] |
class Load(object):
"""
Handles remote control of Array 3710A DC Electronic Load.
Also sold under Gossen, Tekpower, Circuit Specialists with same 3710A model number.
"""
DEBUG_MODE = False
# Packet command values
CMD_SET_PARAMETERS = 0x90
CMD_READ_VALUES = 0x91
CMD_LOAD_STATE = 0x92
CMD_DEFINE_PROG_1_5 = 0x93
CMD_DEFINE_PROG_6_10 = 0x94
CMD_START_PROG = 0x95
CMD_STOP_PROG = 0x96
SET_TYPE_CURRENT = 0x01
SET_TYPE_POWER = 0x02
SET_TYPE_RESISTANCE = 0x03
FRAME_LENGTH = 26
# Description of data structures for various packet types
STRUCT_FRONT = struct.Struct(b'< 3B 23x')
STRUCT_SET_PARAMETERS = struct.Struct(b'< 2H 2B H 14x')
STRUCT_READ_VALUES_OUT = struct.Struct(b'< 22x')
STRUCT_READ_VALUES_IN = struct.Struct(b'< 3B H I 4H B 7x B')
STRUCT_LOAD_STATE = struct.Struct(b'< B 21x')
STRUCT_DEFINE_PROG_LOW = struct.Struct(b'< 2B 10H')
STRUCT_DEFINE_PROG_HIGH = struct.Struct(b'< 10H B x')
STRUCT_START_PROGRAM = struct.Struct(b'< 22x')
STRUCT_STOP_PROGRAM = struct.Struct(b'< 22x')
STRUCT_CHECKSUM = struct.Struct(b'< B')
# Offsets for packing partial structs
OFFSET_FRONT = 0
OFFSET_PAYLOAD = 3
OFFSET_CHECKSUM = 25
def __init__(self, address, serial_connection, print_errors=True):
"""
Require passing in serial_connection, because multiple Loads can exist
with different addresses on a single serial port.
:param address: Load address (0x00-0xFE)
:param serial_connection: Serial Connection from serial.Serial()
:return: None
"""
# Serial Comm Packets are all 26 byte frames.
# out_buffer for building data to send, in_buffer for consuming responses.
self.__out_buffer = ctypes.create_string_buffer(self.FRAME_LENGTH)
self.__in_buffer = ctypes.create_string_buffer(self.FRAME_LENGTH)
self.address = address
self.serial = serial_connection
self._max_current = 30000
self._max_power = 2000
self._load_mode = self.SET_TYPE_RESISTANCE
self._load_value = 500
self._current = 0
self._power = 0
self._voltage = 0
self._resistance = 0
self._remote_control = 0
self._load_on = 0
self.wrong_polarity = 0
self.excessive_temp = 0
self.excessive_voltage = 0
self.excessive_power = 0
self.print_errors = print_errors
self.update_status()
# Note: Internally, all values are stored as integer values
# in the format of the load interface.
#
# Ex: current is stored in mA, but public IO is Amps
# power is stored in tenths of Watts, but public IO is Watts.
#
# Conversion is done on getter and setter methods.
@property
def max_current(self):
"""
Max Current (in Amps) allowed to be set by load.
Rounds to nearest mA.
"""
return self._max_current / 1000
@max_current.setter
def max_current(self, current_amps):
new_val = int(round(current_amps * 1000, 0))
if not 0 <= new_val <= 30000:
raise ValueError("Max Current should be between 0-30A")
self._max_current = new_val
self.__set_parameters()
@property
def max_power(self):
"""
Max Power (in Watts) allowed to be set by load.
Rounds to nearest 0.1W
"""
return self._max_power / 10
@max_power.setter
def max_power(self, power_watts):
new_val = int(round(power_watts * 10, 0))
if not 0 <= new_val <= 2000:
raise ValueError("Max Power should be between 0-200W")
self._max_power = new_val
self.__set_parameters()
def set_load_resistance(self, resistance):
"""
Changes load to resistance mode and sets resistance value.
Rounds to nearest 0.01 Ohms
:param resistance: Load Resistance in Ohms (0-500 ohms)
:return: None
"""
new_val = int(round(resistance * 100))
if not 0 <= new_val <= 50000:
raise ValueError("Load Resistance should be between 0-500 ohms")
self._load_mode = self.SET_TYPE_RESISTANCE
self._load_value = new_val
self.__set_parameters()
def set_load_power(self, power_watts):
"""
Changes load to power mode and sets power value.
Rounds to nearest 0.1W.
:param power_watts: Power in Watts (0-200)
:return:
"""
new_val = int(round(power_watts * 10))
if not 0 <= new_val <= 2000:
raise ValueError("Load Power should be between 0-200 W")
self._load_mode = self.SET_TYPE_POWER
self._load_value = new_val
self.__set_parameters()
def set_load_current(self, current_amps):
"""
Changes load to current mode and sets current value.
Rounds to nearest mA.
:param current_amps: Current in Amps (0-30A)
:return: None
"""
new_val = int(round(current_amps * 1000))
if not 0 <= new_val <= 30000:
raise ValueError("Load Current should be between 0-30A")
self._load_mode = self.SET_TYPE_CURRENT
self._load_value = new_val
self.__set_parameters()
@property
def current(self):
"""
Current value (in Amps) obtained during last update_status call.
"""
return self._current / 1000
@property
def power(self):
"""
Power value (in Watts) obtained during last update_status call.
"""
return self._power / 10
@property
def resistance(self):
"""
Resistance value (in ohms) obtained during last update_status call.
"""
return self._resistance / 100
@property
def voltage(self):
"""
Voltage value (in Volts) obtained during last update_status call.
"""
return self._voltage / 1000
@property
def remote_control(self):
"""
Remote control enabled
"""
return self._remote_control == 1
@remote_control.setter
def remote_control(self, value):
new_val = 0
if value:
new_val = 1
if new_val != self._remote_control:
self._remote_control = new_val
self.__set_load_state()
@property
def load_on(self):
"""
Load enabled state
"""
return self._load_on == 1
@load_on.setter
def load_on(self, value):
new_val = 0
if value:
new_val = 1
if new_val != self._load_on:
self._load_on = new_val
self.__set_load_state()
def __set_buffer_start(self, command):
"""
This sets the first three bytes and clears the other 23 bytes.
:param command: Command Code to set
:return: None
"""
self.STRUCT_FRONT.pack_into(self.__out_buffer, self.OFFSET_FRONT, 0xAA, self.address, command)
@staticmethod
def __get_checksum(byte_str):
"""
Calculates checksum of string, excluding last character.
Checksum is generated by summing all byte values, except last,
and taking lowest byte of result.
:param byte_str: string to checksum, plus extra character on end
:return: checksum value as int
"""
return sum(byte2int(x) for x in byte_str[:-1]) % 256
def __set_checksum(self):
"""
Sets the checksum on the last byte of buffer,
based on values in the buffer
:return: None
"""
checksum = self.__get_checksum(self.__out_buffer.raw)
self.STRUCT_CHECKSUM.pack_into(self.__out_buffer, self.OFFSET_CHECKSUM, checksum)
def __is_valid_checksum(self, byte_str):
"""
Verifies last byte checksum of full packet
:param byte_str: byte string message
:return: boolean
"""
return byte2int(byte_str[-1]) == self.__get_checksum(byte_str)
def __clear_in_buffer(self):
"""
Zeros out the in buffer
:return: None
"""
self.__in_buffer.value = bytes(b'\0' * len(self.__in_buffer))
def __send_buffer(self):
"""
Sends the contents of self.__out_buffer to serial device
:return: Number of bytes written
"""
bytes_written = self.serial.write(self.__out_buffer.raw)
if self.DEBUG_MODE:
print("Wrote: '{}'".format(binascii.hexlify(self.__out_buffer.raw)))
if bytes_written != len(self.__out_buffer):
raise IOError("{} bytes written for output buffer of size {}".format(bytes_written,
len(self.__out_buffer)))
return bytes_written
def __send_receive_buffer(self):
"""
Performs a send of self.__out_buffer and then an immediate read into self.__in_buffer
:return: None
"""
self.__clear_in_buffer()
self.__send_buffer()
read_string = self.serial.read(len(self.__in_buffer))
if self.DEBUG_MODE:
print("Read: '{}'".format(binascii.hexlify(read_string)))
if len(read_string) != len(self.__in_buffer):
raise IOError("{} bytes received for input buffer of size {}".format(len(read_string),
len(self.__in_buffer)))
if not self.__is_valid_checksum(read_string):
raise IOError("Checksum validation failed on received data")
self.__in_buffer.value = read_string
def __set_parameters(self):
"""
Sets Load Parameters from class values, including:
Max Current, Max Power, Address, Load Mode, Load Value
:return: None
"""
self.__set_buffer_start(self.CMD_SET_PARAMETERS)
# Can I send 0xFF as address to not change it each time?
# Worry about writing to EEPROM or Flash with each address change.
# Would then implement a separate address only change function.
self.STRUCT_SET_PARAMETERS.pack_into(self.__out_buffer, self.OFFSET_PAYLOAD,
self._max_current, self._max_power, self.address,
self._load_mode, self._load_value)
self.__set_checksum()
self.__send_buffer()
self.update_status()
def update_status(self, retry_count=2):
"""
Updates current values from load.
Must be called to get latest values for the following properties of class:
current
voltage
power
max current
max power
resistance
local_control
load_on
wrong_polarity
excessive_temp
excessive_voltage
excessive_power
:param retry_count: Number of times to ignore IOErrors and retry update
:return: None
"""
# I think retry should be in here.
# Throw exceptions in __update_status and handle here
cur_count = max(retry_count, 0)
while cur_count >= 0:
try:
self.__update_status()
except IOError as err:
if self.print_errors:
print("IOError: {}".format(err))
else:
if not self.__is_valid_checksum(self.__in_buffer.raw):
if self.print_errors:
raise IOError("Checksum validation failed.")
values = self.STRUCT_READ_VALUES_IN.unpack_from(self.__in_buffer, self.OFFSET_FRONT)
(self._current,
self._voltage,
self._power,
self._max_current,
self._max_power,
self._resistance,
output_state) = values[3:-1]
self._remote_control = (output_state & 0b00000001) > 0
self._load_on = (output_state & 0b00000010) > 0
self.wrong_polarity = (output_state & 0b00000100) > 0
self.excessive_temp = (output_state & 0b00001000) > 0
self.excessive_voltage = (output_state & 0b00010000) > 0
self.excessive_power = (output_state & 0b00100000) > 0
return None
cur_count -= 1
raise IOError("Retry count exceeded with serial IO.")
def __update_status(self):
self.__set_buffer_start(self.CMD_READ_VALUES)
self.STRUCT_READ_VALUES_OUT.pack_into(self.__out_buffer, 3)
self.__set_checksum()
self.__send_receive_buffer()
def __set_load_state(self):
# Remote Control is bit 2
flags = self._remote_control << 1
# Load On is bit 1
flags |= self._load_on
self.__set_buffer_start(self.CMD_LOAD_STATE)
self.STRUCT_LOAD_STATE.pack_into(self.__out_buffer, self.OFFSET_PAYLOAD, flags)
self.__set_checksum()
self.__send_buffer()
def start_program(self, turn_on_load=True):
"""
Starts running programmed test sequence
:return: None
"""
self.__set_buffer_start(self.CMD_START_PROG)
self.__set_checksum()
self.__send_buffer()
# Turn on Load if not on
if turn_on_load and not self.load_on:
self.load_on = True
def stop_program(self, turn_off_load=True):
"""
Stops running programmed test sequence
:return: None
"""
self.__set_buffer_start(self.CMD_STOP_PROG)
self.__set_checksum()
self.__send_buffer()
if turn_off_load and self.load_on:
self.load_on = False
|
sacherjj/array_devices
|
array_devices/array3710.py
|
Load.start_program
|
python
|
def start_program(self, turn_on_load=True):
self.__set_buffer_start(self.CMD_START_PROG)
self.__set_checksum()
self.__send_buffer()
# Turn on Load if not on
if turn_on_load and not self.load_on:
self.load_on = True
|
Starts running programmed test sequence
:return: None
|
train
|
https://github.com/sacherjj/array_devices/blob/ba93a081e555321125ead33cf6fc5197569ef08f/array_devices/array3710.py#L591-L601
|
[
"def __set_buffer_start(self, command):\n \"\"\"\n This sets the first three bytes and clears the other 23 bytes.\n :param command: Command Code to set\n :return: None\n \"\"\"\n self.STRUCT_FRONT.pack_into(self.__out_buffer, self.OFFSET_FRONT, 0xAA, self.address, command)\n",
"def __set_checksum(self):\n \"\"\"\n Sets the checksum on the last byte of buffer,\n based on values in the buffer\n :return: None\n \"\"\"\n checksum = self.__get_checksum(self.__out_buffer.raw)\n self.STRUCT_CHECKSUM.pack_into(self.__out_buffer, self.OFFSET_CHECKSUM, checksum)\n",
"def __send_buffer(self):\n \"\"\"\n Sends the contents of self.__out_buffer to serial device\n :return: Number of bytes written\n \"\"\"\n bytes_written = self.serial.write(self.__out_buffer.raw)\n if self.DEBUG_MODE:\n print(\"Wrote: '{}'\".format(binascii.hexlify(self.__out_buffer.raw)))\n if bytes_written != len(self.__out_buffer):\n raise IOError(\"{} bytes written for output buffer of size {}\".format(bytes_written,\n len(self.__out_buffer)))\n return bytes_written\n"
] |
class Load(object):
"""
Handles remote control of Array 3710A DC Electronic Load.
Also sold under Gossen, Tekpower, Circuit Specialists with same 3710A model number.
"""
DEBUG_MODE = False
# Packet command values
CMD_SET_PARAMETERS = 0x90
CMD_READ_VALUES = 0x91
CMD_LOAD_STATE = 0x92
CMD_DEFINE_PROG_1_5 = 0x93
CMD_DEFINE_PROG_6_10 = 0x94
CMD_START_PROG = 0x95
CMD_STOP_PROG = 0x96
SET_TYPE_CURRENT = 0x01
SET_TYPE_POWER = 0x02
SET_TYPE_RESISTANCE = 0x03
FRAME_LENGTH = 26
# Description of data structures for various packet types
STRUCT_FRONT = struct.Struct(b'< 3B 23x')
STRUCT_SET_PARAMETERS = struct.Struct(b'< 2H 2B H 14x')
STRUCT_READ_VALUES_OUT = struct.Struct(b'< 22x')
STRUCT_READ_VALUES_IN = struct.Struct(b'< 3B H I 4H B 7x B')
STRUCT_LOAD_STATE = struct.Struct(b'< B 21x')
STRUCT_DEFINE_PROG_LOW = struct.Struct(b'< 2B 10H')
STRUCT_DEFINE_PROG_HIGH = struct.Struct(b'< 10H B x')
STRUCT_START_PROGRAM = struct.Struct(b'< 22x')
STRUCT_STOP_PROGRAM = struct.Struct(b'< 22x')
STRUCT_CHECKSUM = struct.Struct(b'< B')
# Offsets for packing partial structs
OFFSET_FRONT = 0
OFFSET_PAYLOAD = 3
OFFSET_CHECKSUM = 25
def __init__(self, address, serial_connection, print_errors=True):
"""
Require passing in serial_connection, because multiple Loads can exist
with different addresses on a single serial port.
:param address: Load address (0x00-0xFE)
:param serial_connection: Serial Connection from serial.Serial()
:return: None
"""
# Serial Comm Packets are all 26 byte frames.
# out_buffer for building data to send, in_buffer for consuming responses.
self.__out_buffer = ctypes.create_string_buffer(self.FRAME_LENGTH)
self.__in_buffer = ctypes.create_string_buffer(self.FRAME_LENGTH)
self.address = address
self.serial = serial_connection
self._max_current = 30000
self._max_power = 2000
self._load_mode = self.SET_TYPE_RESISTANCE
self._load_value = 500
self._current = 0
self._power = 0
self._voltage = 0
self._resistance = 0
self._remote_control = 0
self._load_on = 0
self.wrong_polarity = 0
self.excessive_temp = 0
self.excessive_voltage = 0
self.excessive_power = 0
self.print_errors = print_errors
self.update_status()
# Note: Internally, all values are stored as integer values
# in the format of the load interface.
#
# Ex: current is stored in mA, but public IO is Amps
# power is stored in tenths of Watts, but public IO is Watts.
#
# Conversion is done on getter and setter methods.
@property
def max_current(self):
"""
Max Current (in Amps) allowed to be set by load.
Rounds to nearest mA.
"""
return self._max_current / 1000
@max_current.setter
def max_current(self, current_amps):
new_val = int(round(current_amps * 1000, 0))
if not 0 <= new_val <= 30000:
raise ValueError("Max Current should be between 0-30A")
self._max_current = new_val
self.__set_parameters()
@property
def max_power(self):
"""
Max Power (in Watts) allowed to be set by load.
Rounds to nearest 0.1W
"""
return self._max_power / 10
@max_power.setter
def max_power(self, power_watts):
new_val = int(round(power_watts * 10, 0))
if not 0 <= new_val <= 2000:
raise ValueError("Max Power should be between 0-200W")
self._max_power = new_val
self.__set_parameters()
def set_load_resistance(self, resistance):
"""
Changes load to resistance mode and sets resistance value.
Rounds to nearest 0.01 Ohms
:param resistance: Load Resistance in Ohms (0-500 ohms)
:return: None
"""
new_val = int(round(resistance * 100))
if not 0 <= new_val <= 50000:
raise ValueError("Load Resistance should be between 0-500 ohms")
self._load_mode = self.SET_TYPE_RESISTANCE
self._load_value = new_val
self.__set_parameters()
def set_load_power(self, power_watts):
"""
Changes load to power mode and sets power value.
Rounds to nearest 0.1W.
:param power_watts: Power in Watts (0-200)
:return:
"""
new_val = int(round(power_watts * 10))
if not 0 <= new_val <= 2000:
raise ValueError("Load Power should be between 0-200 W")
self._load_mode = self.SET_TYPE_POWER
self._load_value = new_val
self.__set_parameters()
def set_load_current(self, current_amps):
"""
Changes load to current mode and sets current value.
Rounds to nearest mA.
:param current_amps: Current in Amps (0-30A)
:return: None
"""
new_val = int(round(current_amps * 1000))
if not 0 <= new_val <= 30000:
raise ValueError("Load Current should be between 0-30A")
self._load_mode = self.SET_TYPE_CURRENT
self._load_value = new_val
self.__set_parameters()
@property
def current(self):
"""
Current value (in Amps) obtained during last update_status call.
"""
return self._current / 1000
@property
def power(self):
"""
Power value (in Watts) obtained during last update_status call.
"""
return self._power / 10
@property
def resistance(self):
"""
Resistance value (in ohms) obtained during last update_status call.
"""
return self._resistance / 100
@property
def voltage(self):
"""
Voltage value (in Volts) obtained during last update_status call.
"""
return self._voltage / 1000
@property
def remote_control(self):
"""
Remote control enabled
"""
return self._remote_control == 1
@remote_control.setter
def remote_control(self, value):
new_val = 0
if value:
new_val = 1
if new_val != self._remote_control:
self._remote_control = new_val
self.__set_load_state()
@property
def load_on(self):
"""
Load enabled state
"""
return self._load_on == 1
@load_on.setter
def load_on(self, value):
new_val = 0
if value:
new_val = 1
if new_val != self._load_on:
self._load_on = new_val
self.__set_load_state()
def __set_buffer_start(self, command):
"""
This sets the first three bytes and clears the other 23 bytes.
:param command: Command Code to set
:return: None
"""
self.STRUCT_FRONT.pack_into(self.__out_buffer, self.OFFSET_FRONT, 0xAA, self.address, command)
@staticmethod
def __get_checksum(byte_str):
"""
Calculates checksum of string, excluding last character.
Checksum is generated by summing all byte values, except last,
and taking lowest byte of result.
:param byte_str: string to checksum, plus extra character on end
:return: checksum value as int
"""
return sum(byte2int(x) for x in byte_str[:-1]) % 256
def __set_checksum(self):
"""
Sets the checksum on the last byte of buffer,
based on values in the buffer
:return: None
"""
checksum = self.__get_checksum(self.__out_buffer.raw)
self.STRUCT_CHECKSUM.pack_into(self.__out_buffer, self.OFFSET_CHECKSUM, checksum)
def __is_valid_checksum(self, byte_str):
"""
Verifies last byte checksum of full packet
:param byte_str: byte string message
:return: boolean
"""
return byte2int(byte_str[-1]) == self.__get_checksum(byte_str)
def __clear_in_buffer(self):
"""
Zeros out the in buffer
:return: None
"""
self.__in_buffer.value = bytes(b'\0' * len(self.__in_buffer))
def __send_buffer(self):
"""
Sends the contents of self.__out_buffer to serial device
:return: Number of bytes written
"""
bytes_written = self.serial.write(self.__out_buffer.raw)
if self.DEBUG_MODE:
print("Wrote: '{}'".format(binascii.hexlify(self.__out_buffer.raw)))
if bytes_written != len(self.__out_buffer):
raise IOError("{} bytes written for output buffer of size {}".format(bytes_written,
len(self.__out_buffer)))
return bytes_written
def __send_receive_buffer(self):
"""
Performs a send of self.__out_buffer and then an immediate read into self.__in_buffer
:return: None
"""
self.__clear_in_buffer()
self.__send_buffer()
read_string = self.serial.read(len(self.__in_buffer))
if self.DEBUG_MODE:
print("Read: '{}'".format(binascii.hexlify(read_string)))
if len(read_string) != len(self.__in_buffer):
raise IOError("{} bytes received for input buffer of size {}".format(len(read_string),
len(self.__in_buffer)))
if not self.__is_valid_checksum(read_string):
raise IOError("Checksum validation failed on received data")
self.__in_buffer.value = read_string
def __set_parameters(self):
"""
Sets Load Parameters from class values, including:
Max Current, Max Power, Address, Load Mode, Load Value
:return: None
"""
self.__set_buffer_start(self.CMD_SET_PARAMETERS)
# Can I send 0xFF as address to not change it each time?
# Worry about writing to EEPROM or Flash with each address change.
# Would then implement a separate address only change function.
self.STRUCT_SET_PARAMETERS.pack_into(self.__out_buffer, self.OFFSET_PAYLOAD,
self._max_current, self._max_power, self.address,
self._load_mode, self._load_value)
self.__set_checksum()
self.__send_buffer()
self.update_status()
def update_status(self, retry_count=2):
"""
Updates current values from load.
Must be called to get latest values for the following properties of class:
current
voltage
power
max current
max power
resistance
local_control
load_on
wrong_polarity
excessive_temp
excessive_voltage
excessive_power
:param retry_count: Number of times to ignore IOErrors and retry update
:return: None
"""
# I think retry should be in here.
# Throw exceptions in __update_status and handle here
cur_count = max(retry_count, 0)
while cur_count >= 0:
try:
self.__update_status()
except IOError as err:
if self.print_errors:
print("IOError: {}".format(err))
else:
if not self.__is_valid_checksum(self.__in_buffer.raw):
if self.print_errors:
raise IOError("Checksum validation failed.")
values = self.STRUCT_READ_VALUES_IN.unpack_from(self.__in_buffer, self.OFFSET_FRONT)
(self._current,
self._voltage,
self._power,
self._max_current,
self._max_power,
self._resistance,
output_state) = values[3:-1]
self._remote_control = (output_state & 0b00000001) > 0
self._load_on = (output_state & 0b00000010) > 0
self.wrong_polarity = (output_state & 0b00000100) > 0
self.excessive_temp = (output_state & 0b00001000) > 0
self.excessive_voltage = (output_state & 0b00010000) > 0
self.excessive_power = (output_state & 0b00100000) > 0
return None
cur_count -= 1
raise IOError("Retry count exceeded with serial IO.")
def __update_status(self):
self.__set_buffer_start(self.CMD_READ_VALUES)
self.STRUCT_READ_VALUES_OUT.pack_into(self.__out_buffer, 3)
self.__set_checksum()
self.__send_receive_buffer()
def __set_load_state(self):
# Remote Control is bit 2
flags = self._remote_control << 1
# Load On is bit 1
flags |= self._load_on
self.__set_buffer_start(self.CMD_LOAD_STATE)
self.STRUCT_LOAD_STATE.pack_into(self.__out_buffer, self.OFFSET_PAYLOAD, flags)
self.__set_checksum()
self.__send_buffer()
def set_program_sequence(self, array_program):
"""
Sets program up in load.
:param array_program: Populated Array3710Program object
:return: None
"""
self.__set_buffer_start(self.CMD_DEFINE_PROG_1_5)
array_program.load_buffer_one_to_five(self.__out_buffer)
self.__set_checksum()
self.__send_buffer()
self.__set_buffer_start(self.CMD_DEFINE_PROG_6_10)
array_program.load_buffer_six_to_ten(self.__out_buffer)
self.__set_checksum()
self.__send_buffer()
def stop_program(self, turn_off_load=True):
"""
Stops running programmed test sequence
:return: None
"""
self.__set_buffer_start(self.CMD_STOP_PROG)
self.__set_checksum()
self.__send_buffer()
if turn_off_load and self.load_on:
self.load_on = False
|
sacherjj/array_devices
|
array_devices/array3710.py
|
Load.stop_program
|
python
|
def stop_program(self, turn_off_load=True):
self.__set_buffer_start(self.CMD_STOP_PROG)
self.__set_checksum()
self.__send_buffer()
if turn_off_load and self.load_on:
self.load_on = False
|
Stops running programmed test sequence
:return: None
|
train
|
https://github.com/sacherjj/array_devices/blob/ba93a081e555321125ead33cf6fc5197569ef08f/array_devices/array3710.py#L603-L612
|
[
"def __set_buffer_start(self, command):\n \"\"\"\n This sets the first three bytes and clears the other 23 bytes.\n :param command: Command Code to set\n :return: None\n \"\"\"\n self.STRUCT_FRONT.pack_into(self.__out_buffer, self.OFFSET_FRONT, 0xAA, self.address, command)\n",
"def __set_checksum(self):\n \"\"\"\n Sets the checksum on the last byte of buffer,\n based on values in the buffer\n :return: None\n \"\"\"\n checksum = self.__get_checksum(self.__out_buffer.raw)\n self.STRUCT_CHECKSUM.pack_into(self.__out_buffer, self.OFFSET_CHECKSUM, checksum)\n",
"def __send_buffer(self):\n \"\"\"\n Sends the contents of self.__out_buffer to serial device\n :return: Number of bytes written\n \"\"\"\n bytes_written = self.serial.write(self.__out_buffer.raw)\n if self.DEBUG_MODE:\n print(\"Wrote: '{}'\".format(binascii.hexlify(self.__out_buffer.raw)))\n if bytes_written != len(self.__out_buffer):\n raise IOError(\"{} bytes written for output buffer of size {}\".format(bytes_written,\n len(self.__out_buffer)))\n return bytes_written\n"
] |
class Load(object):
"""
Handles remote control of Array 3710A DC Electronic Load.
Also sold under Gossen, Tekpower, Circuit Specialists with same 3710A model number.
"""
DEBUG_MODE = False
# Packet command values
CMD_SET_PARAMETERS = 0x90
CMD_READ_VALUES = 0x91
CMD_LOAD_STATE = 0x92
CMD_DEFINE_PROG_1_5 = 0x93
CMD_DEFINE_PROG_6_10 = 0x94
CMD_START_PROG = 0x95
CMD_STOP_PROG = 0x96
SET_TYPE_CURRENT = 0x01
SET_TYPE_POWER = 0x02
SET_TYPE_RESISTANCE = 0x03
FRAME_LENGTH = 26
# Description of data structures for various packet types
STRUCT_FRONT = struct.Struct(b'< 3B 23x')
STRUCT_SET_PARAMETERS = struct.Struct(b'< 2H 2B H 14x')
STRUCT_READ_VALUES_OUT = struct.Struct(b'< 22x')
STRUCT_READ_VALUES_IN = struct.Struct(b'< 3B H I 4H B 7x B')
STRUCT_LOAD_STATE = struct.Struct(b'< B 21x')
STRUCT_DEFINE_PROG_LOW = struct.Struct(b'< 2B 10H')
STRUCT_DEFINE_PROG_HIGH = struct.Struct(b'< 10H B x')
STRUCT_START_PROGRAM = struct.Struct(b'< 22x')
STRUCT_STOP_PROGRAM = struct.Struct(b'< 22x')
STRUCT_CHECKSUM = struct.Struct(b'< B')
# Offsets for packing partial structs
OFFSET_FRONT = 0
OFFSET_PAYLOAD = 3
OFFSET_CHECKSUM = 25
def __init__(self, address, serial_connection, print_errors=True):
"""
Require passing in serial_connection, because multiple Loads can exist
with different addresses on a single serial port.
:param address: Load address (0x00-0xFE)
:param serial_connection: Serial Connection from serial.Serial()
:return: None
"""
# Serial Comm Packets are all 26 byte frames.
# out_buffer for building data to send, in_buffer for consuming responses.
self.__out_buffer = ctypes.create_string_buffer(self.FRAME_LENGTH)
self.__in_buffer = ctypes.create_string_buffer(self.FRAME_LENGTH)
self.address = address
self.serial = serial_connection
self._max_current = 30000
self._max_power = 2000
self._load_mode = self.SET_TYPE_RESISTANCE
self._load_value = 500
self._current = 0
self._power = 0
self._voltage = 0
self._resistance = 0
self._remote_control = 0
self._load_on = 0
self.wrong_polarity = 0
self.excessive_temp = 0
self.excessive_voltage = 0
self.excessive_power = 0
self.print_errors = print_errors
self.update_status()
# Note: Internally, all values are stored as integer values
# in the format of the load interface.
#
# Ex: current is stored in mA, but public IO is Amps
# power is stored in tenths of Watts, but public IO is Watts.
#
# Conversion is done on getter and setter methods.
@property
def max_current(self):
"""
Max Current (in Amps) allowed to be set by load.
Rounds to nearest mA.
"""
return self._max_current / 1000
@max_current.setter
def max_current(self, current_amps):
new_val = int(round(current_amps * 1000, 0))
if not 0 <= new_val <= 30000:
raise ValueError("Max Current should be between 0-30A")
self._max_current = new_val
self.__set_parameters()
@property
def max_power(self):
"""
Max Power (in Watts) allowed to be set by load.
Rounds to nearest 0.1W
"""
return self._max_power / 10
@max_power.setter
def max_power(self, power_watts):
new_val = int(round(power_watts * 10, 0))
if not 0 <= new_val <= 2000:
raise ValueError("Max Power should be between 0-200W")
self._max_power = new_val
self.__set_parameters()
def set_load_resistance(self, resistance):
"""
Changes load to resistance mode and sets resistance value.
Rounds to nearest 0.01 Ohms
:param resistance: Load Resistance in Ohms (0-500 ohms)
:return: None
"""
new_val = int(round(resistance * 100))
if not 0 <= new_val <= 50000:
raise ValueError("Load Resistance should be between 0-500 ohms")
self._load_mode = self.SET_TYPE_RESISTANCE
self._load_value = new_val
self.__set_parameters()
def set_load_power(self, power_watts):
"""
Changes load to power mode and sets power value.
Rounds to nearest 0.1W.
:param power_watts: Power in Watts (0-200)
:return:
"""
new_val = int(round(power_watts * 10))
if not 0 <= new_val <= 2000:
raise ValueError("Load Power should be between 0-200 W")
self._load_mode = self.SET_TYPE_POWER
self._load_value = new_val
self.__set_parameters()
def set_load_current(self, current_amps):
"""
Changes load to current mode and sets current value.
Rounds to nearest mA.
:param current_amps: Current in Amps (0-30A)
:return: None
"""
new_val = int(round(current_amps * 1000))
if not 0 <= new_val <= 30000:
raise ValueError("Load Current should be between 0-30A")
self._load_mode = self.SET_TYPE_CURRENT
self._load_value = new_val
self.__set_parameters()
@property
def current(self):
"""
Current value (in Amps) obtained during last update_status call.
"""
return self._current / 1000
@property
def power(self):
"""
Power value (in Watts) obtained during last update_status call.
"""
return self._power / 10
@property
def resistance(self):
"""
Resistance value (in ohms) obtained during last update_status call.
"""
return self._resistance / 100
@property
def voltage(self):
"""
Voltage value (in Volts) obtained during last update_status call.
"""
return self._voltage / 1000
@property
def remote_control(self):
"""
Remote control enabled
"""
return self._remote_control == 1
@remote_control.setter
def remote_control(self, value):
new_val = 0
if value:
new_val = 1
if new_val != self._remote_control:
self._remote_control = new_val
self.__set_load_state()
@property
def load_on(self):
"""
Load enabled state
"""
return self._load_on == 1
@load_on.setter
def load_on(self, value):
new_val = 0
if value:
new_val = 1
if new_val != self._load_on:
self._load_on = new_val
self.__set_load_state()
def __set_buffer_start(self, command):
"""
This sets the first three bytes and clears the other 23 bytes.
:param command: Command Code to set
:return: None
"""
self.STRUCT_FRONT.pack_into(self.__out_buffer, self.OFFSET_FRONT, 0xAA, self.address, command)
@staticmethod
def __get_checksum(byte_str):
"""
Calculates checksum of string, excluding last character.
Checksum is generated by summing all byte values, except last,
and taking lowest byte of result.
:param byte_str: string to checksum, plus extra character on end
:return: checksum value as int
"""
return sum(byte2int(x) for x in byte_str[:-1]) % 256
def __set_checksum(self):
"""
Sets the checksum on the last byte of buffer,
based on values in the buffer
:return: None
"""
checksum = self.__get_checksum(self.__out_buffer.raw)
self.STRUCT_CHECKSUM.pack_into(self.__out_buffer, self.OFFSET_CHECKSUM, checksum)
def __is_valid_checksum(self, byte_str):
"""
Verifies last byte checksum of full packet
:param byte_str: byte string message
:return: boolean
"""
return byte2int(byte_str[-1]) == self.__get_checksum(byte_str)
def __clear_in_buffer(self):
"""
Zeros out the in buffer
:return: None
"""
self.__in_buffer.value = bytes(b'\0' * len(self.__in_buffer))
def __send_buffer(self):
"""
Sends the contents of self.__out_buffer to serial device
:return: Number of bytes written
"""
bytes_written = self.serial.write(self.__out_buffer.raw)
if self.DEBUG_MODE:
print("Wrote: '{}'".format(binascii.hexlify(self.__out_buffer.raw)))
if bytes_written != len(self.__out_buffer):
raise IOError("{} bytes written for output buffer of size {}".format(bytes_written,
len(self.__out_buffer)))
return bytes_written
def __send_receive_buffer(self):
"""
Performs a send of self.__out_buffer and then an immediate read into self.__in_buffer
:return: None
"""
self.__clear_in_buffer()
self.__send_buffer()
read_string = self.serial.read(len(self.__in_buffer))
if self.DEBUG_MODE:
print("Read: '{}'".format(binascii.hexlify(read_string)))
if len(read_string) != len(self.__in_buffer):
raise IOError("{} bytes received for input buffer of size {}".format(len(read_string),
len(self.__in_buffer)))
if not self.__is_valid_checksum(read_string):
raise IOError("Checksum validation failed on received data")
self.__in_buffer.value = read_string
def __set_parameters(self):
"""
Sets Load Parameters from class values, including:
Max Current, Max Power, Address, Load Mode, Load Value
:return: None
"""
self.__set_buffer_start(self.CMD_SET_PARAMETERS)
# Can I send 0xFF as address to not change it each time?
# Worry about writing to EEPROM or Flash with each address change.
# Would then implement a separate address only change function.
self.STRUCT_SET_PARAMETERS.pack_into(self.__out_buffer, self.OFFSET_PAYLOAD,
self._max_current, self._max_power, self.address,
self._load_mode, self._load_value)
self.__set_checksum()
self.__send_buffer()
self.update_status()
def update_status(self, retry_count=2):
"""
Updates current values from load.
Must be called to get latest values for the following properties of class:
current
voltage
power
max current
max power
resistance
local_control
load_on
wrong_polarity
excessive_temp
excessive_voltage
excessive_power
:param retry_count: Number of times to ignore IOErrors and retry update
:return: None
"""
# I think retry should be in here.
# Throw exceptions in __update_status and handle here
cur_count = max(retry_count, 0)
while cur_count >= 0:
try:
self.__update_status()
except IOError as err:
if self.print_errors:
print("IOError: {}".format(err))
else:
if not self.__is_valid_checksum(self.__in_buffer.raw):
if self.print_errors:
raise IOError("Checksum validation failed.")
values = self.STRUCT_READ_VALUES_IN.unpack_from(self.__in_buffer, self.OFFSET_FRONT)
(self._current,
self._voltage,
self._power,
self._max_current,
self._max_power,
self._resistance,
output_state) = values[3:-1]
self._remote_control = (output_state & 0b00000001) > 0
self._load_on = (output_state & 0b00000010) > 0
self.wrong_polarity = (output_state & 0b00000100) > 0
self.excessive_temp = (output_state & 0b00001000) > 0
self.excessive_voltage = (output_state & 0b00010000) > 0
self.excessive_power = (output_state & 0b00100000) > 0
return None
cur_count -= 1
raise IOError("Retry count exceeded with serial IO.")
def __update_status(self):
self.__set_buffer_start(self.CMD_READ_VALUES)
self.STRUCT_READ_VALUES_OUT.pack_into(self.__out_buffer, 3)
self.__set_checksum()
self.__send_receive_buffer()
def __set_load_state(self):
# Remote Control is bit 2
flags = self._remote_control << 1
# Load On is bit 1
flags |= self._load_on
self.__set_buffer_start(self.CMD_LOAD_STATE)
self.STRUCT_LOAD_STATE.pack_into(self.__out_buffer, self.OFFSET_PAYLOAD, flags)
self.__set_checksum()
self.__send_buffer()
def set_program_sequence(self, array_program):
"""
Sets program up in load.
:param array_program: Populated Array3710Program object
:return: None
"""
self.__set_buffer_start(self.CMD_DEFINE_PROG_1_5)
array_program.load_buffer_one_to_five(self.__out_buffer)
self.__set_checksum()
self.__send_buffer()
self.__set_buffer_start(self.CMD_DEFINE_PROG_6_10)
array_program.load_buffer_six_to_ten(self.__out_buffer)
self.__set_checksum()
self.__send_buffer()
def start_program(self, turn_on_load=True):
"""
Starts running programmed test sequence
:return: None
"""
self.__set_buffer_start(self.CMD_START_PROG)
self.__set_checksum()
self.__send_buffer()
# Turn on Load if not on
if turn_on_load and not self.load_on:
self.load_on = True
|
flowroute/txjason
|
txjason/handler.py
|
Handler.addToService
|
python
|
def addToService(self, service, namespace=None, seperator='.'):
if namespace is None:
namespace = []
if isinstance(namespace, basestring):
namespace = [namespace]
for n, m in inspect.getmembers(self, inspect.ismethod):
if hasattr(m, 'export_rpc'):
try:
name = seperator.join(namespace + m.export_rpc)
except TypeError:
name = seperator.join(namespace + [m.export_rpc])
service.add(m, name)
|
Add this Handler's exported methods to an RPC Service instance.
|
train
|
https://github.com/flowroute/txjason/blob/4865bd716847dcbab99acc69daa0c44ae3cc5b89/txjason/handler.py#L44-L59
| null |
class Handler(object):
"""
Define RPC methods in subclasses of Handler. @exportRPC decorator indicates
that a method should be exported. Call .addHandler on a subclass of txjason's
BaseClientFactory (e.g., netstring.JSONRPCServerFactory) and pass an instance
of a Handler subclass to expose the RPC methods via that factory.
Example:
class Example(handler.Handler):
# export the echo2 method as 'echo'
@handler.exportRPC('echo')
def echo2(self, param):
return param
# exported methods may return a deferred
@handler.exportRPC()
def deferred_echo(self, param):
return defer.succeed(param)
"""
|
flowroute/txjason
|
txjason/service.py
|
JSONRPCService.add
|
python
|
def add(self, f, name=None, types=None, required=None):
if name is None:
fname = f.__name__ # Register the function using its own name.
else:
fname = name
self.method_data[fname] = {'method': f}
if types is not None:
self.method_data[fname]['types'] = types
if required is not None:
self.method_data[fname]['required'] = required
|
Adds a new method to the jsonrpc service.
Arguments:
f -- the remote function
name -- name of the method in the jsonrpc service
types -- list or dictionary of the types of accepted arguments
required -- list of required keyword arguments
If name argument is not given, function's own name will be used.
Argument types must be a list if positional arguments are used or a
dictionary if keyword arguments are used in the method in question.
Argument required MUST be used only for methods requiring keyword
arguments, not for methods accepting positional arguments.
|
train
|
https://github.com/flowroute/txjason/blob/4865bd716847dcbab99acc69daa0c44ae3cc5b89/txjason/service.py#L108-L137
| null |
class JSONRPCService(object):
"""
The JSONRPCService class is a JSON-RPC
"""
def __init__(self, timeout=None, reactor=reactor):
self.method_data = {}
self.serve_exception = None
self.out_of_service_deferred = None
self.pending = set()
self.timeout = timeout
self.reactor = reactor
def stopServing(self, exception=None):
"""
Returns a deferred that will fire immediately if there are
no pending requests, otherwise when the last request is removed
from self.pending.
"""
if exception is None:
exception = ServiceUnavailableError
self.serve_exception = exception
if self.pending:
d = self.out_of_service_deferred = defer.Deferred()
return d
return defer.succeed(None)
def startServing(self):
self.serve_exception = None
self.out_of_service_deferred = None
def cancelPending(self):
pending = self.pending.copy()
for i in pending:
i.cancel()
@defer.inlineCallbacks
def call(self, jsondata):
"""
Calls jsonrpc service's method and returns its return value in a JSON
string or None if there is none.
Arguments:
jsondata -- remote method call in jsonrpc format
"""
result = yield self.call_py(jsondata)
if result is None:
defer.returnValue(None)
else:
defer.returnValue(json.dumps(result))
@defer.inlineCallbacks
def call_py(self, jsondata):
"""
Calls jsonrpc service's method and returns its return value in python
object format or None if there is none.
This method is same as call() except the return value is a python
object instead of JSON string. This method is mainly only useful for
debugging purposes.
"""
try:
try:
rdata = json.loads(jsondata)
except ValueError:
raise ParseError
except ParseError, e:
defer.returnValue(self._get_err(e))
return
# set some default values for error handling
request = self._get_default_vals()
try:
if isinstance(rdata, dict) and rdata:
# It's a single request.
self._fill_request(request, rdata)
respond = yield self._handle_request(request)
# Don't respond to notifications
if respond is None:
defer.returnValue(None)
else:
defer.returnValue(respond)
return
elif isinstance(rdata, list) and rdata:
# It's a batch.
requests = []
responds = []
for rdata_ in rdata:
# set some default values for error handling
request_ = self._get_default_vals()
try:
self._fill_request(request_, rdata_)
except InvalidRequestError, e:
err = self._get_err(e, request_['id'])
if err:
responds.append(err)
continue
except JSONRPCError, e:
err = self._get_err(e, request_['id'])
if err:
responds.append(err)
continue
requests.append(request_)
for request_ in requests:
try:
# TODO: We should use a deferred list so requests
# are processed in parallel
respond = yield self._handle_request(request_)
except JSONRPCError, e:
respond = self._get_err(e,
request_['id'],
request_['jsonrpc'])
# Don't respond to notifications
if respond is not None:
responds.append(respond)
if responds:
defer.returnValue(responds)
return
# Nothing to respond.
defer.returnValue(None)
return
else:
# empty dict, list or wrong type
raise InvalidRequestError
except InvalidRequestError, e:
defer.returnValue(self._get_err(e, request['id']))
except JSONRPCError, e:
defer.returnValue(self._get_err(e,
request['id'],
request['jsonrpc']))
def _get_err(self, e, id=None, jsonrpc=DEFAULT_JSONRPC):
"""
Returns jsonrpc error message.
"""
# Do not respond to notifications when the request is valid.
if not id \
and not isinstance(e, ParseError) \
and not isinstance(e, InvalidRequestError):
return None
respond = {'id': id}
if isinstance(jsonrpc, int):
# v1.0 requires result to exist always.
# No error codes are defined in v1.0 so only use the message.
if jsonrpc == 10:
respond['result'] = None
respond['error'] = e.dumps()['message']
else:
self._fill_ver(jsonrpc, respond)
respond['error'] = e.dumps()
else:
respond['jsonrpc'] = jsonrpc
respond['error'] = e.dumps()
return respond
def _fill_ver(self, iver, respond):
"""
Fills version information to the respond from the internal integer
version.
"""
if iver == 20:
respond['jsonrpc'] = '2.0'
if iver == 11:
respond['version'] = '1.1'
def _vargs(self, f):
"""
Returns True if given function accepts variadic positional arguments,
otherwise False.
"""
if f.func_code.co_flags & 4:
return True
return False
def _man_args(self, f):
"""
Returns number of mandatory arguments required by given function.
"""
argcount = f.func_code.co_argcount
# account for "self" getting passed to class instance methods
if isinstance(f, types.MethodType):
argcount -= 1
if f.func_defaults is None:
return argcount
return argcount - len(f.func_defaults)
def _max_args(self, f):
"""
Returns maximum number of arguments accepted by given function.
"""
if f.func_defaults is None:
return f.func_code.co_argcount
return f.func_code.co_argcount + len(f.func_defaults)
def _get_jsonrpc(self, rdata):
"""
Returns jsonrpc request's jsonrpc value.
InvalidRequestError will be raised if the jsonrpc value has invalid
value.
"""
if 'jsonrpc' in rdata:
if rdata['jsonrpc'] == '2.0':
return 20
else:
# invalid version
raise InvalidRequestError
else:
# It's probably a JSON-RPC v1.x style call.
if 'version' in rdata:
if rdata['version'] == '1.1':
return 11
# Assume v1.0.
return 10
def _get_id(self, rdata):
"""
Returns jsonrpc request's id value or None if there is none.
InvalidRequestError will be raised if the id value has invalid type.
"""
if 'id' in rdata:
if isinstance(rdata['id'], basestring) or \
isinstance(rdata['id'], int) or \
isinstance(rdata['id'], long) or \
isinstance(rdata['id'], float) or \
rdata['id'] is None:
return rdata['id']
else:
# invalid type
raise InvalidRequestError
else:
# It's a notification.
return None
def _get_method(self, rdata):
"""
Returns jsonrpc request's method value.
InvalidRequestError will be raised if it's missing or is wrong type.
MethodNotFoundError will be raised if a method with given method name
does not exist.
"""
if 'method' in rdata:
if not isinstance(rdata['method'], basestring):
raise InvalidRequestError
else:
raise InvalidRequestError
if rdata['method'] not in self.method_data.keys():
raise MethodNotFoundError
return rdata['method']
def _get_params(self, rdata):
"""
Returns a list of jsonrpc request's method parameters.
"""
if 'params' in rdata:
if isinstance(rdata['params'], dict) \
or isinstance(rdata['params'], list) \
or rdata['params'] is None:
return rdata['params']
else:
# wrong type
raise InvalidRequestError
else:
return None
def _fill_request(self, request, rdata):
"""Fills request with data from the jsonrpc call."""
if not isinstance(rdata, dict):
raise InvalidRequestError
request['jsonrpc'] = self._get_jsonrpc(rdata)
request['id'] = self._get_id(rdata)
request['method'] = self._get_method(rdata)
request['params'] = self._get_params(rdata)
@defer.inlineCallbacks
def _call_method(self, request):
"""Calls given method with given params and returns it value."""
method = self.method_data[request['method']]['method']
params = request['params']
result = None
try:
if isinstance(params, list):
# Does it have enough arguments?
if len(params) < self._man_args(method):
raise InvalidParamsError('not enough arguments')
# Does it have too many arguments?
if not self._vargs(method) \
and len(params) > self._max_args(method):
raise InvalidParamsError('too many arguments')
result = yield defer.maybeDeferred(method, *params)
elif isinstance(params, dict):
# Do not accept keyword arguments if the jsonrpc version is
# not >=1.1.
if request['jsonrpc'] < 11:
raise KeywordError
result = yield defer.maybeDeferred(method, **params)
else: # No params
result = yield defer.maybeDeferred(method)
except JSONRPCError:
raise
except Exception:
# Exception was raised inside the method.
log.msg('Exception raised while invoking RPC method "{}".'.format(
request['method']))
log.err()
raise ServerError
defer.returnValue(result)
def _remove_pending(self, d):
self.pending.remove(d)
if self.out_of_service_deferred and not self.pending:
self.out_of_service_deferred.callback(None)
@defer.inlineCallbacks
def _handle_request(self, request):
"""Handles given request and returns its response."""
if 'types' in self.method_data[request['method']]:
self._validate_params_types(request['method'], request['params'])
if self.serve_exception:
raise self.serve_exception()
d = self._call_method(request)
self.pending.add(d)
if self.timeout:
timeout_deferred = self.reactor.callLater(self.timeout, d.cancel)
def completed(result):
if timeout_deferred.active():
# cancel the timeout_deferred if it has not been fired yet
# this is to prevent d's deferred chain from firing twice
# (and raising an exception).
timeout_deferred.cancel()
return result
d.addBoth(completed)
try:
result = yield d
except defer.CancelledError:
# The request was cancelled due to a timeout or by cancelPending
# having been called. We return a TimeoutError to the client.
self._remove_pending(d)
raise TimeoutError()
except Exception as e:
self._remove_pending(d)
raise e
self._remove_pending(d)
# Do not respond to notifications.
if request['id'] is None:
defer.returnValue(None)
respond = {}
self._fill_ver(request['jsonrpc'], respond)
respond['result'] = result
respond['id'] = request['id']
defer.returnValue(respond)
def _get_default_vals(self):
"""
Returns dictionary containing default jsonrpc request/responds values
for error handling purposes.
"""
return {"jsonrpc": DEFAULT_JSONRPC, "id": None}
def _validate_params_types(self, method, params):
"""
Validates request's parameter types.
"""
if isinstance(params, list):
if not isinstance(self.method_data[method]['types'], list):
raise InvalidParamsError(
'expected keyword params, not positional')
for param, type, posnum in zip(params,
self.method_data[method]['types'],
range(1, len(params)+1)):
if not (isinstance(param, type) or param is None):
raise InvalidParamsError(
'positional arg #{} is the wrong type'.format(posnum))
elif isinstance(params, dict):
if not isinstance(self.method_data[method]['types'], dict):
raise InvalidParamsError(
'expected positional params, not keyword')
if 'required' in self.method_data[method]:
for key in self.method_data[method]['required']:
if key not in params:
raise InvalidParamsError('missing key: %s' % key)
for key in params.keys():
if key not in self.method_data[method]['types'] or \
not (isinstance(params[key],
self.method_data[method]['types'][key])
or params[key] is None):
raise InvalidParamsError(
'arg "{}" is the wrong type'.format(key))
|
flowroute/txjason
|
txjason/service.py
|
JSONRPCService.stopServing
|
python
|
def stopServing(self, exception=None):
if exception is None:
exception = ServiceUnavailableError
self.serve_exception = exception
if self.pending:
d = self.out_of_service_deferred = defer.Deferred()
return d
return defer.succeed(None)
|
Returns a deferred that will fire immediately if there are
no pending requests, otherwise when the last request is removed
from self.pending.
|
train
|
https://github.com/flowroute/txjason/blob/4865bd716847dcbab99acc69daa0c44ae3cc5b89/txjason/service.py#L139-L151
| null |
class JSONRPCService(object):
"""
The JSONRPCService class is a JSON-RPC
"""
def __init__(self, timeout=None, reactor=reactor):
self.method_data = {}
self.serve_exception = None
self.out_of_service_deferred = None
self.pending = set()
self.timeout = timeout
self.reactor = reactor
def add(self, f, name=None, types=None, required=None):
"""
Adds a new method to the jsonrpc service.
Arguments:
f -- the remote function
name -- name of the method in the jsonrpc service
types -- list or dictionary of the types of accepted arguments
required -- list of required keyword arguments
If name argument is not given, function's own name will be used.
Argument types must be a list if positional arguments are used or a
dictionary if keyword arguments are used in the method in question.
Argument required MUST be used only for methods requiring keyword
arguments, not for methods accepting positional arguments.
"""
if name is None:
fname = f.__name__ # Register the function using its own name.
else:
fname = name
self.method_data[fname] = {'method': f}
if types is not None:
self.method_data[fname]['types'] = types
if required is not None:
self.method_data[fname]['required'] = required
def startServing(self):
self.serve_exception = None
self.out_of_service_deferred = None
def cancelPending(self):
pending = self.pending.copy()
for i in pending:
i.cancel()
@defer.inlineCallbacks
def call(self, jsondata):
"""
Calls jsonrpc service's method and returns its return value in a JSON
string or None if there is none.
Arguments:
jsondata -- remote method call in jsonrpc format
"""
result = yield self.call_py(jsondata)
if result is None:
defer.returnValue(None)
else:
defer.returnValue(json.dumps(result))
@defer.inlineCallbacks
def call_py(self, jsondata):
"""
Calls jsonrpc service's method and returns its return value in python
object format or None if there is none.
This method is same as call() except the return value is a python
object instead of JSON string. This method is mainly only useful for
debugging purposes.
"""
try:
try:
rdata = json.loads(jsondata)
except ValueError:
raise ParseError
except ParseError, e:
defer.returnValue(self._get_err(e))
return
# set some default values for error handling
request = self._get_default_vals()
try:
if isinstance(rdata, dict) and rdata:
# It's a single request.
self._fill_request(request, rdata)
respond = yield self._handle_request(request)
# Don't respond to notifications
if respond is None:
defer.returnValue(None)
else:
defer.returnValue(respond)
return
elif isinstance(rdata, list) and rdata:
# It's a batch.
requests = []
responds = []
for rdata_ in rdata:
# set some default values for error handling
request_ = self._get_default_vals()
try:
self._fill_request(request_, rdata_)
except InvalidRequestError, e:
err = self._get_err(e, request_['id'])
if err:
responds.append(err)
continue
except JSONRPCError, e:
err = self._get_err(e, request_['id'])
if err:
responds.append(err)
continue
requests.append(request_)
for request_ in requests:
try:
# TODO: We should use a deferred list so requests
# are processed in parallel
respond = yield self._handle_request(request_)
except JSONRPCError, e:
respond = self._get_err(e,
request_['id'],
request_['jsonrpc'])
# Don't respond to notifications
if respond is not None:
responds.append(respond)
if responds:
defer.returnValue(responds)
return
# Nothing to respond.
defer.returnValue(None)
return
else:
# empty dict, list or wrong type
raise InvalidRequestError
except InvalidRequestError, e:
defer.returnValue(self._get_err(e, request['id']))
except JSONRPCError, e:
defer.returnValue(self._get_err(e,
request['id'],
request['jsonrpc']))
def _get_err(self, e, id=None, jsonrpc=DEFAULT_JSONRPC):
"""
Returns jsonrpc error message.
"""
# Do not respond to notifications when the request is valid.
if not id \
and not isinstance(e, ParseError) \
and not isinstance(e, InvalidRequestError):
return None
respond = {'id': id}
if isinstance(jsonrpc, int):
# v1.0 requires result to exist always.
# No error codes are defined in v1.0 so only use the message.
if jsonrpc == 10:
respond['result'] = None
respond['error'] = e.dumps()['message']
else:
self._fill_ver(jsonrpc, respond)
respond['error'] = e.dumps()
else:
respond['jsonrpc'] = jsonrpc
respond['error'] = e.dumps()
return respond
def _fill_ver(self, iver, respond):
"""
Fills version information to the respond from the internal integer
version.
"""
if iver == 20:
respond['jsonrpc'] = '2.0'
if iver == 11:
respond['version'] = '1.1'
def _vargs(self, f):
"""
Returns True if given function accepts variadic positional arguments,
otherwise False.
"""
if f.func_code.co_flags & 4:
return True
return False
def _man_args(self, f):
"""
Returns number of mandatory arguments required by given function.
"""
argcount = f.func_code.co_argcount
# account for "self" getting passed to class instance methods
if isinstance(f, types.MethodType):
argcount -= 1
if f.func_defaults is None:
return argcount
return argcount - len(f.func_defaults)
def _max_args(self, f):
"""
Returns maximum number of arguments accepted by given function.
"""
if f.func_defaults is None:
return f.func_code.co_argcount
return f.func_code.co_argcount + len(f.func_defaults)
def _get_jsonrpc(self, rdata):
"""
Returns jsonrpc request's jsonrpc value.
InvalidRequestError will be raised if the jsonrpc value has invalid
value.
"""
if 'jsonrpc' in rdata:
if rdata['jsonrpc'] == '2.0':
return 20
else:
# invalid version
raise InvalidRequestError
else:
# It's probably a JSON-RPC v1.x style call.
if 'version' in rdata:
if rdata['version'] == '1.1':
return 11
# Assume v1.0.
return 10
def _get_id(self, rdata):
"""
Returns jsonrpc request's id value or None if there is none.
InvalidRequestError will be raised if the id value has invalid type.
"""
if 'id' in rdata:
if isinstance(rdata['id'], basestring) or \
isinstance(rdata['id'], int) or \
isinstance(rdata['id'], long) or \
isinstance(rdata['id'], float) or \
rdata['id'] is None:
return rdata['id']
else:
# invalid type
raise InvalidRequestError
else:
# It's a notification.
return None
def _get_method(self, rdata):
"""
Returns jsonrpc request's method value.
InvalidRequestError will be raised if it's missing or is wrong type.
MethodNotFoundError will be raised if a method with given method name
does not exist.
"""
if 'method' in rdata:
if not isinstance(rdata['method'], basestring):
raise InvalidRequestError
else:
raise InvalidRequestError
if rdata['method'] not in self.method_data.keys():
raise MethodNotFoundError
return rdata['method']
def _get_params(self, rdata):
"""
Returns a list of jsonrpc request's method parameters.
"""
if 'params' in rdata:
if isinstance(rdata['params'], dict) \
or isinstance(rdata['params'], list) \
or rdata['params'] is None:
return rdata['params']
else:
# wrong type
raise InvalidRequestError
else:
return None
def _fill_request(self, request, rdata):
"""Fills request with data from the jsonrpc call."""
if not isinstance(rdata, dict):
raise InvalidRequestError
request['jsonrpc'] = self._get_jsonrpc(rdata)
request['id'] = self._get_id(rdata)
request['method'] = self._get_method(rdata)
request['params'] = self._get_params(rdata)
@defer.inlineCallbacks
def _call_method(self, request):
"""Calls given method with given params and returns it value."""
method = self.method_data[request['method']]['method']
params = request['params']
result = None
try:
if isinstance(params, list):
# Does it have enough arguments?
if len(params) < self._man_args(method):
raise InvalidParamsError('not enough arguments')
# Does it have too many arguments?
if not self._vargs(method) \
and len(params) > self._max_args(method):
raise InvalidParamsError('too many arguments')
result = yield defer.maybeDeferred(method, *params)
elif isinstance(params, dict):
# Do not accept keyword arguments if the jsonrpc version is
# not >=1.1.
if request['jsonrpc'] < 11:
raise KeywordError
result = yield defer.maybeDeferred(method, **params)
else: # No params
result = yield defer.maybeDeferred(method)
except JSONRPCError:
raise
except Exception:
# Exception was raised inside the method.
log.msg('Exception raised while invoking RPC method "{}".'.format(
request['method']))
log.err()
raise ServerError
defer.returnValue(result)
def _remove_pending(self, d):
self.pending.remove(d)
if self.out_of_service_deferred and not self.pending:
self.out_of_service_deferred.callback(None)
@defer.inlineCallbacks
def _handle_request(self, request):
"""Handles given request and returns its response."""
if 'types' in self.method_data[request['method']]:
self._validate_params_types(request['method'], request['params'])
if self.serve_exception:
raise self.serve_exception()
d = self._call_method(request)
self.pending.add(d)
if self.timeout:
timeout_deferred = self.reactor.callLater(self.timeout, d.cancel)
def completed(result):
if timeout_deferred.active():
# cancel the timeout_deferred if it has not been fired yet
# this is to prevent d's deferred chain from firing twice
# (and raising an exception).
timeout_deferred.cancel()
return result
d.addBoth(completed)
try:
result = yield d
except defer.CancelledError:
# The request was cancelled due to a timeout or by cancelPending
# having been called. We return a TimeoutError to the client.
self._remove_pending(d)
raise TimeoutError()
except Exception as e:
self._remove_pending(d)
raise e
self._remove_pending(d)
# Do not respond to notifications.
if request['id'] is None:
defer.returnValue(None)
respond = {}
self._fill_ver(request['jsonrpc'], respond)
respond['result'] = result
respond['id'] = request['id']
defer.returnValue(respond)
def _get_default_vals(self):
"""
Returns dictionary containing default jsonrpc request/responds values
for error handling purposes.
"""
return {"jsonrpc": DEFAULT_JSONRPC, "id": None}
def _validate_params_types(self, method, params):
"""
Validates request's parameter types.
"""
if isinstance(params, list):
if not isinstance(self.method_data[method]['types'], list):
raise InvalidParamsError(
'expected keyword params, not positional')
for param, type, posnum in zip(params,
self.method_data[method]['types'],
range(1, len(params)+1)):
if not (isinstance(param, type) or param is None):
raise InvalidParamsError(
'positional arg #{} is the wrong type'.format(posnum))
elif isinstance(params, dict):
if not isinstance(self.method_data[method]['types'], dict):
raise InvalidParamsError(
'expected positional params, not keyword')
if 'required' in self.method_data[method]:
for key in self.method_data[method]['required']:
if key not in params:
raise InvalidParamsError('missing key: %s' % key)
for key in params.keys():
if key not in self.method_data[method]['types'] or \
not (isinstance(params[key],
self.method_data[method]['types'][key])
or params[key] is None):
raise InvalidParamsError(
'arg "{}" is the wrong type'.format(key))
|
flowroute/txjason
|
txjason/service.py
|
JSONRPCService.call
|
python
|
def call(self, jsondata):
result = yield self.call_py(jsondata)
if result is None:
defer.returnValue(None)
else:
defer.returnValue(json.dumps(result))
|
Calls jsonrpc service's method and returns its return value in a JSON
string or None if there is none.
Arguments:
jsondata -- remote method call in jsonrpc format
|
train
|
https://github.com/flowroute/txjason/blob/4865bd716847dcbab99acc69daa0c44ae3cc5b89/txjason/service.py#L163-L175
| null |
class JSONRPCService(object):
"""
The JSONRPCService class is a JSON-RPC
"""
def __init__(self, timeout=None, reactor=reactor):
self.method_data = {}
self.serve_exception = None
self.out_of_service_deferred = None
self.pending = set()
self.timeout = timeout
self.reactor = reactor
def add(self, f, name=None, types=None, required=None):
"""
Adds a new method to the jsonrpc service.
Arguments:
f -- the remote function
name -- name of the method in the jsonrpc service
types -- list or dictionary of the types of accepted arguments
required -- list of required keyword arguments
If name argument is not given, function's own name will be used.
Argument types must be a list if positional arguments are used or a
dictionary if keyword arguments are used in the method in question.
Argument required MUST be used only for methods requiring keyword
arguments, not for methods accepting positional arguments.
"""
if name is None:
fname = f.__name__ # Register the function using its own name.
else:
fname = name
self.method_data[fname] = {'method': f}
if types is not None:
self.method_data[fname]['types'] = types
if required is not None:
self.method_data[fname]['required'] = required
def stopServing(self, exception=None):
"""
Returns a deferred that will fire immediately if there are
no pending requests, otherwise when the last request is removed
from self.pending.
"""
if exception is None:
exception = ServiceUnavailableError
self.serve_exception = exception
if self.pending:
d = self.out_of_service_deferred = defer.Deferred()
return d
return defer.succeed(None)
def startServing(self):
self.serve_exception = None
self.out_of_service_deferred = None
def cancelPending(self):
pending = self.pending.copy()
for i in pending:
i.cancel()
@defer.inlineCallbacks
@defer.inlineCallbacks
def call_py(self, jsondata):
"""
Calls jsonrpc service's method and returns its return value in python
object format or None if there is none.
This method is same as call() except the return value is a python
object instead of JSON string. This method is mainly only useful for
debugging purposes.
"""
try:
try:
rdata = json.loads(jsondata)
except ValueError:
raise ParseError
except ParseError, e:
defer.returnValue(self._get_err(e))
return
# set some default values for error handling
request = self._get_default_vals()
try:
if isinstance(rdata, dict) and rdata:
# It's a single request.
self._fill_request(request, rdata)
respond = yield self._handle_request(request)
# Don't respond to notifications
if respond is None:
defer.returnValue(None)
else:
defer.returnValue(respond)
return
elif isinstance(rdata, list) and rdata:
# It's a batch.
requests = []
responds = []
for rdata_ in rdata:
# set some default values for error handling
request_ = self._get_default_vals()
try:
self._fill_request(request_, rdata_)
except InvalidRequestError, e:
err = self._get_err(e, request_['id'])
if err:
responds.append(err)
continue
except JSONRPCError, e:
err = self._get_err(e, request_['id'])
if err:
responds.append(err)
continue
requests.append(request_)
for request_ in requests:
try:
# TODO: We should use a deferred list so requests
# are processed in parallel
respond = yield self._handle_request(request_)
except JSONRPCError, e:
respond = self._get_err(e,
request_['id'],
request_['jsonrpc'])
# Don't respond to notifications
if respond is not None:
responds.append(respond)
if responds:
defer.returnValue(responds)
return
# Nothing to respond.
defer.returnValue(None)
return
else:
# empty dict, list or wrong type
raise InvalidRequestError
except InvalidRequestError, e:
defer.returnValue(self._get_err(e, request['id']))
except JSONRPCError, e:
defer.returnValue(self._get_err(e,
request['id'],
request['jsonrpc']))
def _get_err(self, e, id=None, jsonrpc=DEFAULT_JSONRPC):
"""
Returns jsonrpc error message.
"""
# Do not respond to notifications when the request is valid.
if not id \
and not isinstance(e, ParseError) \
and not isinstance(e, InvalidRequestError):
return None
respond = {'id': id}
if isinstance(jsonrpc, int):
# v1.0 requires result to exist always.
# No error codes are defined in v1.0 so only use the message.
if jsonrpc == 10:
respond['result'] = None
respond['error'] = e.dumps()['message']
else:
self._fill_ver(jsonrpc, respond)
respond['error'] = e.dumps()
else:
respond['jsonrpc'] = jsonrpc
respond['error'] = e.dumps()
return respond
def _fill_ver(self, iver, respond):
"""
Fills version information to the respond from the internal integer
version.
"""
if iver == 20:
respond['jsonrpc'] = '2.0'
if iver == 11:
respond['version'] = '1.1'
def _vargs(self, f):
"""
Returns True if given function accepts variadic positional arguments,
otherwise False.
"""
if f.func_code.co_flags & 4:
return True
return False
def _man_args(self, f):
"""
Returns number of mandatory arguments required by given function.
"""
argcount = f.func_code.co_argcount
# account for "self" getting passed to class instance methods
if isinstance(f, types.MethodType):
argcount -= 1
if f.func_defaults is None:
return argcount
return argcount - len(f.func_defaults)
def _max_args(self, f):
"""
Returns maximum number of arguments accepted by given function.
"""
if f.func_defaults is None:
return f.func_code.co_argcount
return f.func_code.co_argcount + len(f.func_defaults)
def _get_jsonrpc(self, rdata):
"""
Returns jsonrpc request's jsonrpc value.
InvalidRequestError will be raised if the jsonrpc value has invalid
value.
"""
if 'jsonrpc' in rdata:
if rdata['jsonrpc'] == '2.0':
return 20
else:
# invalid version
raise InvalidRequestError
else:
# It's probably a JSON-RPC v1.x style call.
if 'version' in rdata:
if rdata['version'] == '1.1':
return 11
# Assume v1.0.
return 10
def _get_id(self, rdata):
"""
Returns jsonrpc request's id value or None if there is none.
InvalidRequestError will be raised if the id value has invalid type.
"""
if 'id' in rdata:
if isinstance(rdata['id'], basestring) or \
isinstance(rdata['id'], int) or \
isinstance(rdata['id'], long) or \
isinstance(rdata['id'], float) or \
rdata['id'] is None:
return rdata['id']
else:
# invalid type
raise InvalidRequestError
else:
# It's a notification.
return None
def _get_method(self, rdata):
"""
Returns jsonrpc request's method value.
InvalidRequestError will be raised if it's missing or is wrong type.
MethodNotFoundError will be raised if a method with given method name
does not exist.
"""
if 'method' in rdata:
if not isinstance(rdata['method'], basestring):
raise InvalidRequestError
else:
raise InvalidRequestError
if rdata['method'] not in self.method_data.keys():
raise MethodNotFoundError
return rdata['method']
def _get_params(self, rdata):
"""
Returns a list of jsonrpc request's method parameters.
"""
if 'params' in rdata:
if isinstance(rdata['params'], dict) \
or isinstance(rdata['params'], list) \
or rdata['params'] is None:
return rdata['params']
else:
# wrong type
raise InvalidRequestError
else:
return None
def _fill_request(self, request, rdata):
"""Fills request with data from the jsonrpc call."""
if not isinstance(rdata, dict):
raise InvalidRequestError
request['jsonrpc'] = self._get_jsonrpc(rdata)
request['id'] = self._get_id(rdata)
request['method'] = self._get_method(rdata)
request['params'] = self._get_params(rdata)
@defer.inlineCallbacks
def _call_method(self, request):
"""Calls given method with given params and returns it value."""
method = self.method_data[request['method']]['method']
params = request['params']
result = None
try:
if isinstance(params, list):
# Does it have enough arguments?
if len(params) < self._man_args(method):
raise InvalidParamsError('not enough arguments')
# Does it have too many arguments?
if not self._vargs(method) \
and len(params) > self._max_args(method):
raise InvalidParamsError('too many arguments')
result = yield defer.maybeDeferred(method, *params)
elif isinstance(params, dict):
# Do not accept keyword arguments if the jsonrpc version is
# not >=1.1.
if request['jsonrpc'] < 11:
raise KeywordError
result = yield defer.maybeDeferred(method, **params)
else: # No params
result = yield defer.maybeDeferred(method)
except JSONRPCError:
raise
except Exception:
# Exception was raised inside the method.
log.msg('Exception raised while invoking RPC method "{}".'.format(
request['method']))
log.err()
raise ServerError
defer.returnValue(result)
def _remove_pending(self, d):
self.pending.remove(d)
if self.out_of_service_deferred and not self.pending:
self.out_of_service_deferred.callback(None)
@defer.inlineCallbacks
def _handle_request(self, request):
"""Handles given request and returns its response."""
if 'types' in self.method_data[request['method']]:
self._validate_params_types(request['method'], request['params'])
if self.serve_exception:
raise self.serve_exception()
d = self._call_method(request)
self.pending.add(d)
if self.timeout:
timeout_deferred = self.reactor.callLater(self.timeout, d.cancel)
def completed(result):
if timeout_deferred.active():
# cancel the timeout_deferred if it has not been fired yet
# this is to prevent d's deferred chain from firing twice
# (and raising an exception).
timeout_deferred.cancel()
return result
d.addBoth(completed)
try:
result = yield d
except defer.CancelledError:
# The request was cancelled due to a timeout or by cancelPending
# having been called. We return a TimeoutError to the client.
self._remove_pending(d)
raise TimeoutError()
except Exception as e:
self._remove_pending(d)
raise e
self._remove_pending(d)
# Do not respond to notifications.
if request['id'] is None:
defer.returnValue(None)
respond = {}
self._fill_ver(request['jsonrpc'], respond)
respond['result'] = result
respond['id'] = request['id']
defer.returnValue(respond)
def _get_default_vals(self):
"""
Returns dictionary containing default jsonrpc request/responds values
for error handling purposes.
"""
return {"jsonrpc": DEFAULT_JSONRPC, "id": None}
def _validate_params_types(self, method, params):
"""
Validates request's parameter types.
"""
if isinstance(params, list):
if not isinstance(self.method_data[method]['types'], list):
raise InvalidParamsError(
'expected keyword params, not positional')
for param, type, posnum in zip(params,
self.method_data[method]['types'],
range(1, len(params)+1)):
if not (isinstance(param, type) or param is None):
raise InvalidParamsError(
'positional arg #{} is the wrong type'.format(posnum))
elif isinstance(params, dict):
if not isinstance(self.method_data[method]['types'], dict):
raise InvalidParamsError(
'expected positional params, not keyword')
if 'required' in self.method_data[method]:
for key in self.method_data[method]['required']:
if key not in params:
raise InvalidParamsError('missing key: %s' % key)
for key in params.keys():
if key not in self.method_data[method]['types'] or \
not (isinstance(params[key],
self.method_data[method]['types'][key])
or params[key] is None):
raise InvalidParamsError(
'arg "{}" is the wrong type'.format(key))
|
flowroute/txjason
|
txjason/service.py
|
JSONRPCService.call_py
|
python
|
def call_py(self, jsondata):
try:
try:
rdata = json.loads(jsondata)
except ValueError:
raise ParseError
except ParseError, e:
defer.returnValue(self._get_err(e))
return
# set some default values for error handling
request = self._get_default_vals()
try:
if isinstance(rdata, dict) and rdata:
# It's a single request.
self._fill_request(request, rdata)
respond = yield self._handle_request(request)
# Don't respond to notifications
if respond is None:
defer.returnValue(None)
else:
defer.returnValue(respond)
return
elif isinstance(rdata, list) and rdata:
# It's a batch.
requests = []
responds = []
for rdata_ in rdata:
# set some default values for error handling
request_ = self._get_default_vals()
try:
self._fill_request(request_, rdata_)
except InvalidRequestError, e:
err = self._get_err(e, request_['id'])
if err:
responds.append(err)
continue
except JSONRPCError, e:
err = self._get_err(e, request_['id'])
if err:
responds.append(err)
continue
requests.append(request_)
for request_ in requests:
try:
# TODO: We should use a deferred list so requests
# are processed in parallel
respond = yield self._handle_request(request_)
except JSONRPCError, e:
respond = self._get_err(e,
request_['id'],
request_['jsonrpc'])
# Don't respond to notifications
if respond is not None:
responds.append(respond)
if responds:
defer.returnValue(responds)
return
# Nothing to respond.
defer.returnValue(None)
return
else:
# empty dict, list or wrong type
raise InvalidRequestError
except InvalidRequestError, e:
defer.returnValue(self._get_err(e, request['id']))
except JSONRPCError, e:
defer.returnValue(self._get_err(e,
request['id'],
request['jsonrpc']))
|
Calls jsonrpc service's method and returns its return value in python
object format or None if there is none.
This method is same as call() except the return value is a python
object instead of JSON string. This method is mainly only useful for
debugging purposes.
|
train
|
https://github.com/flowroute/txjason/blob/4865bd716847dcbab99acc69daa0c44ae3cc5b89/txjason/service.py#L178-L263
|
[
"def _get_err(self, e, id=None, jsonrpc=DEFAULT_JSONRPC):\n \"\"\"\n Returns jsonrpc error message.\n \"\"\"\n # Do not respond to notifications when the request is valid.\n if not id \\\n and not isinstance(e, ParseError) \\\n and not isinstance(e, InvalidRequestError):\n return None\n\n respond = {'id': id}\n\n if isinstance(jsonrpc, int):\n # v1.0 requires result to exist always.\n # No error codes are defined in v1.0 so only use the message.\n if jsonrpc == 10:\n respond['result'] = None\n respond['error'] = e.dumps()['message']\n else:\n self._fill_ver(jsonrpc, respond)\n respond['error'] = e.dumps()\n else:\n respond['jsonrpc'] = jsonrpc\n respond['error'] = e.dumps()\n\n return respond\n",
"def _get_default_vals(self):\n \"\"\"\n Returns dictionary containing default jsonrpc request/responds values\n for error handling purposes.\n \"\"\"\n return {\"jsonrpc\": DEFAULT_JSONRPC, \"id\": None}\n"
] |
class JSONRPCService(object):
"""
The JSONRPCService class is a JSON-RPC
"""
def __init__(self, timeout=None, reactor=reactor):
self.method_data = {}
self.serve_exception = None
self.out_of_service_deferred = None
self.pending = set()
self.timeout = timeout
self.reactor = reactor
def add(self, f, name=None, types=None, required=None):
"""
Adds a new method to the jsonrpc service.
Arguments:
f -- the remote function
name -- name of the method in the jsonrpc service
types -- list or dictionary of the types of accepted arguments
required -- list of required keyword arguments
If name argument is not given, function's own name will be used.
Argument types must be a list if positional arguments are used or a
dictionary if keyword arguments are used in the method in question.
Argument required MUST be used only for methods requiring keyword
arguments, not for methods accepting positional arguments.
"""
if name is None:
fname = f.__name__ # Register the function using its own name.
else:
fname = name
self.method_data[fname] = {'method': f}
if types is not None:
self.method_data[fname]['types'] = types
if required is not None:
self.method_data[fname]['required'] = required
def stopServing(self, exception=None):
"""
Returns a deferred that will fire immediately if there are
no pending requests, otherwise when the last request is removed
from self.pending.
"""
if exception is None:
exception = ServiceUnavailableError
self.serve_exception = exception
if self.pending:
d = self.out_of_service_deferred = defer.Deferred()
return d
return defer.succeed(None)
def startServing(self):
self.serve_exception = None
self.out_of_service_deferred = None
def cancelPending(self):
pending = self.pending.copy()
for i in pending:
i.cancel()
@defer.inlineCallbacks
def call(self, jsondata):
"""
Calls jsonrpc service's method and returns its return value in a JSON
string or None if there is none.
Arguments:
jsondata -- remote method call in jsonrpc format
"""
result = yield self.call_py(jsondata)
if result is None:
defer.returnValue(None)
else:
defer.returnValue(json.dumps(result))
@defer.inlineCallbacks
def _get_err(self, e, id=None, jsonrpc=DEFAULT_JSONRPC):
"""
Returns jsonrpc error message.
"""
# Do not respond to notifications when the request is valid.
if not id \
and not isinstance(e, ParseError) \
and not isinstance(e, InvalidRequestError):
return None
respond = {'id': id}
if isinstance(jsonrpc, int):
# v1.0 requires result to exist always.
# No error codes are defined in v1.0 so only use the message.
if jsonrpc == 10:
respond['result'] = None
respond['error'] = e.dumps()['message']
else:
self._fill_ver(jsonrpc, respond)
respond['error'] = e.dumps()
else:
respond['jsonrpc'] = jsonrpc
respond['error'] = e.dumps()
return respond
def _fill_ver(self, iver, respond):
"""
Fills version information to the respond from the internal integer
version.
"""
if iver == 20:
respond['jsonrpc'] = '2.0'
if iver == 11:
respond['version'] = '1.1'
def _vargs(self, f):
"""
Returns True if given function accepts variadic positional arguments,
otherwise False.
"""
if f.func_code.co_flags & 4:
return True
return False
def _man_args(self, f):
"""
Returns number of mandatory arguments required by given function.
"""
argcount = f.func_code.co_argcount
# account for "self" getting passed to class instance methods
if isinstance(f, types.MethodType):
argcount -= 1
if f.func_defaults is None:
return argcount
return argcount - len(f.func_defaults)
def _max_args(self, f):
"""
Returns maximum number of arguments accepted by given function.
"""
if f.func_defaults is None:
return f.func_code.co_argcount
return f.func_code.co_argcount + len(f.func_defaults)
def _get_jsonrpc(self, rdata):
"""
Returns jsonrpc request's jsonrpc value.
InvalidRequestError will be raised if the jsonrpc value has invalid
value.
"""
if 'jsonrpc' in rdata:
if rdata['jsonrpc'] == '2.0':
return 20
else:
# invalid version
raise InvalidRequestError
else:
# It's probably a JSON-RPC v1.x style call.
if 'version' in rdata:
if rdata['version'] == '1.1':
return 11
# Assume v1.0.
return 10
def _get_id(self, rdata):
"""
Returns jsonrpc request's id value or None if there is none.
InvalidRequestError will be raised if the id value has invalid type.
"""
if 'id' in rdata:
if isinstance(rdata['id'], basestring) or \
isinstance(rdata['id'], int) or \
isinstance(rdata['id'], long) or \
isinstance(rdata['id'], float) or \
rdata['id'] is None:
return rdata['id']
else:
# invalid type
raise InvalidRequestError
else:
# It's a notification.
return None
def _get_method(self, rdata):
"""
Returns jsonrpc request's method value.
InvalidRequestError will be raised if it's missing or is wrong type.
MethodNotFoundError will be raised if a method with given method name
does not exist.
"""
if 'method' in rdata:
if not isinstance(rdata['method'], basestring):
raise InvalidRequestError
else:
raise InvalidRequestError
if rdata['method'] not in self.method_data.keys():
raise MethodNotFoundError
return rdata['method']
def _get_params(self, rdata):
"""
Returns a list of jsonrpc request's method parameters.
"""
if 'params' in rdata:
if isinstance(rdata['params'], dict) \
or isinstance(rdata['params'], list) \
or rdata['params'] is None:
return rdata['params']
else:
# wrong type
raise InvalidRequestError
else:
return None
def _fill_request(self, request, rdata):
"""Fills request with data from the jsonrpc call."""
if not isinstance(rdata, dict):
raise InvalidRequestError
request['jsonrpc'] = self._get_jsonrpc(rdata)
request['id'] = self._get_id(rdata)
request['method'] = self._get_method(rdata)
request['params'] = self._get_params(rdata)
@defer.inlineCallbacks
def _call_method(self, request):
"""Calls given method with given params and returns it value."""
method = self.method_data[request['method']]['method']
params = request['params']
result = None
try:
if isinstance(params, list):
# Does it have enough arguments?
if len(params) < self._man_args(method):
raise InvalidParamsError('not enough arguments')
# Does it have too many arguments?
if not self._vargs(method) \
and len(params) > self._max_args(method):
raise InvalidParamsError('too many arguments')
result = yield defer.maybeDeferred(method, *params)
elif isinstance(params, dict):
# Do not accept keyword arguments if the jsonrpc version is
# not >=1.1.
if request['jsonrpc'] < 11:
raise KeywordError
result = yield defer.maybeDeferred(method, **params)
else: # No params
result = yield defer.maybeDeferred(method)
except JSONRPCError:
raise
except Exception:
# Exception was raised inside the method.
log.msg('Exception raised while invoking RPC method "{}".'.format(
request['method']))
log.err()
raise ServerError
defer.returnValue(result)
def _remove_pending(self, d):
self.pending.remove(d)
if self.out_of_service_deferred and not self.pending:
self.out_of_service_deferred.callback(None)
@defer.inlineCallbacks
def _handle_request(self, request):
"""Handles given request and returns its response."""
if 'types' in self.method_data[request['method']]:
self._validate_params_types(request['method'], request['params'])
if self.serve_exception:
raise self.serve_exception()
d = self._call_method(request)
self.pending.add(d)
if self.timeout:
timeout_deferred = self.reactor.callLater(self.timeout, d.cancel)
def completed(result):
if timeout_deferred.active():
# cancel the timeout_deferred if it has not been fired yet
# this is to prevent d's deferred chain from firing twice
# (and raising an exception).
timeout_deferred.cancel()
return result
d.addBoth(completed)
try:
result = yield d
except defer.CancelledError:
# The request was cancelled due to a timeout or by cancelPending
# having been called. We return a TimeoutError to the client.
self._remove_pending(d)
raise TimeoutError()
except Exception as e:
self._remove_pending(d)
raise e
self._remove_pending(d)
# Do not respond to notifications.
if request['id'] is None:
defer.returnValue(None)
respond = {}
self._fill_ver(request['jsonrpc'], respond)
respond['result'] = result
respond['id'] = request['id']
defer.returnValue(respond)
def _get_default_vals(self):
"""
Returns dictionary containing default jsonrpc request/responds values
for error handling purposes.
"""
return {"jsonrpc": DEFAULT_JSONRPC, "id": None}
def _validate_params_types(self, method, params):
"""
Validates request's parameter types.
"""
if isinstance(params, list):
if not isinstance(self.method_data[method]['types'], list):
raise InvalidParamsError(
'expected keyword params, not positional')
for param, type, posnum in zip(params,
self.method_data[method]['types'],
range(1, len(params)+1)):
if not (isinstance(param, type) or param is None):
raise InvalidParamsError(
'positional arg #{} is the wrong type'.format(posnum))
elif isinstance(params, dict):
if not isinstance(self.method_data[method]['types'], dict):
raise InvalidParamsError(
'expected positional params, not keyword')
if 'required' in self.method_data[method]:
for key in self.method_data[method]['required']:
if key not in params:
raise InvalidParamsError('missing key: %s' % key)
for key in params.keys():
if key not in self.method_data[method]['types'] or \
not (isinstance(params[key],
self.method_data[method]['types'][key])
or params[key] is None):
raise InvalidParamsError(
'arg "{}" is the wrong type'.format(key))
|
flowroute/txjason
|
txjason/service.py
|
JSONRPCService._get_err
|
python
|
def _get_err(self, e, id=None, jsonrpc=DEFAULT_JSONRPC):
# Do not respond to notifications when the request is valid.
if not id \
and not isinstance(e, ParseError) \
and not isinstance(e, InvalidRequestError):
return None
respond = {'id': id}
if isinstance(jsonrpc, int):
# v1.0 requires result to exist always.
# No error codes are defined in v1.0 so only use the message.
if jsonrpc == 10:
respond['result'] = None
respond['error'] = e.dumps()['message']
else:
self._fill_ver(jsonrpc, respond)
respond['error'] = e.dumps()
else:
respond['jsonrpc'] = jsonrpc
respond['error'] = e.dumps()
return respond
|
Returns jsonrpc error message.
|
train
|
https://github.com/flowroute/txjason/blob/4865bd716847dcbab99acc69daa0c44ae3cc5b89/txjason/service.py#L265-L290
|
[
"def _fill_ver(self, iver, respond):\n \"\"\"\n Fills version information to the respond from the internal integer\n version.\n \"\"\"\n if iver == 20:\n respond['jsonrpc'] = '2.0'\n if iver == 11:\n respond['version'] = '1.1'\n"
] |
class JSONRPCService(object):
"""
The JSONRPCService class is a JSON-RPC
"""
def __init__(self, timeout=None, reactor=reactor):
self.method_data = {}
self.serve_exception = None
self.out_of_service_deferred = None
self.pending = set()
self.timeout = timeout
self.reactor = reactor
def add(self, f, name=None, types=None, required=None):
"""
Adds a new method to the jsonrpc service.
Arguments:
f -- the remote function
name -- name of the method in the jsonrpc service
types -- list or dictionary of the types of accepted arguments
required -- list of required keyword arguments
If name argument is not given, function's own name will be used.
Argument types must be a list if positional arguments are used or a
dictionary if keyword arguments are used in the method in question.
Argument required MUST be used only for methods requiring keyword
arguments, not for methods accepting positional arguments.
"""
if name is None:
fname = f.__name__ # Register the function using its own name.
else:
fname = name
self.method_data[fname] = {'method': f}
if types is not None:
self.method_data[fname]['types'] = types
if required is not None:
self.method_data[fname]['required'] = required
def stopServing(self, exception=None):
"""
Returns a deferred that will fire immediately if there are
no pending requests, otherwise when the last request is removed
from self.pending.
"""
if exception is None:
exception = ServiceUnavailableError
self.serve_exception = exception
if self.pending:
d = self.out_of_service_deferred = defer.Deferred()
return d
return defer.succeed(None)
def startServing(self):
self.serve_exception = None
self.out_of_service_deferred = None
def cancelPending(self):
pending = self.pending.copy()
for i in pending:
i.cancel()
@defer.inlineCallbacks
def call(self, jsondata):
"""
Calls jsonrpc service's method and returns its return value in a JSON
string or None if there is none.
Arguments:
jsondata -- remote method call in jsonrpc format
"""
result = yield self.call_py(jsondata)
if result is None:
defer.returnValue(None)
else:
defer.returnValue(json.dumps(result))
@defer.inlineCallbacks
def call_py(self, jsondata):
"""
Calls jsonrpc service's method and returns its return value in python
object format or None if there is none.
This method is same as call() except the return value is a python
object instead of JSON string. This method is mainly only useful for
debugging purposes.
"""
try:
try:
rdata = json.loads(jsondata)
except ValueError:
raise ParseError
except ParseError, e:
defer.returnValue(self._get_err(e))
return
# set some default values for error handling
request = self._get_default_vals()
try:
if isinstance(rdata, dict) and rdata:
# It's a single request.
self._fill_request(request, rdata)
respond = yield self._handle_request(request)
# Don't respond to notifications
if respond is None:
defer.returnValue(None)
else:
defer.returnValue(respond)
return
elif isinstance(rdata, list) and rdata:
# It's a batch.
requests = []
responds = []
for rdata_ in rdata:
# set some default values for error handling
request_ = self._get_default_vals()
try:
self._fill_request(request_, rdata_)
except InvalidRequestError, e:
err = self._get_err(e, request_['id'])
if err:
responds.append(err)
continue
except JSONRPCError, e:
err = self._get_err(e, request_['id'])
if err:
responds.append(err)
continue
requests.append(request_)
for request_ in requests:
try:
# TODO: We should use a deferred list so requests
# are processed in parallel
respond = yield self._handle_request(request_)
except JSONRPCError, e:
respond = self._get_err(e,
request_['id'],
request_['jsonrpc'])
# Don't respond to notifications
if respond is not None:
responds.append(respond)
if responds:
defer.returnValue(responds)
return
# Nothing to respond.
defer.returnValue(None)
return
else:
# empty dict, list or wrong type
raise InvalidRequestError
except InvalidRequestError, e:
defer.returnValue(self._get_err(e, request['id']))
except JSONRPCError, e:
defer.returnValue(self._get_err(e,
request['id'],
request['jsonrpc']))
def _fill_ver(self, iver, respond):
"""
Fills version information to the respond from the internal integer
version.
"""
if iver == 20:
respond['jsonrpc'] = '2.0'
if iver == 11:
respond['version'] = '1.1'
def _vargs(self, f):
"""
Returns True if given function accepts variadic positional arguments,
otherwise False.
"""
if f.func_code.co_flags & 4:
return True
return False
def _man_args(self, f):
"""
Returns number of mandatory arguments required by given function.
"""
argcount = f.func_code.co_argcount
# account for "self" getting passed to class instance methods
if isinstance(f, types.MethodType):
argcount -= 1
if f.func_defaults is None:
return argcount
return argcount - len(f.func_defaults)
def _max_args(self, f):
"""
Returns maximum number of arguments accepted by given function.
"""
if f.func_defaults is None:
return f.func_code.co_argcount
return f.func_code.co_argcount + len(f.func_defaults)
def _get_jsonrpc(self, rdata):
"""
Returns jsonrpc request's jsonrpc value.
InvalidRequestError will be raised if the jsonrpc value has invalid
value.
"""
if 'jsonrpc' in rdata:
if rdata['jsonrpc'] == '2.0':
return 20
else:
# invalid version
raise InvalidRequestError
else:
# It's probably a JSON-RPC v1.x style call.
if 'version' in rdata:
if rdata['version'] == '1.1':
return 11
# Assume v1.0.
return 10
def _get_id(self, rdata):
"""
Returns jsonrpc request's id value or None if there is none.
InvalidRequestError will be raised if the id value has invalid type.
"""
if 'id' in rdata:
if isinstance(rdata['id'], basestring) or \
isinstance(rdata['id'], int) or \
isinstance(rdata['id'], long) or \
isinstance(rdata['id'], float) or \
rdata['id'] is None:
return rdata['id']
else:
# invalid type
raise InvalidRequestError
else:
# It's a notification.
return None
def _get_method(self, rdata):
"""
Returns jsonrpc request's method value.
InvalidRequestError will be raised if it's missing or is wrong type.
MethodNotFoundError will be raised if a method with given method name
does not exist.
"""
if 'method' in rdata:
if not isinstance(rdata['method'], basestring):
raise InvalidRequestError
else:
raise InvalidRequestError
if rdata['method'] not in self.method_data.keys():
raise MethodNotFoundError
return rdata['method']
def _get_params(self, rdata):
"""
Returns a list of jsonrpc request's method parameters.
"""
if 'params' in rdata:
if isinstance(rdata['params'], dict) \
or isinstance(rdata['params'], list) \
or rdata['params'] is None:
return rdata['params']
else:
# wrong type
raise InvalidRequestError
else:
return None
def _fill_request(self, request, rdata):
"""Fills request with data from the jsonrpc call."""
if not isinstance(rdata, dict):
raise InvalidRequestError
request['jsonrpc'] = self._get_jsonrpc(rdata)
request['id'] = self._get_id(rdata)
request['method'] = self._get_method(rdata)
request['params'] = self._get_params(rdata)
@defer.inlineCallbacks
def _call_method(self, request):
"""Calls given method with given params and returns it value."""
method = self.method_data[request['method']]['method']
params = request['params']
result = None
try:
if isinstance(params, list):
# Does it have enough arguments?
if len(params) < self._man_args(method):
raise InvalidParamsError('not enough arguments')
# Does it have too many arguments?
if not self._vargs(method) \
and len(params) > self._max_args(method):
raise InvalidParamsError('too many arguments')
result = yield defer.maybeDeferred(method, *params)
elif isinstance(params, dict):
# Do not accept keyword arguments if the jsonrpc version is
# not >=1.1.
if request['jsonrpc'] < 11:
raise KeywordError
result = yield defer.maybeDeferred(method, **params)
else: # No params
result = yield defer.maybeDeferred(method)
except JSONRPCError:
raise
except Exception:
# Exception was raised inside the method.
log.msg('Exception raised while invoking RPC method "{}".'.format(
request['method']))
log.err()
raise ServerError
defer.returnValue(result)
def _remove_pending(self, d):
self.pending.remove(d)
if self.out_of_service_deferred and not self.pending:
self.out_of_service_deferred.callback(None)
@defer.inlineCallbacks
def _handle_request(self, request):
"""Handles given request and returns its response."""
if 'types' in self.method_data[request['method']]:
self._validate_params_types(request['method'], request['params'])
if self.serve_exception:
raise self.serve_exception()
d = self._call_method(request)
self.pending.add(d)
if self.timeout:
timeout_deferred = self.reactor.callLater(self.timeout, d.cancel)
def completed(result):
if timeout_deferred.active():
# cancel the timeout_deferred if it has not been fired yet
# this is to prevent d's deferred chain from firing twice
# (and raising an exception).
timeout_deferred.cancel()
return result
d.addBoth(completed)
try:
result = yield d
except defer.CancelledError:
# The request was cancelled due to a timeout or by cancelPending
# having been called. We return a TimeoutError to the client.
self._remove_pending(d)
raise TimeoutError()
except Exception as e:
self._remove_pending(d)
raise e
self._remove_pending(d)
# Do not respond to notifications.
if request['id'] is None:
defer.returnValue(None)
respond = {}
self._fill_ver(request['jsonrpc'], respond)
respond['result'] = result
respond['id'] = request['id']
defer.returnValue(respond)
def _get_default_vals(self):
"""
Returns dictionary containing default jsonrpc request/responds values
for error handling purposes.
"""
return {"jsonrpc": DEFAULT_JSONRPC, "id": None}
def _validate_params_types(self, method, params):
"""
Validates request's parameter types.
"""
if isinstance(params, list):
if not isinstance(self.method_data[method]['types'], list):
raise InvalidParamsError(
'expected keyword params, not positional')
for param, type, posnum in zip(params,
self.method_data[method]['types'],
range(1, len(params)+1)):
if not (isinstance(param, type) or param is None):
raise InvalidParamsError(
'positional arg #{} is the wrong type'.format(posnum))
elif isinstance(params, dict):
if not isinstance(self.method_data[method]['types'], dict):
raise InvalidParamsError(
'expected positional params, not keyword')
if 'required' in self.method_data[method]:
for key in self.method_data[method]['required']:
if key not in params:
raise InvalidParamsError('missing key: %s' % key)
for key in params.keys():
if key not in self.method_data[method]['types'] or \
not (isinstance(params[key],
self.method_data[method]['types'][key])
or params[key] is None):
raise InvalidParamsError(
'arg "{}" is the wrong type'.format(key))
|
flowroute/txjason
|
txjason/service.py
|
JSONRPCService._man_args
|
python
|
def _man_args(self, f):
argcount = f.func_code.co_argcount
# account for "self" getting passed to class instance methods
if isinstance(f, types.MethodType):
argcount -= 1
if f.func_defaults is None:
return argcount
return argcount - len(f.func_defaults)
|
Returns number of mandatory arguments required by given function.
|
train
|
https://github.com/flowroute/txjason/blob/4865bd716847dcbab99acc69daa0c44ae3cc5b89/txjason/service.py#L312-L325
| null |
class JSONRPCService(object):
"""
The JSONRPCService class is a JSON-RPC
"""
def __init__(self, timeout=None, reactor=reactor):
self.method_data = {}
self.serve_exception = None
self.out_of_service_deferred = None
self.pending = set()
self.timeout = timeout
self.reactor = reactor
def add(self, f, name=None, types=None, required=None):
"""
Adds a new method to the jsonrpc service.
Arguments:
f -- the remote function
name -- name of the method in the jsonrpc service
types -- list or dictionary of the types of accepted arguments
required -- list of required keyword arguments
If name argument is not given, function's own name will be used.
Argument types must be a list if positional arguments are used or a
dictionary if keyword arguments are used in the method in question.
Argument required MUST be used only for methods requiring keyword
arguments, not for methods accepting positional arguments.
"""
if name is None:
fname = f.__name__ # Register the function using its own name.
else:
fname = name
self.method_data[fname] = {'method': f}
if types is not None:
self.method_data[fname]['types'] = types
if required is not None:
self.method_data[fname]['required'] = required
def stopServing(self, exception=None):
"""
Returns a deferred that will fire immediately if there are
no pending requests, otherwise when the last request is removed
from self.pending.
"""
if exception is None:
exception = ServiceUnavailableError
self.serve_exception = exception
if self.pending:
d = self.out_of_service_deferred = defer.Deferred()
return d
return defer.succeed(None)
def startServing(self):
self.serve_exception = None
self.out_of_service_deferred = None
def cancelPending(self):
pending = self.pending.copy()
for i in pending:
i.cancel()
@defer.inlineCallbacks
def call(self, jsondata):
"""
Calls jsonrpc service's method and returns its return value in a JSON
string or None if there is none.
Arguments:
jsondata -- remote method call in jsonrpc format
"""
result = yield self.call_py(jsondata)
if result is None:
defer.returnValue(None)
else:
defer.returnValue(json.dumps(result))
@defer.inlineCallbacks
def call_py(self, jsondata):
"""
Calls jsonrpc service's method and returns its return value in python
object format or None if there is none.
This method is same as call() except the return value is a python
object instead of JSON string. This method is mainly only useful for
debugging purposes.
"""
try:
try:
rdata = json.loads(jsondata)
except ValueError:
raise ParseError
except ParseError, e:
defer.returnValue(self._get_err(e))
return
# set some default values for error handling
request = self._get_default_vals()
try:
if isinstance(rdata, dict) and rdata:
# It's a single request.
self._fill_request(request, rdata)
respond = yield self._handle_request(request)
# Don't respond to notifications
if respond is None:
defer.returnValue(None)
else:
defer.returnValue(respond)
return
elif isinstance(rdata, list) and rdata:
# It's a batch.
requests = []
responds = []
for rdata_ in rdata:
# set some default values for error handling
request_ = self._get_default_vals()
try:
self._fill_request(request_, rdata_)
except InvalidRequestError, e:
err = self._get_err(e, request_['id'])
if err:
responds.append(err)
continue
except JSONRPCError, e:
err = self._get_err(e, request_['id'])
if err:
responds.append(err)
continue
requests.append(request_)
for request_ in requests:
try:
# TODO: We should use a deferred list so requests
# are processed in parallel
respond = yield self._handle_request(request_)
except JSONRPCError, e:
respond = self._get_err(e,
request_['id'],
request_['jsonrpc'])
# Don't respond to notifications
if respond is not None:
responds.append(respond)
if responds:
defer.returnValue(responds)
return
# Nothing to respond.
defer.returnValue(None)
return
else:
# empty dict, list or wrong type
raise InvalidRequestError
except InvalidRequestError, e:
defer.returnValue(self._get_err(e, request['id']))
except JSONRPCError, e:
defer.returnValue(self._get_err(e,
request['id'],
request['jsonrpc']))
def _get_err(self, e, id=None, jsonrpc=DEFAULT_JSONRPC):
"""
Returns jsonrpc error message.
"""
# Do not respond to notifications when the request is valid.
if not id \
and not isinstance(e, ParseError) \
and not isinstance(e, InvalidRequestError):
return None
respond = {'id': id}
if isinstance(jsonrpc, int):
# v1.0 requires result to exist always.
# No error codes are defined in v1.0 so only use the message.
if jsonrpc == 10:
respond['result'] = None
respond['error'] = e.dumps()['message']
else:
self._fill_ver(jsonrpc, respond)
respond['error'] = e.dumps()
else:
respond['jsonrpc'] = jsonrpc
respond['error'] = e.dumps()
return respond
def _fill_ver(self, iver, respond):
"""
Fills version information to the respond from the internal integer
version.
"""
if iver == 20:
respond['jsonrpc'] = '2.0'
if iver == 11:
respond['version'] = '1.1'
def _vargs(self, f):
"""
Returns True if given function accepts variadic positional arguments,
otherwise False.
"""
if f.func_code.co_flags & 4:
return True
return False
def _max_args(self, f):
"""
Returns maximum number of arguments accepted by given function.
"""
if f.func_defaults is None:
return f.func_code.co_argcount
return f.func_code.co_argcount + len(f.func_defaults)
def _get_jsonrpc(self, rdata):
"""
Returns jsonrpc request's jsonrpc value.
InvalidRequestError will be raised if the jsonrpc value has invalid
value.
"""
if 'jsonrpc' in rdata:
if rdata['jsonrpc'] == '2.0':
return 20
else:
# invalid version
raise InvalidRequestError
else:
# It's probably a JSON-RPC v1.x style call.
if 'version' in rdata:
if rdata['version'] == '1.1':
return 11
# Assume v1.0.
return 10
def _get_id(self, rdata):
"""
Returns jsonrpc request's id value or None if there is none.
InvalidRequestError will be raised if the id value has invalid type.
"""
if 'id' in rdata:
if isinstance(rdata['id'], basestring) or \
isinstance(rdata['id'], int) or \
isinstance(rdata['id'], long) or \
isinstance(rdata['id'], float) or \
rdata['id'] is None:
return rdata['id']
else:
# invalid type
raise InvalidRequestError
else:
# It's a notification.
return None
def _get_method(self, rdata):
"""
Returns jsonrpc request's method value.
InvalidRequestError will be raised if it's missing or is wrong type.
MethodNotFoundError will be raised if a method with given method name
does not exist.
"""
if 'method' in rdata:
if not isinstance(rdata['method'], basestring):
raise InvalidRequestError
else:
raise InvalidRequestError
if rdata['method'] not in self.method_data.keys():
raise MethodNotFoundError
return rdata['method']
def _get_params(self, rdata):
"""
Returns a list of jsonrpc request's method parameters.
"""
if 'params' in rdata:
if isinstance(rdata['params'], dict) \
or isinstance(rdata['params'], list) \
or rdata['params'] is None:
return rdata['params']
else:
# wrong type
raise InvalidRequestError
else:
return None
def _fill_request(self, request, rdata):
"""Fills request with data from the jsonrpc call."""
if not isinstance(rdata, dict):
raise InvalidRequestError
request['jsonrpc'] = self._get_jsonrpc(rdata)
request['id'] = self._get_id(rdata)
request['method'] = self._get_method(rdata)
request['params'] = self._get_params(rdata)
@defer.inlineCallbacks
def _call_method(self, request):
"""Calls given method with given params and returns it value."""
method = self.method_data[request['method']]['method']
params = request['params']
result = None
try:
if isinstance(params, list):
# Does it have enough arguments?
if len(params) < self._man_args(method):
raise InvalidParamsError('not enough arguments')
# Does it have too many arguments?
if not self._vargs(method) \
and len(params) > self._max_args(method):
raise InvalidParamsError('too many arguments')
result = yield defer.maybeDeferred(method, *params)
elif isinstance(params, dict):
# Do not accept keyword arguments if the jsonrpc version is
# not >=1.1.
if request['jsonrpc'] < 11:
raise KeywordError
result = yield defer.maybeDeferred(method, **params)
else: # No params
result = yield defer.maybeDeferred(method)
except JSONRPCError:
raise
except Exception:
# Exception was raised inside the method.
log.msg('Exception raised while invoking RPC method "{}".'.format(
request['method']))
log.err()
raise ServerError
defer.returnValue(result)
def _remove_pending(self, d):
self.pending.remove(d)
if self.out_of_service_deferred and not self.pending:
self.out_of_service_deferred.callback(None)
@defer.inlineCallbacks
def _handle_request(self, request):
"""Handles given request and returns its response."""
if 'types' in self.method_data[request['method']]:
self._validate_params_types(request['method'], request['params'])
if self.serve_exception:
raise self.serve_exception()
d = self._call_method(request)
self.pending.add(d)
if self.timeout:
timeout_deferred = self.reactor.callLater(self.timeout, d.cancel)
def completed(result):
if timeout_deferred.active():
# cancel the timeout_deferred if it has not been fired yet
# this is to prevent d's deferred chain from firing twice
# (and raising an exception).
timeout_deferred.cancel()
return result
d.addBoth(completed)
try:
result = yield d
except defer.CancelledError:
# The request was cancelled due to a timeout or by cancelPending
# having been called. We return a TimeoutError to the client.
self._remove_pending(d)
raise TimeoutError()
except Exception as e:
self._remove_pending(d)
raise e
self._remove_pending(d)
# Do not respond to notifications.
if request['id'] is None:
defer.returnValue(None)
respond = {}
self._fill_ver(request['jsonrpc'], respond)
respond['result'] = result
respond['id'] = request['id']
defer.returnValue(respond)
def _get_default_vals(self):
"""
Returns dictionary containing default jsonrpc request/responds values
for error handling purposes.
"""
return {"jsonrpc": DEFAULT_JSONRPC, "id": None}
def _validate_params_types(self, method, params):
"""
Validates request's parameter types.
"""
if isinstance(params, list):
if not isinstance(self.method_data[method]['types'], list):
raise InvalidParamsError(
'expected keyword params, not positional')
for param, type, posnum in zip(params,
self.method_data[method]['types'],
range(1, len(params)+1)):
if not (isinstance(param, type) or param is None):
raise InvalidParamsError(
'positional arg #{} is the wrong type'.format(posnum))
elif isinstance(params, dict):
if not isinstance(self.method_data[method]['types'], dict):
raise InvalidParamsError(
'expected positional params, not keyword')
if 'required' in self.method_data[method]:
for key in self.method_data[method]['required']:
if key not in params:
raise InvalidParamsError('missing key: %s' % key)
for key in params.keys():
if key not in self.method_data[method]['types'] or \
not (isinstance(params[key],
self.method_data[method]['types'][key])
or params[key] is None):
raise InvalidParamsError(
'arg "{}" is the wrong type'.format(key))
|
flowroute/txjason
|
txjason/service.py
|
JSONRPCService._max_args
|
python
|
def _max_args(self, f):
if f.func_defaults is None:
return f.func_code.co_argcount
return f.func_code.co_argcount + len(f.func_defaults)
|
Returns maximum number of arguments accepted by given function.
|
train
|
https://github.com/flowroute/txjason/blob/4865bd716847dcbab99acc69daa0c44ae3cc5b89/txjason/service.py#L327-L334
| null |
class JSONRPCService(object):
"""
The JSONRPCService class is a JSON-RPC
"""
def __init__(self, timeout=None, reactor=reactor):
self.method_data = {}
self.serve_exception = None
self.out_of_service_deferred = None
self.pending = set()
self.timeout = timeout
self.reactor = reactor
def add(self, f, name=None, types=None, required=None):
"""
Adds a new method to the jsonrpc service.
Arguments:
f -- the remote function
name -- name of the method in the jsonrpc service
types -- list or dictionary of the types of accepted arguments
required -- list of required keyword arguments
If name argument is not given, function's own name will be used.
Argument types must be a list if positional arguments are used or a
dictionary if keyword arguments are used in the method in question.
Argument required MUST be used only for methods requiring keyword
arguments, not for methods accepting positional arguments.
"""
if name is None:
fname = f.__name__ # Register the function using its own name.
else:
fname = name
self.method_data[fname] = {'method': f}
if types is not None:
self.method_data[fname]['types'] = types
if required is not None:
self.method_data[fname]['required'] = required
def stopServing(self, exception=None):
"""
Returns a deferred that will fire immediately if there are
no pending requests, otherwise when the last request is removed
from self.pending.
"""
if exception is None:
exception = ServiceUnavailableError
self.serve_exception = exception
if self.pending:
d = self.out_of_service_deferred = defer.Deferred()
return d
return defer.succeed(None)
def startServing(self):
self.serve_exception = None
self.out_of_service_deferred = None
def cancelPending(self):
pending = self.pending.copy()
for i in pending:
i.cancel()
@defer.inlineCallbacks
def call(self, jsondata):
"""
Calls jsonrpc service's method and returns its return value in a JSON
string or None if there is none.
Arguments:
jsondata -- remote method call in jsonrpc format
"""
result = yield self.call_py(jsondata)
if result is None:
defer.returnValue(None)
else:
defer.returnValue(json.dumps(result))
@defer.inlineCallbacks
def call_py(self, jsondata):
"""
Calls jsonrpc service's method and returns its return value in python
object format or None if there is none.
This method is same as call() except the return value is a python
object instead of JSON string. This method is mainly only useful for
debugging purposes.
"""
try:
try:
rdata = json.loads(jsondata)
except ValueError:
raise ParseError
except ParseError, e:
defer.returnValue(self._get_err(e))
return
# set some default values for error handling
request = self._get_default_vals()
try:
if isinstance(rdata, dict) and rdata:
# It's a single request.
self._fill_request(request, rdata)
respond = yield self._handle_request(request)
# Don't respond to notifications
if respond is None:
defer.returnValue(None)
else:
defer.returnValue(respond)
return
elif isinstance(rdata, list) and rdata:
# It's a batch.
requests = []
responds = []
for rdata_ in rdata:
# set some default values for error handling
request_ = self._get_default_vals()
try:
self._fill_request(request_, rdata_)
except InvalidRequestError, e:
err = self._get_err(e, request_['id'])
if err:
responds.append(err)
continue
except JSONRPCError, e:
err = self._get_err(e, request_['id'])
if err:
responds.append(err)
continue
requests.append(request_)
for request_ in requests:
try:
# TODO: We should use a deferred list so requests
# are processed in parallel
respond = yield self._handle_request(request_)
except JSONRPCError, e:
respond = self._get_err(e,
request_['id'],
request_['jsonrpc'])
# Don't respond to notifications
if respond is not None:
responds.append(respond)
if responds:
defer.returnValue(responds)
return
# Nothing to respond.
defer.returnValue(None)
return
else:
# empty dict, list or wrong type
raise InvalidRequestError
except InvalidRequestError, e:
defer.returnValue(self._get_err(e, request['id']))
except JSONRPCError, e:
defer.returnValue(self._get_err(e,
request['id'],
request['jsonrpc']))
def _get_err(self, e, id=None, jsonrpc=DEFAULT_JSONRPC):
"""
Returns jsonrpc error message.
"""
# Do not respond to notifications when the request is valid.
if not id \
and not isinstance(e, ParseError) \
and not isinstance(e, InvalidRequestError):
return None
respond = {'id': id}
if isinstance(jsonrpc, int):
# v1.0 requires result to exist always.
# No error codes are defined in v1.0 so only use the message.
if jsonrpc == 10:
respond['result'] = None
respond['error'] = e.dumps()['message']
else:
self._fill_ver(jsonrpc, respond)
respond['error'] = e.dumps()
else:
respond['jsonrpc'] = jsonrpc
respond['error'] = e.dumps()
return respond
def _fill_ver(self, iver, respond):
"""
Fills version information to the respond from the internal integer
version.
"""
if iver == 20:
respond['jsonrpc'] = '2.0'
if iver == 11:
respond['version'] = '1.1'
def _vargs(self, f):
"""
Returns True if given function accepts variadic positional arguments,
otherwise False.
"""
if f.func_code.co_flags & 4:
return True
return False
def _man_args(self, f):
"""
Returns number of mandatory arguments required by given function.
"""
argcount = f.func_code.co_argcount
# account for "self" getting passed to class instance methods
if isinstance(f, types.MethodType):
argcount -= 1
if f.func_defaults is None:
return argcount
return argcount - len(f.func_defaults)
def _get_jsonrpc(self, rdata):
"""
Returns jsonrpc request's jsonrpc value.
InvalidRequestError will be raised if the jsonrpc value has invalid
value.
"""
if 'jsonrpc' in rdata:
if rdata['jsonrpc'] == '2.0':
return 20
else:
# invalid version
raise InvalidRequestError
else:
# It's probably a JSON-RPC v1.x style call.
if 'version' in rdata:
if rdata['version'] == '1.1':
return 11
# Assume v1.0.
return 10
def _get_id(self, rdata):
"""
Returns jsonrpc request's id value or None if there is none.
InvalidRequestError will be raised if the id value has invalid type.
"""
if 'id' in rdata:
if isinstance(rdata['id'], basestring) or \
isinstance(rdata['id'], int) or \
isinstance(rdata['id'], long) or \
isinstance(rdata['id'], float) or \
rdata['id'] is None:
return rdata['id']
else:
# invalid type
raise InvalidRequestError
else:
# It's a notification.
return None
def _get_method(self, rdata):
"""
Returns jsonrpc request's method value.
InvalidRequestError will be raised if it's missing or is wrong type.
MethodNotFoundError will be raised if a method with given method name
does not exist.
"""
if 'method' in rdata:
if not isinstance(rdata['method'], basestring):
raise InvalidRequestError
else:
raise InvalidRequestError
if rdata['method'] not in self.method_data.keys():
raise MethodNotFoundError
return rdata['method']
def _get_params(self, rdata):
"""
Returns a list of jsonrpc request's method parameters.
"""
if 'params' in rdata:
if isinstance(rdata['params'], dict) \
or isinstance(rdata['params'], list) \
or rdata['params'] is None:
return rdata['params']
else:
# wrong type
raise InvalidRequestError
else:
return None
def _fill_request(self, request, rdata):
"""Fills request with data from the jsonrpc call."""
if not isinstance(rdata, dict):
raise InvalidRequestError
request['jsonrpc'] = self._get_jsonrpc(rdata)
request['id'] = self._get_id(rdata)
request['method'] = self._get_method(rdata)
request['params'] = self._get_params(rdata)
@defer.inlineCallbacks
def _call_method(self, request):
"""Calls given method with given params and returns it value."""
method = self.method_data[request['method']]['method']
params = request['params']
result = None
try:
if isinstance(params, list):
# Does it have enough arguments?
if len(params) < self._man_args(method):
raise InvalidParamsError('not enough arguments')
# Does it have too many arguments?
if not self._vargs(method) \
and len(params) > self._max_args(method):
raise InvalidParamsError('too many arguments')
result = yield defer.maybeDeferred(method, *params)
elif isinstance(params, dict):
# Do not accept keyword arguments if the jsonrpc version is
# not >=1.1.
if request['jsonrpc'] < 11:
raise KeywordError
result = yield defer.maybeDeferred(method, **params)
else: # No params
result = yield defer.maybeDeferred(method)
except JSONRPCError:
raise
except Exception:
# Exception was raised inside the method.
log.msg('Exception raised while invoking RPC method "{}".'.format(
request['method']))
log.err()
raise ServerError
defer.returnValue(result)
def _remove_pending(self, d):
self.pending.remove(d)
if self.out_of_service_deferred and not self.pending:
self.out_of_service_deferred.callback(None)
@defer.inlineCallbacks
def _handle_request(self, request):
"""Handles given request and returns its response."""
if 'types' in self.method_data[request['method']]:
self._validate_params_types(request['method'], request['params'])
if self.serve_exception:
raise self.serve_exception()
d = self._call_method(request)
self.pending.add(d)
if self.timeout:
timeout_deferred = self.reactor.callLater(self.timeout, d.cancel)
def completed(result):
if timeout_deferred.active():
# cancel the timeout_deferred if it has not been fired yet
# this is to prevent d's deferred chain from firing twice
# (and raising an exception).
timeout_deferred.cancel()
return result
d.addBoth(completed)
try:
result = yield d
except defer.CancelledError:
# The request was cancelled due to a timeout or by cancelPending
# having been called. We return a TimeoutError to the client.
self._remove_pending(d)
raise TimeoutError()
except Exception as e:
self._remove_pending(d)
raise e
self._remove_pending(d)
# Do not respond to notifications.
if request['id'] is None:
defer.returnValue(None)
respond = {}
self._fill_ver(request['jsonrpc'], respond)
respond['result'] = result
respond['id'] = request['id']
defer.returnValue(respond)
def _get_default_vals(self):
"""
Returns dictionary containing default jsonrpc request/responds values
for error handling purposes.
"""
return {"jsonrpc": DEFAULT_JSONRPC, "id": None}
def _validate_params_types(self, method, params):
"""
Validates request's parameter types.
"""
if isinstance(params, list):
if not isinstance(self.method_data[method]['types'], list):
raise InvalidParamsError(
'expected keyword params, not positional')
for param, type, posnum in zip(params,
self.method_data[method]['types'],
range(1, len(params)+1)):
if not (isinstance(param, type) or param is None):
raise InvalidParamsError(
'positional arg #{} is the wrong type'.format(posnum))
elif isinstance(params, dict):
if not isinstance(self.method_data[method]['types'], dict):
raise InvalidParamsError(
'expected positional params, not keyword')
if 'required' in self.method_data[method]:
for key in self.method_data[method]['required']:
if key not in params:
raise InvalidParamsError('missing key: %s' % key)
for key in params.keys():
if key not in self.method_data[method]['types'] or \
not (isinstance(params[key],
self.method_data[method]['types'][key])
or params[key] is None):
raise InvalidParamsError(
'arg "{}" is the wrong type'.format(key))
|
flowroute/txjason
|
txjason/service.py
|
JSONRPCService._get_id
|
python
|
def _get_id(self, rdata):
if 'id' in rdata:
if isinstance(rdata['id'], basestring) or \
isinstance(rdata['id'], int) or \
isinstance(rdata['id'], long) or \
isinstance(rdata['id'], float) or \
rdata['id'] is None:
return rdata['id']
else:
# invalid type
raise InvalidRequestError
else:
# It's a notification.
return None
|
Returns jsonrpc request's id value or None if there is none.
InvalidRequestError will be raised if the id value has invalid type.
|
train
|
https://github.com/flowroute/txjason/blob/4865bd716847dcbab99acc69daa0c44ae3cc5b89/txjason/service.py#L358-L376
| null |
class JSONRPCService(object):
"""
The JSONRPCService class is a JSON-RPC
"""
def __init__(self, timeout=None, reactor=reactor):
self.method_data = {}
self.serve_exception = None
self.out_of_service_deferred = None
self.pending = set()
self.timeout = timeout
self.reactor = reactor
def add(self, f, name=None, types=None, required=None):
"""
Adds a new method to the jsonrpc service.
Arguments:
f -- the remote function
name -- name of the method in the jsonrpc service
types -- list or dictionary of the types of accepted arguments
required -- list of required keyword arguments
If name argument is not given, function's own name will be used.
Argument types must be a list if positional arguments are used or a
dictionary if keyword arguments are used in the method in question.
Argument required MUST be used only for methods requiring keyword
arguments, not for methods accepting positional arguments.
"""
if name is None:
fname = f.__name__ # Register the function using its own name.
else:
fname = name
self.method_data[fname] = {'method': f}
if types is not None:
self.method_data[fname]['types'] = types
if required is not None:
self.method_data[fname]['required'] = required
def stopServing(self, exception=None):
"""
Returns a deferred that will fire immediately if there are
no pending requests, otherwise when the last request is removed
from self.pending.
"""
if exception is None:
exception = ServiceUnavailableError
self.serve_exception = exception
if self.pending:
d = self.out_of_service_deferred = defer.Deferred()
return d
return defer.succeed(None)
def startServing(self):
self.serve_exception = None
self.out_of_service_deferred = None
def cancelPending(self):
pending = self.pending.copy()
for i in pending:
i.cancel()
@defer.inlineCallbacks
def call(self, jsondata):
"""
Calls jsonrpc service's method and returns its return value in a JSON
string or None if there is none.
Arguments:
jsondata -- remote method call in jsonrpc format
"""
result = yield self.call_py(jsondata)
if result is None:
defer.returnValue(None)
else:
defer.returnValue(json.dumps(result))
@defer.inlineCallbacks
def call_py(self, jsondata):
"""
Calls jsonrpc service's method and returns its return value in python
object format or None if there is none.
This method is same as call() except the return value is a python
object instead of JSON string. This method is mainly only useful for
debugging purposes.
"""
try:
try:
rdata = json.loads(jsondata)
except ValueError:
raise ParseError
except ParseError, e:
defer.returnValue(self._get_err(e))
return
# set some default values for error handling
request = self._get_default_vals()
try:
if isinstance(rdata, dict) and rdata:
# It's a single request.
self._fill_request(request, rdata)
respond = yield self._handle_request(request)
# Don't respond to notifications
if respond is None:
defer.returnValue(None)
else:
defer.returnValue(respond)
return
elif isinstance(rdata, list) and rdata:
# It's a batch.
requests = []
responds = []
for rdata_ in rdata:
# set some default values for error handling
request_ = self._get_default_vals()
try:
self._fill_request(request_, rdata_)
except InvalidRequestError, e:
err = self._get_err(e, request_['id'])
if err:
responds.append(err)
continue
except JSONRPCError, e:
err = self._get_err(e, request_['id'])
if err:
responds.append(err)
continue
requests.append(request_)
for request_ in requests:
try:
# TODO: We should use a deferred list so requests
# are processed in parallel
respond = yield self._handle_request(request_)
except JSONRPCError, e:
respond = self._get_err(e,
request_['id'],
request_['jsonrpc'])
# Don't respond to notifications
if respond is not None:
responds.append(respond)
if responds:
defer.returnValue(responds)
return
# Nothing to respond.
defer.returnValue(None)
return
else:
# empty dict, list or wrong type
raise InvalidRequestError
except InvalidRequestError, e:
defer.returnValue(self._get_err(e, request['id']))
except JSONRPCError, e:
defer.returnValue(self._get_err(e,
request['id'],
request['jsonrpc']))
def _get_err(self, e, id=None, jsonrpc=DEFAULT_JSONRPC):
"""
Returns jsonrpc error message.
"""
# Do not respond to notifications when the request is valid.
if not id \
and not isinstance(e, ParseError) \
and not isinstance(e, InvalidRequestError):
return None
respond = {'id': id}
if isinstance(jsonrpc, int):
# v1.0 requires result to exist always.
# No error codes are defined in v1.0 so only use the message.
if jsonrpc == 10:
respond['result'] = None
respond['error'] = e.dumps()['message']
else:
self._fill_ver(jsonrpc, respond)
respond['error'] = e.dumps()
else:
respond['jsonrpc'] = jsonrpc
respond['error'] = e.dumps()
return respond
def _fill_ver(self, iver, respond):
"""
Fills version information to the respond from the internal integer
version.
"""
if iver == 20:
respond['jsonrpc'] = '2.0'
if iver == 11:
respond['version'] = '1.1'
def _vargs(self, f):
"""
Returns True if given function accepts variadic positional arguments,
otherwise False.
"""
if f.func_code.co_flags & 4:
return True
return False
def _man_args(self, f):
"""
Returns number of mandatory arguments required by given function.
"""
argcount = f.func_code.co_argcount
# account for "self" getting passed to class instance methods
if isinstance(f, types.MethodType):
argcount -= 1
if f.func_defaults is None:
return argcount
return argcount - len(f.func_defaults)
def _max_args(self, f):
"""
Returns maximum number of arguments accepted by given function.
"""
if f.func_defaults is None:
return f.func_code.co_argcount
return f.func_code.co_argcount + len(f.func_defaults)
def _get_jsonrpc(self, rdata):
"""
Returns jsonrpc request's jsonrpc value.
InvalidRequestError will be raised if the jsonrpc value has invalid
value.
"""
if 'jsonrpc' in rdata:
if rdata['jsonrpc'] == '2.0':
return 20
else:
# invalid version
raise InvalidRequestError
else:
# It's probably a JSON-RPC v1.x style call.
if 'version' in rdata:
if rdata['version'] == '1.1':
return 11
# Assume v1.0.
return 10
def _get_method(self, rdata):
"""
Returns jsonrpc request's method value.
InvalidRequestError will be raised if it's missing or is wrong type.
MethodNotFoundError will be raised if a method with given method name
does not exist.
"""
if 'method' in rdata:
if not isinstance(rdata['method'], basestring):
raise InvalidRequestError
else:
raise InvalidRequestError
if rdata['method'] not in self.method_data.keys():
raise MethodNotFoundError
return rdata['method']
def _get_params(self, rdata):
"""
Returns a list of jsonrpc request's method parameters.
"""
if 'params' in rdata:
if isinstance(rdata['params'], dict) \
or isinstance(rdata['params'], list) \
or rdata['params'] is None:
return rdata['params']
else:
# wrong type
raise InvalidRequestError
else:
return None
def _fill_request(self, request, rdata):
"""Fills request with data from the jsonrpc call."""
if not isinstance(rdata, dict):
raise InvalidRequestError
request['jsonrpc'] = self._get_jsonrpc(rdata)
request['id'] = self._get_id(rdata)
request['method'] = self._get_method(rdata)
request['params'] = self._get_params(rdata)
@defer.inlineCallbacks
def _call_method(self, request):
"""Calls given method with given params and returns it value."""
method = self.method_data[request['method']]['method']
params = request['params']
result = None
try:
if isinstance(params, list):
# Does it have enough arguments?
if len(params) < self._man_args(method):
raise InvalidParamsError('not enough arguments')
# Does it have too many arguments?
if not self._vargs(method) \
and len(params) > self._max_args(method):
raise InvalidParamsError('too many arguments')
result = yield defer.maybeDeferred(method, *params)
elif isinstance(params, dict):
# Do not accept keyword arguments if the jsonrpc version is
# not >=1.1.
if request['jsonrpc'] < 11:
raise KeywordError
result = yield defer.maybeDeferred(method, **params)
else: # No params
result = yield defer.maybeDeferred(method)
except JSONRPCError:
raise
except Exception:
# Exception was raised inside the method.
log.msg('Exception raised while invoking RPC method "{}".'.format(
request['method']))
log.err()
raise ServerError
defer.returnValue(result)
def _remove_pending(self, d):
self.pending.remove(d)
if self.out_of_service_deferred and not self.pending:
self.out_of_service_deferred.callback(None)
@defer.inlineCallbacks
def _handle_request(self, request):
"""Handles given request and returns its response."""
if 'types' in self.method_data[request['method']]:
self._validate_params_types(request['method'], request['params'])
if self.serve_exception:
raise self.serve_exception()
d = self._call_method(request)
self.pending.add(d)
if self.timeout:
timeout_deferred = self.reactor.callLater(self.timeout, d.cancel)
def completed(result):
if timeout_deferred.active():
# cancel the timeout_deferred if it has not been fired yet
# this is to prevent d's deferred chain from firing twice
# (and raising an exception).
timeout_deferred.cancel()
return result
d.addBoth(completed)
try:
result = yield d
except defer.CancelledError:
# The request was cancelled due to a timeout or by cancelPending
# having been called. We return a TimeoutError to the client.
self._remove_pending(d)
raise TimeoutError()
except Exception as e:
self._remove_pending(d)
raise e
self._remove_pending(d)
# Do not respond to notifications.
if request['id'] is None:
defer.returnValue(None)
respond = {}
self._fill_ver(request['jsonrpc'], respond)
respond['result'] = result
respond['id'] = request['id']
defer.returnValue(respond)
def _get_default_vals(self):
"""
Returns dictionary containing default jsonrpc request/responds values
for error handling purposes.
"""
return {"jsonrpc": DEFAULT_JSONRPC, "id": None}
def _validate_params_types(self, method, params):
"""
Validates request's parameter types.
"""
if isinstance(params, list):
if not isinstance(self.method_data[method]['types'], list):
raise InvalidParamsError(
'expected keyword params, not positional')
for param, type, posnum in zip(params,
self.method_data[method]['types'],
range(1, len(params)+1)):
if not (isinstance(param, type) or param is None):
raise InvalidParamsError(
'positional arg #{} is the wrong type'.format(posnum))
elif isinstance(params, dict):
if not isinstance(self.method_data[method]['types'], dict):
raise InvalidParamsError(
'expected positional params, not keyword')
if 'required' in self.method_data[method]:
for key in self.method_data[method]['required']:
if key not in params:
raise InvalidParamsError('missing key: %s' % key)
for key in params.keys():
if key not in self.method_data[method]['types'] or \
not (isinstance(params[key],
self.method_data[method]['types'][key])
or params[key] is None):
raise InvalidParamsError(
'arg "{}" is the wrong type'.format(key))
|
flowroute/txjason
|
txjason/service.py
|
JSONRPCService._get_method
|
python
|
def _get_method(self, rdata):
if 'method' in rdata:
if not isinstance(rdata['method'], basestring):
raise InvalidRequestError
else:
raise InvalidRequestError
if rdata['method'] not in self.method_data.keys():
raise MethodNotFoundError
return rdata['method']
|
Returns jsonrpc request's method value.
InvalidRequestError will be raised if it's missing or is wrong type.
MethodNotFoundError will be raised if a method with given method name
does not exist.
|
train
|
https://github.com/flowroute/txjason/blob/4865bd716847dcbab99acc69daa0c44ae3cc5b89/txjason/service.py#L378-L395
| null |
class JSONRPCService(object):
"""
The JSONRPCService class is a JSON-RPC
"""
def __init__(self, timeout=None, reactor=reactor):
self.method_data = {}
self.serve_exception = None
self.out_of_service_deferred = None
self.pending = set()
self.timeout = timeout
self.reactor = reactor
def add(self, f, name=None, types=None, required=None):
"""
Adds a new method to the jsonrpc service.
Arguments:
f -- the remote function
name -- name of the method in the jsonrpc service
types -- list or dictionary of the types of accepted arguments
required -- list of required keyword arguments
If name argument is not given, function's own name will be used.
Argument types must be a list if positional arguments are used or a
dictionary if keyword arguments are used in the method in question.
Argument required MUST be used only for methods requiring keyword
arguments, not for methods accepting positional arguments.
"""
if name is None:
fname = f.__name__ # Register the function using its own name.
else:
fname = name
self.method_data[fname] = {'method': f}
if types is not None:
self.method_data[fname]['types'] = types
if required is not None:
self.method_data[fname]['required'] = required
def stopServing(self, exception=None):
"""
Returns a deferred that will fire immediately if there are
no pending requests, otherwise when the last request is removed
from self.pending.
"""
if exception is None:
exception = ServiceUnavailableError
self.serve_exception = exception
if self.pending:
d = self.out_of_service_deferred = defer.Deferred()
return d
return defer.succeed(None)
def startServing(self):
self.serve_exception = None
self.out_of_service_deferred = None
def cancelPending(self):
pending = self.pending.copy()
for i in pending:
i.cancel()
@defer.inlineCallbacks
def call(self, jsondata):
"""
Calls jsonrpc service's method and returns its return value in a JSON
string or None if there is none.
Arguments:
jsondata -- remote method call in jsonrpc format
"""
result = yield self.call_py(jsondata)
if result is None:
defer.returnValue(None)
else:
defer.returnValue(json.dumps(result))
@defer.inlineCallbacks
def call_py(self, jsondata):
"""
Calls jsonrpc service's method and returns its return value in python
object format or None if there is none.
This method is same as call() except the return value is a python
object instead of JSON string. This method is mainly only useful for
debugging purposes.
"""
try:
try:
rdata = json.loads(jsondata)
except ValueError:
raise ParseError
except ParseError, e:
defer.returnValue(self._get_err(e))
return
# set some default values for error handling
request = self._get_default_vals()
try:
if isinstance(rdata, dict) and rdata:
# It's a single request.
self._fill_request(request, rdata)
respond = yield self._handle_request(request)
# Don't respond to notifications
if respond is None:
defer.returnValue(None)
else:
defer.returnValue(respond)
return
elif isinstance(rdata, list) and rdata:
# It's a batch.
requests = []
responds = []
for rdata_ in rdata:
# set some default values for error handling
request_ = self._get_default_vals()
try:
self._fill_request(request_, rdata_)
except InvalidRequestError, e:
err = self._get_err(e, request_['id'])
if err:
responds.append(err)
continue
except JSONRPCError, e:
err = self._get_err(e, request_['id'])
if err:
responds.append(err)
continue
requests.append(request_)
for request_ in requests:
try:
# TODO: We should use a deferred list so requests
# are processed in parallel
respond = yield self._handle_request(request_)
except JSONRPCError, e:
respond = self._get_err(e,
request_['id'],
request_['jsonrpc'])
# Don't respond to notifications
if respond is not None:
responds.append(respond)
if responds:
defer.returnValue(responds)
return
# Nothing to respond.
defer.returnValue(None)
return
else:
# empty dict, list or wrong type
raise InvalidRequestError
except InvalidRequestError, e:
defer.returnValue(self._get_err(e, request['id']))
except JSONRPCError, e:
defer.returnValue(self._get_err(e,
request['id'],
request['jsonrpc']))
def _get_err(self, e, id=None, jsonrpc=DEFAULT_JSONRPC):
"""
Returns jsonrpc error message.
"""
# Do not respond to notifications when the request is valid.
if not id \
and not isinstance(e, ParseError) \
and not isinstance(e, InvalidRequestError):
return None
respond = {'id': id}
if isinstance(jsonrpc, int):
# v1.0 requires result to exist always.
# No error codes are defined in v1.0 so only use the message.
if jsonrpc == 10:
respond['result'] = None
respond['error'] = e.dumps()['message']
else:
self._fill_ver(jsonrpc, respond)
respond['error'] = e.dumps()
else:
respond['jsonrpc'] = jsonrpc
respond['error'] = e.dumps()
return respond
def _fill_ver(self, iver, respond):
"""
Fills version information to the respond from the internal integer
version.
"""
if iver == 20:
respond['jsonrpc'] = '2.0'
if iver == 11:
respond['version'] = '1.1'
def _vargs(self, f):
"""
Returns True if given function accepts variadic positional arguments,
otherwise False.
"""
if f.func_code.co_flags & 4:
return True
return False
def _man_args(self, f):
"""
Returns number of mandatory arguments required by given function.
"""
argcount = f.func_code.co_argcount
# account for "self" getting passed to class instance methods
if isinstance(f, types.MethodType):
argcount -= 1
if f.func_defaults is None:
return argcount
return argcount - len(f.func_defaults)
def _max_args(self, f):
"""
Returns maximum number of arguments accepted by given function.
"""
if f.func_defaults is None:
return f.func_code.co_argcount
return f.func_code.co_argcount + len(f.func_defaults)
def _get_jsonrpc(self, rdata):
"""
Returns jsonrpc request's jsonrpc value.
InvalidRequestError will be raised if the jsonrpc value has invalid
value.
"""
if 'jsonrpc' in rdata:
if rdata['jsonrpc'] == '2.0':
return 20
else:
# invalid version
raise InvalidRequestError
else:
# It's probably a JSON-RPC v1.x style call.
if 'version' in rdata:
if rdata['version'] == '1.1':
return 11
# Assume v1.0.
return 10
def _get_id(self, rdata):
"""
Returns jsonrpc request's id value or None if there is none.
InvalidRequestError will be raised if the id value has invalid type.
"""
if 'id' in rdata:
if isinstance(rdata['id'], basestring) or \
isinstance(rdata['id'], int) or \
isinstance(rdata['id'], long) or \
isinstance(rdata['id'], float) or \
rdata['id'] is None:
return rdata['id']
else:
# invalid type
raise InvalidRequestError
else:
# It's a notification.
return None
def _get_params(self, rdata):
"""
Returns a list of jsonrpc request's method parameters.
"""
if 'params' in rdata:
if isinstance(rdata['params'], dict) \
or isinstance(rdata['params'], list) \
or rdata['params'] is None:
return rdata['params']
else:
# wrong type
raise InvalidRequestError
else:
return None
def _fill_request(self, request, rdata):
"""Fills request with data from the jsonrpc call."""
if not isinstance(rdata, dict):
raise InvalidRequestError
request['jsonrpc'] = self._get_jsonrpc(rdata)
request['id'] = self._get_id(rdata)
request['method'] = self._get_method(rdata)
request['params'] = self._get_params(rdata)
@defer.inlineCallbacks
def _call_method(self, request):
"""Calls given method with given params and returns it value."""
method = self.method_data[request['method']]['method']
params = request['params']
result = None
try:
if isinstance(params, list):
# Does it have enough arguments?
if len(params) < self._man_args(method):
raise InvalidParamsError('not enough arguments')
# Does it have too many arguments?
if not self._vargs(method) \
and len(params) > self._max_args(method):
raise InvalidParamsError('too many arguments')
result = yield defer.maybeDeferred(method, *params)
elif isinstance(params, dict):
# Do not accept keyword arguments if the jsonrpc version is
# not >=1.1.
if request['jsonrpc'] < 11:
raise KeywordError
result = yield defer.maybeDeferred(method, **params)
else: # No params
result = yield defer.maybeDeferred(method)
except JSONRPCError:
raise
except Exception:
# Exception was raised inside the method.
log.msg('Exception raised while invoking RPC method "{}".'.format(
request['method']))
log.err()
raise ServerError
defer.returnValue(result)
def _remove_pending(self, d):
self.pending.remove(d)
if self.out_of_service_deferred and not self.pending:
self.out_of_service_deferred.callback(None)
@defer.inlineCallbacks
def _handle_request(self, request):
"""Handles given request and returns its response."""
if 'types' in self.method_data[request['method']]:
self._validate_params_types(request['method'], request['params'])
if self.serve_exception:
raise self.serve_exception()
d = self._call_method(request)
self.pending.add(d)
if self.timeout:
timeout_deferred = self.reactor.callLater(self.timeout, d.cancel)
def completed(result):
if timeout_deferred.active():
# cancel the timeout_deferred if it has not been fired yet
# this is to prevent d's deferred chain from firing twice
# (and raising an exception).
timeout_deferred.cancel()
return result
d.addBoth(completed)
try:
result = yield d
except defer.CancelledError:
# The request was cancelled due to a timeout or by cancelPending
# having been called. We return a TimeoutError to the client.
self._remove_pending(d)
raise TimeoutError()
except Exception as e:
self._remove_pending(d)
raise e
self._remove_pending(d)
# Do not respond to notifications.
if request['id'] is None:
defer.returnValue(None)
respond = {}
self._fill_ver(request['jsonrpc'], respond)
respond['result'] = result
respond['id'] = request['id']
defer.returnValue(respond)
def _get_default_vals(self):
"""
Returns dictionary containing default jsonrpc request/responds values
for error handling purposes.
"""
return {"jsonrpc": DEFAULT_JSONRPC, "id": None}
def _validate_params_types(self, method, params):
"""
Validates request's parameter types.
"""
if isinstance(params, list):
if not isinstance(self.method_data[method]['types'], list):
raise InvalidParamsError(
'expected keyword params, not positional')
for param, type, posnum in zip(params,
self.method_data[method]['types'],
range(1, len(params)+1)):
if not (isinstance(param, type) or param is None):
raise InvalidParamsError(
'positional arg #{} is the wrong type'.format(posnum))
elif isinstance(params, dict):
if not isinstance(self.method_data[method]['types'], dict):
raise InvalidParamsError(
'expected positional params, not keyword')
if 'required' in self.method_data[method]:
for key in self.method_data[method]['required']:
if key not in params:
raise InvalidParamsError('missing key: %s' % key)
for key in params.keys():
if key not in self.method_data[method]['types'] or \
not (isinstance(params[key],
self.method_data[method]['types'][key])
or params[key] is None):
raise InvalidParamsError(
'arg "{}" is the wrong type'.format(key))
|
flowroute/txjason
|
txjason/service.py
|
JSONRPCService._get_params
|
python
|
def _get_params(self, rdata):
if 'params' in rdata:
if isinstance(rdata['params'], dict) \
or isinstance(rdata['params'], list) \
or rdata['params'] is None:
return rdata['params']
else:
# wrong type
raise InvalidRequestError
else:
return None
|
Returns a list of jsonrpc request's method parameters.
|
train
|
https://github.com/flowroute/txjason/blob/4865bd716847dcbab99acc69daa0c44ae3cc5b89/txjason/service.py#L397-L410
| null |
class JSONRPCService(object):
"""
The JSONRPCService class is a JSON-RPC
"""
def __init__(self, timeout=None, reactor=reactor):
self.method_data = {}
self.serve_exception = None
self.out_of_service_deferred = None
self.pending = set()
self.timeout = timeout
self.reactor = reactor
def add(self, f, name=None, types=None, required=None):
"""
Adds a new method to the jsonrpc service.
Arguments:
f -- the remote function
name -- name of the method in the jsonrpc service
types -- list or dictionary of the types of accepted arguments
required -- list of required keyword arguments
If name argument is not given, function's own name will be used.
Argument types must be a list if positional arguments are used or a
dictionary if keyword arguments are used in the method in question.
Argument required MUST be used only for methods requiring keyword
arguments, not for methods accepting positional arguments.
"""
if name is None:
fname = f.__name__ # Register the function using its own name.
else:
fname = name
self.method_data[fname] = {'method': f}
if types is not None:
self.method_data[fname]['types'] = types
if required is not None:
self.method_data[fname]['required'] = required
def stopServing(self, exception=None):
"""
Returns a deferred that will fire immediately if there are
no pending requests, otherwise when the last request is removed
from self.pending.
"""
if exception is None:
exception = ServiceUnavailableError
self.serve_exception = exception
if self.pending:
d = self.out_of_service_deferred = defer.Deferred()
return d
return defer.succeed(None)
def startServing(self):
self.serve_exception = None
self.out_of_service_deferred = None
def cancelPending(self):
pending = self.pending.copy()
for i in pending:
i.cancel()
@defer.inlineCallbacks
def call(self, jsondata):
"""
Calls jsonrpc service's method and returns its return value in a JSON
string or None if there is none.
Arguments:
jsondata -- remote method call in jsonrpc format
"""
result = yield self.call_py(jsondata)
if result is None:
defer.returnValue(None)
else:
defer.returnValue(json.dumps(result))
@defer.inlineCallbacks
def call_py(self, jsondata):
"""
Calls jsonrpc service's method and returns its return value in python
object format or None if there is none.
This method is same as call() except the return value is a python
object instead of JSON string. This method is mainly only useful for
debugging purposes.
"""
try:
try:
rdata = json.loads(jsondata)
except ValueError:
raise ParseError
except ParseError, e:
defer.returnValue(self._get_err(e))
return
# set some default values for error handling
request = self._get_default_vals()
try:
if isinstance(rdata, dict) and rdata:
# It's a single request.
self._fill_request(request, rdata)
respond = yield self._handle_request(request)
# Don't respond to notifications
if respond is None:
defer.returnValue(None)
else:
defer.returnValue(respond)
return
elif isinstance(rdata, list) and rdata:
# It's a batch.
requests = []
responds = []
for rdata_ in rdata:
# set some default values for error handling
request_ = self._get_default_vals()
try:
self._fill_request(request_, rdata_)
except InvalidRequestError, e:
err = self._get_err(e, request_['id'])
if err:
responds.append(err)
continue
except JSONRPCError, e:
err = self._get_err(e, request_['id'])
if err:
responds.append(err)
continue
requests.append(request_)
for request_ in requests:
try:
# TODO: We should use a deferred list so requests
# are processed in parallel
respond = yield self._handle_request(request_)
except JSONRPCError, e:
respond = self._get_err(e,
request_['id'],
request_['jsonrpc'])
# Don't respond to notifications
if respond is not None:
responds.append(respond)
if responds:
defer.returnValue(responds)
return
# Nothing to respond.
defer.returnValue(None)
return
else:
# empty dict, list or wrong type
raise InvalidRequestError
except InvalidRequestError, e:
defer.returnValue(self._get_err(e, request['id']))
except JSONRPCError, e:
defer.returnValue(self._get_err(e,
request['id'],
request['jsonrpc']))
def _get_err(self, e, id=None, jsonrpc=DEFAULT_JSONRPC):
"""
Returns jsonrpc error message.
"""
# Do not respond to notifications when the request is valid.
if not id \
and not isinstance(e, ParseError) \
and not isinstance(e, InvalidRequestError):
return None
respond = {'id': id}
if isinstance(jsonrpc, int):
# v1.0 requires result to exist always.
# No error codes are defined in v1.0 so only use the message.
if jsonrpc == 10:
respond['result'] = None
respond['error'] = e.dumps()['message']
else:
self._fill_ver(jsonrpc, respond)
respond['error'] = e.dumps()
else:
respond['jsonrpc'] = jsonrpc
respond['error'] = e.dumps()
return respond
def _fill_ver(self, iver, respond):
"""
Fills version information to the respond from the internal integer
version.
"""
if iver == 20:
respond['jsonrpc'] = '2.0'
if iver == 11:
respond['version'] = '1.1'
def _vargs(self, f):
"""
Returns True if given function accepts variadic positional arguments,
otherwise False.
"""
if f.func_code.co_flags & 4:
return True
return False
def _man_args(self, f):
"""
Returns number of mandatory arguments required by given function.
"""
argcount = f.func_code.co_argcount
# account for "self" getting passed to class instance methods
if isinstance(f, types.MethodType):
argcount -= 1
if f.func_defaults is None:
return argcount
return argcount - len(f.func_defaults)
def _max_args(self, f):
"""
Returns maximum number of arguments accepted by given function.
"""
if f.func_defaults is None:
return f.func_code.co_argcount
return f.func_code.co_argcount + len(f.func_defaults)
def _get_jsonrpc(self, rdata):
"""
Returns jsonrpc request's jsonrpc value.
InvalidRequestError will be raised if the jsonrpc value has invalid
value.
"""
if 'jsonrpc' in rdata:
if rdata['jsonrpc'] == '2.0':
return 20
else:
# invalid version
raise InvalidRequestError
else:
# It's probably a JSON-RPC v1.x style call.
if 'version' in rdata:
if rdata['version'] == '1.1':
return 11
# Assume v1.0.
return 10
def _get_id(self, rdata):
"""
Returns jsonrpc request's id value or None if there is none.
InvalidRequestError will be raised if the id value has invalid type.
"""
if 'id' in rdata:
if isinstance(rdata['id'], basestring) or \
isinstance(rdata['id'], int) or \
isinstance(rdata['id'], long) or \
isinstance(rdata['id'], float) or \
rdata['id'] is None:
return rdata['id']
else:
# invalid type
raise InvalidRequestError
else:
# It's a notification.
return None
def _get_method(self, rdata):
"""
Returns jsonrpc request's method value.
InvalidRequestError will be raised if it's missing or is wrong type.
MethodNotFoundError will be raised if a method with given method name
does not exist.
"""
if 'method' in rdata:
if not isinstance(rdata['method'], basestring):
raise InvalidRequestError
else:
raise InvalidRequestError
if rdata['method'] not in self.method_data.keys():
raise MethodNotFoundError
return rdata['method']
def _fill_request(self, request, rdata):
"""Fills request with data from the jsonrpc call."""
if not isinstance(rdata, dict):
raise InvalidRequestError
request['jsonrpc'] = self._get_jsonrpc(rdata)
request['id'] = self._get_id(rdata)
request['method'] = self._get_method(rdata)
request['params'] = self._get_params(rdata)
@defer.inlineCallbacks
def _call_method(self, request):
"""Calls given method with given params and returns it value."""
method = self.method_data[request['method']]['method']
params = request['params']
result = None
try:
if isinstance(params, list):
# Does it have enough arguments?
if len(params) < self._man_args(method):
raise InvalidParamsError('not enough arguments')
# Does it have too many arguments?
if not self._vargs(method) \
and len(params) > self._max_args(method):
raise InvalidParamsError('too many arguments')
result = yield defer.maybeDeferred(method, *params)
elif isinstance(params, dict):
# Do not accept keyword arguments if the jsonrpc version is
# not >=1.1.
if request['jsonrpc'] < 11:
raise KeywordError
result = yield defer.maybeDeferred(method, **params)
else: # No params
result = yield defer.maybeDeferred(method)
except JSONRPCError:
raise
except Exception:
# Exception was raised inside the method.
log.msg('Exception raised while invoking RPC method "{}".'.format(
request['method']))
log.err()
raise ServerError
defer.returnValue(result)
def _remove_pending(self, d):
self.pending.remove(d)
if self.out_of_service_deferred and not self.pending:
self.out_of_service_deferred.callback(None)
@defer.inlineCallbacks
def _handle_request(self, request):
"""Handles given request and returns its response."""
if 'types' in self.method_data[request['method']]:
self._validate_params_types(request['method'], request['params'])
if self.serve_exception:
raise self.serve_exception()
d = self._call_method(request)
self.pending.add(d)
if self.timeout:
timeout_deferred = self.reactor.callLater(self.timeout, d.cancel)
def completed(result):
if timeout_deferred.active():
# cancel the timeout_deferred if it has not been fired yet
# this is to prevent d's deferred chain from firing twice
# (and raising an exception).
timeout_deferred.cancel()
return result
d.addBoth(completed)
try:
result = yield d
except defer.CancelledError:
# The request was cancelled due to a timeout or by cancelPending
# having been called. We return a TimeoutError to the client.
self._remove_pending(d)
raise TimeoutError()
except Exception as e:
self._remove_pending(d)
raise e
self._remove_pending(d)
# Do not respond to notifications.
if request['id'] is None:
defer.returnValue(None)
respond = {}
self._fill_ver(request['jsonrpc'], respond)
respond['result'] = result
respond['id'] = request['id']
defer.returnValue(respond)
def _get_default_vals(self):
"""
Returns dictionary containing default jsonrpc request/responds values
for error handling purposes.
"""
return {"jsonrpc": DEFAULT_JSONRPC, "id": None}
def _validate_params_types(self, method, params):
"""
Validates request's parameter types.
"""
if isinstance(params, list):
if not isinstance(self.method_data[method]['types'], list):
raise InvalidParamsError(
'expected keyword params, not positional')
for param, type, posnum in zip(params,
self.method_data[method]['types'],
range(1, len(params)+1)):
if not (isinstance(param, type) or param is None):
raise InvalidParamsError(
'positional arg #{} is the wrong type'.format(posnum))
elif isinstance(params, dict):
if not isinstance(self.method_data[method]['types'], dict):
raise InvalidParamsError(
'expected positional params, not keyword')
if 'required' in self.method_data[method]:
for key in self.method_data[method]['required']:
if key not in params:
raise InvalidParamsError('missing key: %s' % key)
for key in params.keys():
if key not in self.method_data[method]['types'] or \
not (isinstance(params[key],
self.method_data[method]['types'][key])
or params[key] is None):
raise InvalidParamsError(
'arg "{}" is the wrong type'.format(key))
|
flowroute/txjason
|
txjason/service.py
|
JSONRPCService._fill_request
|
python
|
def _fill_request(self, request, rdata):
if not isinstance(rdata, dict):
raise InvalidRequestError
request['jsonrpc'] = self._get_jsonrpc(rdata)
request['id'] = self._get_id(rdata)
request['method'] = self._get_method(rdata)
request['params'] = self._get_params(rdata)
|
Fills request with data from the jsonrpc call.
|
train
|
https://github.com/flowroute/txjason/blob/4865bd716847dcbab99acc69daa0c44ae3cc5b89/txjason/service.py#L412-L420
| null |
class JSONRPCService(object):
"""
The JSONRPCService class is a JSON-RPC
"""
def __init__(self, timeout=None, reactor=reactor):
self.method_data = {}
self.serve_exception = None
self.out_of_service_deferred = None
self.pending = set()
self.timeout = timeout
self.reactor = reactor
def add(self, f, name=None, types=None, required=None):
"""
Adds a new method to the jsonrpc service.
Arguments:
f -- the remote function
name -- name of the method in the jsonrpc service
types -- list or dictionary of the types of accepted arguments
required -- list of required keyword arguments
If name argument is not given, function's own name will be used.
Argument types must be a list if positional arguments are used or a
dictionary if keyword arguments are used in the method in question.
Argument required MUST be used only for methods requiring keyword
arguments, not for methods accepting positional arguments.
"""
if name is None:
fname = f.__name__ # Register the function using its own name.
else:
fname = name
self.method_data[fname] = {'method': f}
if types is not None:
self.method_data[fname]['types'] = types
if required is not None:
self.method_data[fname]['required'] = required
def stopServing(self, exception=None):
"""
Returns a deferred that will fire immediately if there are
no pending requests, otherwise when the last request is removed
from self.pending.
"""
if exception is None:
exception = ServiceUnavailableError
self.serve_exception = exception
if self.pending:
d = self.out_of_service_deferred = defer.Deferred()
return d
return defer.succeed(None)
def startServing(self):
self.serve_exception = None
self.out_of_service_deferred = None
def cancelPending(self):
pending = self.pending.copy()
for i in pending:
i.cancel()
@defer.inlineCallbacks
def call(self, jsondata):
"""
Calls jsonrpc service's method and returns its return value in a JSON
string or None if there is none.
Arguments:
jsondata -- remote method call in jsonrpc format
"""
result = yield self.call_py(jsondata)
if result is None:
defer.returnValue(None)
else:
defer.returnValue(json.dumps(result))
@defer.inlineCallbacks
def call_py(self, jsondata):
"""
Calls jsonrpc service's method and returns its return value in python
object format or None if there is none.
This method is same as call() except the return value is a python
object instead of JSON string. This method is mainly only useful for
debugging purposes.
"""
try:
try:
rdata = json.loads(jsondata)
except ValueError:
raise ParseError
except ParseError, e:
defer.returnValue(self._get_err(e))
return
# set some default values for error handling
request = self._get_default_vals()
try:
if isinstance(rdata, dict) and rdata:
# It's a single request.
self._fill_request(request, rdata)
respond = yield self._handle_request(request)
# Don't respond to notifications
if respond is None:
defer.returnValue(None)
else:
defer.returnValue(respond)
return
elif isinstance(rdata, list) and rdata:
# It's a batch.
requests = []
responds = []
for rdata_ in rdata:
# set some default values for error handling
request_ = self._get_default_vals()
try:
self._fill_request(request_, rdata_)
except InvalidRequestError, e:
err = self._get_err(e, request_['id'])
if err:
responds.append(err)
continue
except JSONRPCError, e:
err = self._get_err(e, request_['id'])
if err:
responds.append(err)
continue
requests.append(request_)
for request_ in requests:
try:
# TODO: We should use a deferred list so requests
# are processed in parallel
respond = yield self._handle_request(request_)
except JSONRPCError, e:
respond = self._get_err(e,
request_['id'],
request_['jsonrpc'])
# Don't respond to notifications
if respond is not None:
responds.append(respond)
if responds:
defer.returnValue(responds)
return
# Nothing to respond.
defer.returnValue(None)
return
else:
# empty dict, list or wrong type
raise InvalidRequestError
except InvalidRequestError, e:
defer.returnValue(self._get_err(e, request['id']))
except JSONRPCError, e:
defer.returnValue(self._get_err(e,
request['id'],
request['jsonrpc']))
def _get_err(self, e, id=None, jsonrpc=DEFAULT_JSONRPC):
"""
Returns jsonrpc error message.
"""
# Do not respond to notifications when the request is valid.
if not id \
and not isinstance(e, ParseError) \
and not isinstance(e, InvalidRequestError):
return None
respond = {'id': id}
if isinstance(jsonrpc, int):
# v1.0 requires result to exist always.
# No error codes are defined in v1.0 so only use the message.
if jsonrpc == 10:
respond['result'] = None
respond['error'] = e.dumps()['message']
else:
self._fill_ver(jsonrpc, respond)
respond['error'] = e.dumps()
else:
respond['jsonrpc'] = jsonrpc
respond['error'] = e.dumps()
return respond
def _fill_ver(self, iver, respond):
"""
Fills version information to the respond from the internal integer
version.
"""
if iver == 20:
respond['jsonrpc'] = '2.0'
if iver == 11:
respond['version'] = '1.1'
def _vargs(self, f):
"""
Returns True if given function accepts variadic positional arguments,
otherwise False.
"""
if f.func_code.co_flags & 4:
return True
return False
def _man_args(self, f):
"""
Returns number of mandatory arguments required by given function.
"""
argcount = f.func_code.co_argcount
# account for "self" getting passed to class instance methods
if isinstance(f, types.MethodType):
argcount -= 1
if f.func_defaults is None:
return argcount
return argcount - len(f.func_defaults)
def _max_args(self, f):
"""
Returns maximum number of arguments accepted by given function.
"""
if f.func_defaults is None:
return f.func_code.co_argcount
return f.func_code.co_argcount + len(f.func_defaults)
def _get_jsonrpc(self, rdata):
"""
Returns jsonrpc request's jsonrpc value.
InvalidRequestError will be raised if the jsonrpc value has invalid
value.
"""
if 'jsonrpc' in rdata:
if rdata['jsonrpc'] == '2.0':
return 20
else:
# invalid version
raise InvalidRequestError
else:
# It's probably a JSON-RPC v1.x style call.
if 'version' in rdata:
if rdata['version'] == '1.1':
return 11
# Assume v1.0.
return 10
def _get_id(self, rdata):
"""
Returns jsonrpc request's id value or None if there is none.
InvalidRequestError will be raised if the id value has invalid type.
"""
if 'id' in rdata:
if isinstance(rdata['id'], basestring) or \
isinstance(rdata['id'], int) or \
isinstance(rdata['id'], long) or \
isinstance(rdata['id'], float) or \
rdata['id'] is None:
return rdata['id']
else:
# invalid type
raise InvalidRequestError
else:
# It's a notification.
return None
def _get_method(self, rdata):
"""
Returns jsonrpc request's method value.
InvalidRequestError will be raised if it's missing or is wrong type.
MethodNotFoundError will be raised if a method with given method name
does not exist.
"""
if 'method' in rdata:
if not isinstance(rdata['method'], basestring):
raise InvalidRequestError
else:
raise InvalidRequestError
if rdata['method'] not in self.method_data.keys():
raise MethodNotFoundError
return rdata['method']
def _get_params(self, rdata):
"""
Returns a list of jsonrpc request's method parameters.
"""
if 'params' in rdata:
if isinstance(rdata['params'], dict) \
or isinstance(rdata['params'], list) \
or rdata['params'] is None:
return rdata['params']
else:
# wrong type
raise InvalidRequestError
else:
return None
@defer.inlineCallbacks
def _call_method(self, request):
"""Calls given method with given params and returns it value."""
method = self.method_data[request['method']]['method']
params = request['params']
result = None
try:
if isinstance(params, list):
# Does it have enough arguments?
if len(params) < self._man_args(method):
raise InvalidParamsError('not enough arguments')
# Does it have too many arguments?
if not self._vargs(method) \
and len(params) > self._max_args(method):
raise InvalidParamsError('too many arguments')
result = yield defer.maybeDeferred(method, *params)
elif isinstance(params, dict):
# Do not accept keyword arguments if the jsonrpc version is
# not >=1.1.
if request['jsonrpc'] < 11:
raise KeywordError
result = yield defer.maybeDeferred(method, **params)
else: # No params
result = yield defer.maybeDeferred(method)
except JSONRPCError:
raise
except Exception:
# Exception was raised inside the method.
log.msg('Exception raised while invoking RPC method "{}".'.format(
request['method']))
log.err()
raise ServerError
defer.returnValue(result)
def _remove_pending(self, d):
self.pending.remove(d)
if self.out_of_service_deferred and not self.pending:
self.out_of_service_deferred.callback(None)
@defer.inlineCallbacks
def _handle_request(self, request):
"""Handles given request and returns its response."""
if 'types' in self.method_data[request['method']]:
self._validate_params_types(request['method'], request['params'])
if self.serve_exception:
raise self.serve_exception()
d = self._call_method(request)
self.pending.add(d)
if self.timeout:
timeout_deferred = self.reactor.callLater(self.timeout, d.cancel)
def completed(result):
if timeout_deferred.active():
# cancel the timeout_deferred if it has not been fired yet
# this is to prevent d's deferred chain from firing twice
# (and raising an exception).
timeout_deferred.cancel()
return result
d.addBoth(completed)
try:
result = yield d
except defer.CancelledError:
# The request was cancelled due to a timeout or by cancelPending
# having been called. We return a TimeoutError to the client.
self._remove_pending(d)
raise TimeoutError()
except Exception as e:
self._remove_pending(d)
raise e
self._remove_pending(d)
# Do not respond to notifications.
if request['id'] is None:
defer.returnValue(None)
respond = {}
self._fill_ver(request['jsonrpc'], respond)
respond['result'] = result
respond['id'] = request['id']
defer.returnValue(respond)
def _get_default_vals(self):
"""
Returns dictionary containing default jsonrpc request/responds values
for error handling purposes.
"""
return {"jsonrpc": DEFAULT_JSONRPC, "id": None}
def _validate_params_types(self, method, params):
"""
Validates request's parameter types.
"""
if isinstance(params, list):
if not isinstance(self.method_data[method]['types'], list):
raise InvalidParamsError(
'expected keyword params, not positional')
for param, type, posnum in zip(params,
self.method_data[method]['types'],
range(1, len(params)+1)):
if not (isinstance(param, type) or param is None):
raise InvalidParamsError(
'positional arg #{} is the wrong type'.format(posnum))
elif isinstance(params, dict):
if not isinstance(self.method_data[method]['types'], dict):
raise InvalidParamsError(
'expected positional params, not keyword')
if 'required' in self.method_data[method]:
for key in self.method_data[method]['required']:
if key not in params:
raise InvalidParamsError('missing key: %s' % key)
for key in params.keys():
if key not in self.method_data[method]['types'] or \
not (isinstance(params[key],
self.method_data[method]['types'][key])
or params[key] is None):
raise InvalidParamsError(
'arg "{}" is the wrong type'.format(key))
|
flowroute/txjason
|
txjason/service.py
|
JSONRPCService._call_method
|
python
|
def _call_method(self, request):
method = self.method_data[request['method']]['method']
params = request['params']
result = None
try:
if isinstance(params, list):
# Does it have enough arguments?
if len(params) < self._man_args(method):
raise InvalidParamsError('not enough arguments')
# Does it have too many arguments?
if not self._vargs(method) \
and len(params) > self._max_args(method):
raise InvalidParamsError('too many arguments')
result = yield defer.maybeDeferred(method, *params)
elif isinstance(params, dict):
# Do not accept keyword arguments if the jsonrpc version is
# not >=1.1.
if request['jsonrpc'] < 11:
raise KeywordError
result = yield defer.maybeDeferred(method, **params)
else: # No params
result = yield defer.maybeDeferred(method)
except JSONRPCError:
raise
except Exception:
# Exception was raised inside the method.
log.msg('Exception raised while invoking RPC method "{}".'.format(
request['method']))
log.err()
raise ServerError
defer.returnValue(result)
|
Calls given method with given params and returns it value.
|
train
|
https://github.com/flowroute/txjason/blob/4865bd716847dcbab99acc69daa0c44ae3cc5b89/txjason/service.py#L423-L457
| null |
class JSONRPCService(object):
"""
The JSONRPCService class is a JSON-RPC
"""
def __init__(self, timeout=None, reactor=reactor):
self.method_data = {}
self.serve_exception = None
self.out_of_service_deferred = None
self.pending = set()
self.timeout = timeout
self.reactor = reactor
def add(self, f, name=None, types=None, required=None):
"""
Adds a new method to the jsonrpc service.
Arguments:
f -- the remote function
name -- name of the method in the jsonrpc service
types -- list or dictionary of the types of accepted arguments
required -- list of required keyword arguments
If name argument is not given, function's own name will be used.
Argument types must be a list if positional arguments are used or a
dictionary if keyword arguments are used in the method in question.
Argument required MUST be used only for methods requiring keyword
arguments, not for methods accepting positional arguments.
"""
if name is None:
fname = f.__name__ # Register the function using its own name.
else:
fname = name
self.method_data[fname] = {'method': f}
if types is not None:
self.method_data[fname]['types'] = types
if required is not None:
self.method_data[fname]['required'] = required
def stopServing(self, exception=None):
"""
Returns a deferred that will fire immediately if there are
no pending requests, otherwise when the last request is removed
from self.pending.
"""
if exception is None:
exception = ServiceUnavailableError
self.serve_exception = exception
if self.pending:
d = self.out_of_service_deferred = defer.Deferred()
return d
return defer.succeed(None)
def startServing(self):
self.serve_exception = None
self.out_of_service_deferred = None
def cancelPending(self):
pending = self.pending.copy()
for i in pending:
i.cancel()
@defer.inlineCallbacks
def call(self, jsondata):
"""
Calls jsonrpc service's method and returns its return value in a JSON
string or None if there is none.
Arguments:
jsondata -- remote method call in jsonrpc format
"""
result = yield self.call_py(jsondata)
if result is None:
defer.returnValue(None)
else:
defer.returnValue(json.dumps(result))
@defer.inlineCallbacks
def call_py(self, jsondata):
"""
Calls jsonrpc service's method and returns its return value in python
object format or None if there is none.
This method is same as call() except the return value is a python
object instead of JSON string. This method is mainly only useful for
debugging purposes.
"""
try:
try:
rdata = json.loads(jsondata)
except ValueError:
raise ParseError
except ParseError, e:
defer.returnValue(self._get_err(e))
return
# set some default values for error handling
request = self._get_default_vals()
try:
if isinstance(rdata, dict) and rdata:
# It's a single request.
self._fill_request(request, rdata)
respond = yield self._handle_request(request)
# Don't respond to notifications
if respond is None:
defer.returnValue(None)
else:
defer.returnValue(respond)
return
elif isinstance(rdata, list) and rdata:
# It's a batch.
requests = []
responds = []
for rdata_ in rdata:
# set some default values for error handling
request_ = self._get_default_vals()
try:
self._fill_request(request_, rdata_)
except InvalidRequestError, e:
err = self._get_err(e, request_['id'])
if err:
responds.append(err)
continue
except JSONRPCError, e:
err = self._get_err(e, request_['id'])
if err:
responds.append(err)
continue
requests.append(request_)
for request_ in requests:
try:
# TODO: We should use a deferred list so requests
# are processed in parallel
respond = yield self._handle_request(request_)
except JSONRPCError, e:
respond = self._get_err(e,
request_['id'],
request_['jsonrpc'])
# Don't respond to notifications
if respond is not None:
responds.append(respond)
if responds:
defer.returnValue(responds)
return
# Nothing to respond.
defer.returnValue(None)
return
else:
# empty dict, list or wrong type
raise InvalidRequestError
except InvalidRequestError, e:
defer.returnValue(self._get_err(e, request['id']))
except JSONRPCError, e:
defer.returnValue(self._get_err(e,
request['id'],
request['jsonrpc']))
def _get_err(self, e, id=None, jsonrpc=DEFAULT_JSONRPC):
"""
Returns jsonrpc error message.
"""
# Do not respond to notifications when the request is valid.
if not id \
and not isinstance(e, ParseError) \
and not isinstance(e, InvalidRequestError):
return None
respond = {'id': id}
if isinstance(jsonrpc, int):
# v1.0 requires result to exist always.
# No error codes are defined in v1.0 so only use the message.
if jsonrpc == 10:
respond['result'] = None
respond['error'] = e.dumps()['message']
else:
self._fill_ver(jsonrpc, respond)
respond['error'] = e.dumps()
else:
respond['jsonrpc'] = jsonrpc
respond['error'] = e.dumps()
return respond
def _fill_ver(self, iver, respond):
"""
Fills version information to the respond from the internal integer
version.
"""
if iver == 20:
respond['jsonrpc'] = '2.0'
if iver == 11:
respond['version'] = '1.1'
def _vargs(self, f):
"""
Returns True if given function accepts variadic positional arguments,
otherwise False.
"""
if f.func_code.co_flags & 4:
return True
return False
def _man_args(self, f):
"""
Returns number of mandatory arguments required by given function.
"""
argcount = f.func_code.co_argcount
# account for "self" getting passed to class instance methods
if isinstance(f, types.MethodType):
argcount -= 1
if f.func_defaults is None:
return argcount
return argcount - len(f.func_defaults)
def _max_args(self, f):
"""
Returns maximum number of arguments accepted by given function.
"""
if f.func_defaults is None:
return f.func_code.co_argcount
return f.func_code.co_argcount + len(f.func_defaults)
def _get_jsonrpc(self, rdata):
"""
Returns jsonrpc request's jsonrpc value.
InvalidRequestError will be raised if the jsonrpc value has invalid
value.
"""
if 'jsonrpc' in rdata:
if rdata['jsonrpc'] == '2.0':
return 20
else:
# invalid version
raise InvalidRequestError
else:
# It's probably a JSON-RPC v1.x style call.
if 'version' in rdata:
if rdata['version'] == '1.1':
return 11
# Assume v1.0.
return 10
def _get_id(self, rdata):
"""
Returns jsonrpc request's id value or None if there is none.
InvalidRequestError will be raised if the id value has invalid type.
"""
if 'id' in rdata:
if isinstance(rdata['id'], basestring) or \
isinstance(rdata['id'], int) or \
isinstance(rdata['id'], long) or \
isinstance(rdata['id'], float) or \
rdata['id'] is None:
return rdata['id']
else:
# invalid type
raise InvalidRequestError
else:
# It's a notification.
return None
def _get_method(self, rdata):
"""
Returns jsonrpc request's method value.
InvalidRequestError will be raised if it's missing or is wrong type.
MethodNotFoundError will be raised if a method with given method name
does not exist.
"""
if 'method' in rdata:
if not isinstance(rdata['method'], basestring):
raise InvalidRequestError
else:
raise InvalidRequestError
if rdata['method'] not in self.method_data.keys():
raise MethodNotFoundError
return rdata['method']
def _get_params(self, rdata):
"""
Returns a list of jsonrpc request's method parameters.
"""
if 'params' in rdata:
if isinstance(rdata['params'], dict) \
or isinstance(rdata['params'], list) \
or rdata['params'] is None:
return rdata['params']
else:
# wrong type
raise InvalidRequestError
else:
return None
def _fill_request(self, request, rdata):
"""Fills request with data from the jsonrpc call."""
if not isinstance(rdata, dict):
raise InvalidRequestError
request['jsonrpc'] = self._get_jsonrpc(rdata)
request['id'] = self._get_id(rdata)
request['method'] = self._get_method(rdata)
request['params'] = self._get_params(rdata)
@defer.inlineCallbacks
def _remove_pending(self, d):
self.pending.remove(d)
if self.out_of_service_deferred and not self.pending:
self.out_of_service_deferred.callback(None)
@defer.inlineCallbacks
def _handle_request(self, request):
"""Handles given request and returns its response."""
if 'types' in self.method_data[request['method']]:
self._validate_params_types(request['method'], request['params'])
if self.serve_exception:
raise self.serve_exception()
d = self._call_method(request)
self.pending.add(d)
if self.timeout:
timeout_deferred = self.reactor.callLater(self.timeout, d.cancel)
def completed(result):
if timeout_deferred.active():
# cancel the timeout_deferred if it has not been fired yet
# this is to prevent d's deferred chain from firing twice
# (and raising an exception).
timeout_deferred.cancel()
return result
d.addBoth(completed)
try:
result = yield d
except defer.CancelledError:
# The request was cancelled due to a timeout or by cancelPending
# having been called. We return a TimeoutError to the client.
self._remove_pending(d)
raise TimeoutError()
except Exception as e:
self._remove_pending(d)
raise e
self._remove_pending(d)
# Do not respond to notifications.
if request['id'] is None:
defer.returnValue(None)
respond = {}
self._fill_ver(request['jsonrpc'], respond)
respond['result'] = result
respond['id'] = request['id']
defer.returnValue(respond)
def _get_default_vals(self):
"""
Returns dictionary containing default jsonrpc request/responds values
for error handling purposes.
"""
return {"jsonrpc": DEFAULT_JSONRPC, "id": None}
def _validate_params_types(self, method, params):
"""
Validates request's parameter types.
"""
if isinstance(params, list):
if not isinstance(self.method_data[method]['types'], list):
raise InvalidParamsError(
'expected keyword params, not positional')
for param, type, posnum in zip(params,
self.method_data[method]['types'],
range(1, len(params)+1)):
if not (isinstance(param, type) or param is None):
raise InvalidParamsError(
'positional arg #{} is the wrong type'.format(posnum))
elif isinstance(params, dict):
if not isinstance(self.method_data[method]['types'], dict):
raise InvalidParamsError(
'expected positional params, not keyword')
if 'required' in self.method_data[method]:
for key in self.method_data[method]['required']:
if key not in params:
raise InvalidParamsError('missing key: %s' % key)
for key in params.keys():
if key not in self.method_data[method]['types'] or \
not (isinstance(params[key],
self.method_data[method]['types'][key])
or params[key] is None):
raise InvalidParamsError(
'arg "{}" is the wrong type'.format(key))
|
flowroute/txjason
|
txjason/service.py
|
JSONRPCService._handle_request
|
python
|
def _handle_request(self, request):
if 'types' in self.method_data[request['method']]:
self._validate_params_types(request['method'], request['params'])
if self.serve_exception:
raise self.serve_exception()
d = self._call_method(request)
self.pending.add(d)
if self.timeout:
timeout_deferred = self.reactor.callLater(self.timeout, d.cancel)
def completed(result):
if timeout_deferred.active():
# cancel the timeout_deferred if it has not been fired yet
# this is to prevent d's deferred chain from firing twice
# (and raising an exception).
timeout_deferred.cancel()
return result
d.addBoth(completed)
try:
result = yield d
except defer.CancelledError:
# The request was cancelled due to a timeout or by cancelPending
# having been called. We return a TimeoutError to the client.
self._remove_pending(d)
raise TimeoutError()
except Exception as e:
self._remove_pending(d)
raise e
self._remove_pending(d)
# Do not respond to notifications.
if request['id'] is None:
defer.returnValue(None)
respond = {}
self._fill_ver(request['jsonrpc'], respond)
respond['result'] = result
respond['id'] = request['id']
defer.returnValue(respond)
|
Handles given request and returns its response.
|
train
|
https://github.com/flowroute/txjason/blob/4865bd716847dcbab99acc69daa0c44ae3cc5b89/txjason/service.py#L465-L505
| null |
class JSONRPCService(object):
"""
The JSONRPCService class is a JSON-RPC
"""
def __init__(self, timeout=None, reactor=reactor):
self.method_data = {}
self.serve_exception = None
self.out_of_service_deferred = None
self.pending = set()
self.timeout = timeout
self.reactor = reactor
def add(self, f, name=None, types=None, required=None):
"""
Adds a new method to the jsonrpc service.
Arguments:
f -- the remote function
name -- name of the method in the jsonrpc service
types -- list or dictionary of the types of accepted arguments
required -- list of required keyword arguments
If name argument is not given, function's own name will be used.
Argument types must be a list if positional arguments are used or a
dictionary if keyword arguments are used in the method in question.
Argument required MUST be used only for methods requiring keyword
arguments, not for methods accepting positional arguments.
"""
if name is None:
fname = f.__name__ # Register the function using its own name.
else:
fname = name
self.method_data[fname] = {'method': f}
if types is not None:
self.method_data[fname]['types'] = types
if required is not None:
self.method_data[fname]['required'] = required
def stopServing(self, exception=None):
"""
Returns a deferred that will fire immediately if there are
no pending requests, otherwise when the last request is removed
from self.pending.
"""
if exception is None:
exception = ServiceUnavailableError
self.serve_exception = exception
if self.pending:
d = self.out_of_service_deferred = defer.Deferred()
return d
return defer.succeed(None)
def startServing(self):
self.serve_exception = None
self.out_of_service_deferred = None
def cancelPending(self):
pending = self.pending.copy()
for i in pending:
i.cancel()
@defer.inlineCallbacks
def call(self, jsondata):
"""
Calls jsonrpc service's method and returns its return value in a JSON
string or None if there is none.
Arguments:
jsondata -- remote method call in jsonrpc format
"""
result = yield self.call_py(jsondata)
if result is None:
defer.returnValue(None)
else:
defer.returnValue(json.dumps(result))
@defer.inlineCallbacks
def call_py(self, jsondata):
"""
Calls jsonrpc service's method and returns its return value in python
object format or None if there is none.
This method is same as call() except the return value is a python
object instead of JSON string. This method is mainly only useful for
debugging purposes.
"""
try:
try:
rdata = json.loads(jsondata)
except ValueError:
raise ParseError
except ParseError, e:
defer.returnValue(self._get_err(e))
return
# set some default values for error handling
request = self._get_default_vals()
try:
if isinstance(rdata, dict) and rdata:
# It's a single request.
self._fill_request(request, rdata)
respond = yield self._handle_request(request)
# Don't respond to notifications
if respond is None:
defer.returnValue(None)
else:
defer.returnValue(respond)
return
elif isinstance(rdata, list) and rdata:
# It's a batch.
requests = []
responds = []
for rdata_ in rdata:
# set some default values for error handling
request_ = self._get_default_vals()
try:
self._fill_request(request_, rdata_)
except InvalidRequestError, e:
err = self._get_err(e, request_['id'])
if err:
responds.append(err)
continue
except JSONRPCError, e:
err = self._get_err(e, request_['id'])
if err:
responds.append(err)
continue
requests.append(request_)
for request_ in requests:
try:
# TODO: We should use a deferred list so requests
# are processed in parallel
respond = yield self._handle_request(request_)
except JSONRPCError, e:
respond = self._get_err(e,
request_['id'],
request_['jsonrpc'])
# Don't respond to notifications
if respond is not None:
responds.append(respond)
if responds:
defer.returnValue(responds)
return
# Nothing to respond.
defer.returnValue(None)
return
else:
# empty dict, list or wrong type
raise InvalidRequestError
except InvalidRequestError, e:
defer.returnValue(self._get_err(e, request['id']))
except JSONRPCError, e:
defer.returnValue(self._get_err(e,
request['id'],
request['jsonrpc']))
def _get_err(self, e, id=None, jsonrpc=DEFAULT_JSONRPC):
"""
Returns jsonrpc error message.
"""
# Do not respond to notifications when the request is valid.
if not id \
and not isinstance(e, ParseError) \
and not isinstance(e, InvalidRequestError):
return None
respond = {'id': id}
if isinstance(jsonrpc, int):
# v1.0 requires result to exist always.
# No error codes are defined in v1.0 so only use the message.
if jsonrpc == 10:
respond['result'] = None
respond['error'] = e.dumps()['message']
else:
self._fill_ver(jsonrpc, respond)
respond['error'] = e.dumps()
else:
respond['jsonrpc'] = jsonrpc
respond['error'] = e.dumps()
return respond
def _fill_ver(self, iver, respond):
"""
Fills version information to the respond from the internal integer
version.
"""
if iver == 20:
respond['jsonrpc'] = '2.0'
if iver == 11:
respond['version'] = '1.1'
def _vargs(self, f):
"""
Returns True if given function accepts variadic positional arguments,
otherwise False.
"""
if f.func_code.co_flags & 4:
return True
return False
def _man_args(self, f):
"""
Returns number of mandatory arguments required by given function.
"""
argcount = f.func_code.co_argcount
# account for "self" getting passed to class instance methods
if isinstance(f, types.MethodType):
argcount -= 1
if f.func_defaults is None:
return argcount
return argcount - len(f.func_defaults)
def _max_args(self, f):
"""
Returns maximum number of arguments accepted by given function.
"""
if f.func_defaults is None:
return f.func_code.co_argcount
return f.func_code.co_argcount + len(f.func_defaults)
def _get_jsonrpc(self, rdata):
"""
Returns jsonrpc request's jsonrpc value.
InvalidRequestError will be raised if the jsonrpc value has invalid
value.
"""
if 'jsonrpc' in rdata:
if rdata['jsonrpc'] == '2.0':
return 20
else:
# invalid version
raise InvalidRequestError
else:
# It's probably a JSON-RPC v1.x style call.
if 'version' in rdata:
if rdata['version'] == '1.1':
return 11
# Assume v1.0.
return 10
def _get_id(self, rdata):
"""
Returns jsonrpc request's id value or None if there is none.
InvalidRequestError will be raised if the id value has invalid type.
"""
if 'id' in rdata:
if isinstance(rdata['id'], basestring) or \
isinstance(rdata['id'], int) or \
isinstance(rdata['id'], long) or \
isinstance(rdata['id'], float) or \
rdata['id'] is None:
return rdata['id']
else:
# invalid type
raise InvalidRequestError
else:
# It's a notification.
return None
def _get_method(self, rdata):
"""
Returns jsonrpc request's method value.
InvalidRequestError will be raised if it's missing or is wrong type.
MethodNotFoundError will be raised if a method with given method name
does not exist.
"""
if 'method' in rdata:
if not isinstance(rdata['method'], basestring):
raise InvalidRequestError
else:
raise InvalidRequestError
if rdata['method'] not in self.method_data.keys():
raise MethodNotFoundError
return rdata['method']
def _get_params(self, rdata):
"""
Returns a list of jsonrpc request's method parameters.
"""
if 'params' in rdata:
if isinstance(rdata['params'], dict) \
or isinstance(rdata['params'], list) \
or rdata['params'] is None:
return rdata['params']
else:
# wrong type
raise InvalidRequestError
else:
return None
def _fill_request(self, request, rdata):
"""Fills request with data from the jsonrpc call."""
if not isinstance(rdata, dict):
raise InvalidRequestError
request['jsonrpc'] = self._get_jsonrpc(rdata)
request['id'] = self._get_id(rdata)
request['method'] = self._get_method(rdata)
request['params'] = self._get_params(rdata)
@defer.inlineCallbacks
def _call_method(self, request):
"""Calls given method with given params and returns it value."""
method = self.method_data[request['method']]['method']
params = request['params']
result = None
try:
if isinstance(params, list):
# Does it have enough arguments?
if len(params) < self._man_args(method):
raise InvalidParamsError('not enough arguments')
# Does it have too many arguments?
if not self._vargs(method) \
and len(params) > self._max_args(method):
raise InvalidParamsError('too many arguments')
result = yield defer.maybeDeferred(method, *params)
elif isinstance(params, dict):
# Do not accept keyword arguments if the jsonrpc version is
# not >=1.1.
if request['jsonrpc'] < 11:
raise KeywordError
result = yield defer.maybeDeferred(method, **params)
else: # No params
result = yield defer.maybeDeferred(method)
except JSONRPCError:
raise
except Exception:
# Exception was raised inside the method.
log.msg('Exception raised while invoking RPC method "{}".'.format(
request['method']))
log.err()
raise ServerError
defer.returnValue(result)
def _remove_pending(self, d):
self.pending.remove(d)
if self.out_of_service_deferred and not self.pending:
self.out_of_service_deferred.callback(None)
@defer.inlineCallbacks
def _get_default_vals(self):
"""
Returns dictionary containing default jsonrpc request/responds values
for error handling purposes.
"""
return {"jsonrpc": DEFAULT_JSONRPC, "id": None}
def _validate_params_types(self, method, params):
"""
Validates request's parameter types.
"""
if isinstance(params, list):
if not isinstance(self.method_data[method]['types'], list):
raise InvalidParamsError(
'expected keyword params, not positional')
for param, type, posnum in zip(params,
self.method_data[method]['types'],
range(1, len(params)+1)):
if not (isinstance(param, type) or param is None):
raise InvalidParamsError(
'positional arg #{} is the wrong type'.format(posnum))
elif isinstance(params, dict):
if not isinstance(self.method_data[method]['types'], dict):
raise InvalidParamsError(
'expected positional params, not keyword')
if 'required' in self.method_data[method]:
for key in self.method_data[method]['required']:
if key not in params:
raise InvalidParamsError('missing key: %s' % key)
for key in params.keys():
if key not in self.method_data[method]['types'] or \
not (isinstance(params[key],
self.method_data[method]['types'][key])
or params[key] is None):
raise InvalidParamsError(
'arg "{}" is the wrong type'.format(key))
|
flowroute/txjason
|
txjason/service.py
|
JSONRPCService._validate_params_types
|
python
|
def _validate_params_types(self, method, params):
if isinstance(params, list):
if not isinstance(self.method_data[method]['types'], list):
raise InvalidParamsError(
'expected keyword params, not positional')
for param, type, posnum in zip(params,
self.method_data[method]['types'],
range(1, len(params)+1)):
if not (isinstance(param, type) or param is None):
raise InvalidParamsError(
'positional arg #{} is the wrong type'.format(posnum))
elif isinstance(params, dict):
if not isinstance(self.method_data[method]['types'], dict):
raise InvalidParamsError(
'expected positional params, not keyword')
if 'required' in self.method_data[method]:
for key in self.method_data[method]['required']:
if key not in params:
raise InvalidParamsError('missing key: %s' % key)
for key in params.keys():
if key not in self.method_data[method]['types'] or \
not (isinstance(params[key],
self.method_data[method]['types'][key])
or params[key] is None):
raise InvalidParamsError(
'arg "{}" is the wrong type'.format(key))
|
Validates request's parameter types.
|
train
|
https://github.com/flowroute/txjason/blob/4865bd716847dcbab99acc69daa0c44ae3cc5b89/txjason/service.py#L514-L546
| null |
class JSONRPCService(object):
"""
The JSONRPCService class is a JSON-RPC
"""
def __init__(self, timeout=None, reactor=reactor):
self.method_data = {}
self.serve_exception = None
self.out_of_service_deferred = None
self.pending = set()
self.timeout = timeout
self.reactor = reactor
def add(self, f, name=None, types=None, required=None):
"""
Adds a new method to the jsonrpc service.
Arguments:
f -- the remote function
name -- name of the method in the jsonrpc service
types -- list or dictionary of the types of accepted arguments
required -- list of required keyword arguments
If name argument is not given, function's own name will be used.
Argument types must be a list if positional arguments are used or a
dictionary if keyword arguments are used in the method in question.
Argument required MUST be used only for methods requiring keyword
arguments, not for methods accepting positional arguments.
"""
if name is None:
fname = f.__name__ # Register the function using its own name.
else:
fname = name
self.method_data[fname] = {'method': f}
if types is not None:
self.method_data[fname]['types'] = types
if required is not None:
self.method_data[fname]['required'] = required
def stopServing(self, exception=None):
"""
Returns a deferred that will fire immediately if there are
no pending requests, otherwise when the last request is removed
from self.pending.
"""
if exception is None:
exception = ServiceUnavailableError
self.serve_exception = exception
if self.pending:
d = self.out_of_service_deferred = defer.Deferred()
return d
return defer.succeed(None)
def startServing(self):
self.serve_exception = None
self.out_of_service_deferred = None
def cancelPending(self):
pending = self.pending.copy()
for i in pending:
i.cancel()
@defer.inlineCallbacks
def call(self, jsondata):
"""
Calls jsonrpc service's method and returns its return value in a JSON
string or None if there is none.
Arguments:
jsondata -- remote method call in jsonrpc format
"""
result = yield self.call_py(jsondata)
if result is None:
defer.returnValue(None)
else:
defer.returnValue(json.dumps(result))
@defer.inlineCallbacks
def call_py(self, jsondata):
"""
Calls jsonrpc service's method and returns its return value in python
object format or None if there is none.
This method is same as call() except the return value is a python
object instead of JSON string. This method is mainly only useful for
debugging purposes.
"""
try:
try:
rdata = json.loads(jsondata)
except ValueError:
raise ParseError
except ParseError, e:
defer.returnValue(self._get_err(e))
return
# set some default values for error handling
request = self._get_default_vals()
try:
if isinstance(rdata, dict) and rdata:
# It's a single request.
self._fill_request(request, rdata)
respond = yield self._handle_request(request)
# Don't respond to notifications
if respond is None:
defer.returnValue(None)
else:
defer.returnValue(respond)
return
elif isinstance(rdata, list) and rdata:
# It's a batch.
requests = []
responds = []
for rdata_ in rdata:
# set some default values for error handling
request_ = self._get_default_vals()
try:
self._fill_request(request_, rdata_)
except InvalidRequestError, e:
err = self._get_err(e, request_['id'])
if err:
responds.append(err)
continue
except JSONRPCError, e:
err = self._get_err(e, request_['id'])
if err:
responds.append(err)
continue
requests.append(request_)
for request_ in requests:
try:
# TODO: We should use a deferred list so requests
# are processed in parallel
respond = yield self._handle_request(request_)
except JSONRPCError, e:
respond = self._get_err(e,
request_['id'],
request_['jsonrpc'])
# Don't respond to notifications
if respond is not None:
responds.append(respond)
if responds:
defer.returnValue(responds)
return
# Nothing to respond.
defer.returnValue(None)
return
else:
# empty dict, list or wrong type
raise InvalidRequestError
except InvalidRequestError, e:
defer.returnValue(self._get_err(e, request['id']))
except JSONRPCError, e:
defer.returnValue(self._get_err(e,
request['id'],
request['jsonrpc']))
def _get_err(self, e, id=None, jsonrpc=DEFAULT_JSONRPC):
"""
Returns jsonrpc error message.
"""
# Do not respond to notifications when the request is valid.
if not id \
and not isinstance(e, ParseError) \
and not isinstance(e, InvalidRequestError):
return None
respond = {'id': id}
if isinstance(jsonrpc, int):
# v1.0 requires result to exist always.
# No error codes are defined in v1.0 so only use the message.
if jsonrpc == 10:
respond['result'] = None
respond['error'] = e.dumps()['message']
else:
self._fill_ver(jsonrpc, respond)
respond['error'] = e.dumps()
else:
respond['jsonrpc'] = jsonrpc
respond['error'] = e.dumps()
return respond
def _fill_ver(self, iver, respond):
"""
Fills version information to the respond from the internal integer
version.
"""
if iver == 20:
respond['jsonrpc'] = '2.0'
if iver == 11:
respond['version'] = '1.1'
def _vargs(self, f):
"""
Returns True if given function accepts variadic positional arguments,
otherwise False.
"""
if f.func_code.co_flags & 4:
return True
return False
def _man_args(self, f):
"""
Returns number of mandatory arguments required by given function.
"""
argcount = f.func_code.co_argcount
# account for "self" getting passed to class instance methods
if isinstance(f, types.MethodType):
argcount -= 1
if f.func_defaults is None:
return argcount
return argcount - len(f.func_defaults)
def _max_args(self, f):
"""
Returns maximum number of arguments accepted by given function.
"""
if f.func_defaults is None:
return f.func_code.co_argcount
return f.func_code.co_argcount + len(f.func_defaults)
def _get_jsonrpc(self, rdata):
"""
Returns jsonrpc request's jsonrpc value.
InvalidRequestError will be raised if the jsonrpc value has invalid
value.
"""
if 'jsonrpc' in rdata:
if rdata['jsonrpc'] == '2.0':
return 20
else:
# invalid version
raise InvalidRequestError
else:
# It's probably a JSON-RPC v1.x style call.
if 'version' in rdata:
if rdata['version'] == '1.1':
return 11
# Assume v1.0.
return 10
def _get_id(self, rdata):
"""
Returns jsonrpc request's id value or None if there is none.
InvalidRequestError will be raised if the id value has invalid type.
"""
if 'id' in rdata:
if isinstance(rdata['id'], basestring) or \
isinstance(rdata['id'], int) or \
isinstance(rdata['id'], long) or \
isinstance(rdata['id'], float) or \
rdata['id'] is None:
return rdata['id']
else:
# invalid type
raise InvalidRequestError
else:
# It's a notification.
return None
def _get_method(self, rdata):
"""
Returns jsonrpc request's method value.
InvalidRequestError will be raised if it's missing or is wrong type.
MethodNotFoundError will be raised if a method with given method name
does not exist.
"""
if 'method' in rdata:
if not isinstance(rdata['method'], basestring):
raise InvalidRequestError
else:
raise InvalidRequestError
if rdata['method'] not in self.method_data.keys():
raise MethodNotFoundError
return rdata['method']
def _get_params(self, rdata):
"""
Returns a list of jsonrpc request's method parameters.
"""
if 'params' in rdata:
if isinstance(rdata['params'], dict) \
or isinstance(rdata['params'], list) \
or rdata['params'] is None:
return rdata['params']
else:
# wrong type
raise InvalidRequestError
else:
return None
def _fill_request(self, request, rdata):
"""Fills request with data from the jsonrpc call."""
if not isinstance(rdata, dict):
raise InvalidRequestError
request['jsonrpc'] = self._get_jsonrpc(rdata)
request['id'] = self._get_id(rdata)
request['method'] = self._get_method(rdata)
request['params'] = self._get_params(rdata)
@defer.inlineCallbacks
def _call_method(self, request):
"""Calls given method with given params and returns it value."""
method = self.method_data[request['method']]['method']
params = request['params']
result = None
try:
if isinstance(params, list):
# Does it have enough arguments?
if len(params) < self._man_args(method):
raise InvalidParamsError('not enough arguments')
# Does it have too many arguments?
if not self._vargs(method) \
and len(params) > self._max_args(method):
raise InvalidParamsError('too many arguments')
result = yield defer.maybeDeferred(method, *params)
elif isinstance(params, dict):
# Do not accept keyword arguments if the jsonrpc version is
# not >=1.1.
if request['jsonrpc'] < 11:
raise KeywordError
result = yield defer.maybeDeferred(method, **params)
else: # No params
result = yield defer.maybeDeferred(method)
except JSONRPCError:
raise
except Exception:
# Exception was raised inside the method.
log.msg('Exception raised while invoking RPC method "{}".'.format(
request['method']))
log.err()
raise ServerError
defer.returnValue(result)
def _remove_pending(self, d):
self.pending.remove(d)
if self.out_of_service_deferred and not self.pending:
self.out_of_service_deferred.callback(None)
@defer.inlineCallbacks
def _handle_request(self, request):
"""Handles given request and returns its response."""
if 'types' in self.method_data[request['method']]:
self._validate_params_types(request['method'], request['params'])
if self.serve_exception:
raise self.serve_exception()
d = self._call_method(request)
self.pending.add(d)
if self.timeout:
timeout_deferred = self.reactor.callLater(self.timeout, d.cancel)
def completed(result):
if timeout_deferred.active():
# cancel the timeout_deferred if it has not been fired yet
# this is to prevent d's deferred chain from firing twice
# (and raising an exception).
timeout_deferred.cancel()
return result
d.addBoth(completed)
try:
result = yield d
except defer.CancelledError:
# The request was cancelled due to a timeout or by cancelPending
# having been called. We return a TimeoutError to the client.
self._remove_pending(d)
raise TimeoutError()
except Exception as e:
self._remove_pending(d)
raise e
self._remove_pending(d)
# Do not respond to notifications.
if request['id'] is None:
defer.returnValue(None)
respond = {}
self._fill_ver(request['jsonrpc'], respond)
respond['result'] = result
respond['id'] = request['id']
defer.returnValue(respond)
def _get_default_vals(self):
"""
Returns dictionary containing default jsonrpc request/responds values
for error handling purposes.
"""
return {"jsonrpc": DEFAULT_JSONRPC, "id": None}
|
flowroute/txjason
|
txjason/service.py
|
JSONRPCClientService.startService
|
python
|
def startService(self):
self.clientFactory.connect().addErrback(
log.err, 'error starting the JSON-RPC client service %r' % (self,))
service.Service.startService(self)
|
Start the service and connect the JSONRPCClientFactory.
|
train
|
https://github.com/flowroute/txjason/blob/4865bd716847dcbab99acc69daa0c44ae3cc5b89/txjason/service.py#L560-L566
| null |
class JSONRPCClientService(service.Service):
"""
A service that manages a JSONRPCClientFactory.
Starting and stopping this service connects and disconnects the underlying
JSONRPCClientFactory.
"""
def __init__(self, clientFactory):
self.clientFactory = clientFactory
def stopService(self):
"""
Stop the service and disconnect the JSONRPCClientFactory.
"""
self.clientFactory.disconnect()
service.Service.stopService(self)
def callRemote(self, *a, **kw):
"""
Make a callRemote request of the JSONRPCClientFactory.
"""
if not self.running:
return defer.fail(ServiceStopped())
return self.clientFactory.callRemote(*a, **kw)
def notifyRemote(self, *a, **kw):
"""
Make a notifyRemote request of the JSONRPCClientFactory.
"""
if not self.running:
return defer.fail(ServiceStopped())
return self.clientFactory.notifyRemote(*a, **kw)
|
flowroute/txjason
|
txjason/service.py
|
JSONRPCClientService.callRemote
|
python
|
def callRemote(self, *a, **kw):
if not self.running:
return defer.fail(ServiceStopped())
return self.clientFactory.callRemote(*a, **kw)
|
Make a callRemote request of the JSONRPCClientFactory.
|
train
|
https://github.com/flowroute/txjason/blob/4865bd716847dcbab99acc69daa0c44ae3cc5b89/txjason/service.py#L575-L581
| null |
class JSONRPCClientService(service.Service):
"""
A service that manages a JSONRPCClientFactory.
Starting and stopping this service connects and disconnects the underlying
JSONRPCClientFactory.
"""
def __init__(self, clientFactory):
self.clientFactory = clientFactory
def startService(self):
"""
Start the service and connect the JSONRPCClientFactory.
"""
self.clientFactory.connect().addErrback(
log.err, 'error starting the JSON-RPC client service %r' % (self,))
service.Service.startService(self)
def stopService(self):
"""
Stop the service and disconnect the JSONRPCClientFactory.
"""
self.clientFactory.disconnect()
service.Service.stopService(self)
def notifyRemote(self, *a, **kw):
"""
Make a notifyRemote request of the JSONRPCClientFactory.
"""
if not self.running:
return defer.fail(ServiceStopped())
return self.clientFactory.notifyRemote(*a, **kw)
|
flowroute/txjason
|
txjason/service.py
|
JSONRPCError.dumps
|
python
|
def dumps(self):
error = {'code': self.code,
'message': str(self.message)}
if self.data is not None:
error['data'] = self.data
return error
|
Return the Exception data in a format for JSON-RPC.
|
train
|
https://github.com/flowroute/txjason/blob/4865bd716847dcbab99acc69daa0c44ae3cc5b89/txjason/service.py#L615-L624
| null |
class JSONRPCError(Exception):
"""
JSONRPCError class based on the JSON-RPC 2.0 specs.
code - number
message - string
data - object
"""
code = 0
message = None
data = None
def __init__(self, message=None):
"""Setup the Exception and overwrite the default message."""
if message is not None:
self.message = message
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.