desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Original undecorated method.'
| @property
def method(self):
| return self.__method
|
'Expected request type for remote method.'
| @property
def request_type(self):
| if isinstance(self.__request_type, basestring):
self.__request_type = messages.find_definition(self.__request_type, relative_to=sys.modules[self.__method.__module__])
return self.__request_type
|
'Expected response type for remote method.'
| @property
def response_type(self):
| if isinstance(self.__response_type, basestring):
self.__response_type = messages.find_definition(self.__response_type, relative_to=sys.modules[self.__method.__module__])
return self.__response_type
|
'Constructor.
Args:
transport: Underlying transport to communicate with remote service.'
| def __init__(self, transport):
| self.__transport = transport
|
'Transport used to communicate with remote service.'
| @property
def transport(self):
| return self.__transport
|
'Create asynchronous method for Async handler.
Args:
remote: RemoteInfo to create method for.'
| def __new_async_method(cls, remote):
| def async_method(self, *args, **kwargs):
'Asynchronous remote method.\n\n Args:\n self: Instance of StubBase.Async subclass.\n\n Stub methods either take a single positional argument ... |
'Create synchronous method for stub.
Args:
async_method: asynchronous method to delegate calls to.'
| def __new_sync_method(cls, async_method):
| def sync_method(self, *args, **kwargs):
'Synchronous remote method.\n\n Args:\n self: Instance of StubBase.Async subclass.\n args: Tuple (request,):\n request: ... |
'Construct a dictionary of asynchronous methods based on remote methods.
Args:
remote_methods: Dictionary of methods with associated RemoteInfo objects.
Returns:
Dictionary of asynchronous methods with assocaited RemoteInfo objects.
Results added to AsyncStub subclass.'
| def __create_async_methods(cls, remote_methods):
| async_methods = {}
for (method_name, method) in remote_methods.iteritems():
async_methods[method_name] = cls.__new_async_method(method.remote)
return async_methods
|
'Construct a dictionary of synchronous methods based on remote methods.
Args:
async_methods: Dictionary of async methods to delegate calls to.
Returns:
Dictionary of synchronous methods with assocaited RemoteInfo objects.
Results added to Stub subclass.'
| def __create_sync_methods(cls, async_methods):
| sync_methods = {}
for (method_name, async_method) in async_methods.iteritems():
sync_methods[method_name] = cls.__new_sync_method(async_method)
return sync_methods
|
'Instantiate new service class instance.'
| def __new__(cls, name, bases, dct):
| if (StubBase not in bases):
base_methods = {}
for base in bases:
try:
remote_methods = base.__remote_methods
except AttributeError:
pass
else:
base_methods.update(remote_methods)
dct['_ServiceClass__base_meth... |
'Create uninitialized state on new class.'
| def __init__(cls, name, bases, dct):
| type.__init__(cls, name, bases, dct)
if (StubBase not in bases):
cls.__remote_methods = dict(cls.__base_methods)
for (attribute, value) in dct.iteritems():
value = getattr(cls, attribute)
remote_method_info = get_remote_method_info(value)
if remote_method_info... |
'Get all remote methods of service.
Returns:
Dict from method name to unbound method.'
| @staticmethod
def all_remote_methods(cls):
| return dict(cls.__remote_methods)
|
'Constructor.
Args:
remote_host: Assigned to property.
remote_address: Assigned to property.
server_host: Assigned to property.
server_port: Assigned to property.'
| @util.positional(1)
def __init__(self, remote_host=None, remote_address=None, server_host=None, server_port=None):
| self.__remote_host = remote_host
self.__remote_address = remote_address
self.__server_host = server_host
self.__server_port = server_port
|
'String representation of state.'
| def __repr__(self):
| state = [self.__class__.__name__]
for (name, value) in self._repr_items():
if value:
state.append(('%s=%r' % (name, value)))
return ('<%s>' % (' '.join(state),))
|
'Constructor.
Args:
Same as RequestState, including:
http_method: Assigned to property.
service_path: Assigned to property.
headers: HTTP request headers. If instance of Headers, assigned to
property without copying. If dict, will convert to name value pairs
for use with Headers constructor. Otherwise, passed as par... | @util.positional(1)
def __init__(self, http_method=None, service_path=None, headers=None, **kwargs):
| super(HttpRequestState, self).__init__(**kwargs)
self.__http_method = http_method
self.__service_path = service_path
if isinstance(headers, dict):
header_list = []
for (key, value) in sorted(headers.items()):
if (not isinstance(value, list)):
value = [value]
... |
'Get all remote methods for service class.
Built-in methods do not appear in the dictionary of remote methods.
Returns:
Dictionary mapping method name to remote method.'
| @classmethod
def all_remote_methods(cls):
| return _ServiceClass.all_remote_methods(cls)
|
'Create factory for service.
Useful for passing configuration or state objects to the service. Accepts
arbitrary parameters and keywords, however, underlying service must accept
also accept not other parameters in its constructor.
Args:
args: Args to pass to service constructor.
kwargs: Keyword arguments to pass to se... | @classmethod
def new_factory(cls, *args, **kwargs):
| def service_factory():
return cls(*args, **kwargs)
full_class_name = ('%s.%s' % (cls.__module__, cls.__name__))
service_factory.func_doc = ('Creates new instances of service %s.\n\nReturns:\n New instance of %s.' % (cls.__name__, full_class_name))
service_factory.f... |
'Save request state for use in remote method.
Args:
request_state: RequestState instance.'
| def initialize_request_state(self, request_state):
| self.__request_state = request_state
|
'Get definition name for Service class.
Package name is determined by the global \'package\' attribute in the
module that contains the Service definition. If no \'package\' attribute
is available, uses module name. If no module is found, just uses class
name as name.
Returns:
Fully qualified service name.'
| @classmethod
def definition_name(cls):
| try:
return cls.__definition_name
except AttributeError:
outer_definition_name = cls.outer_definition_name()
if (outer_definition_name is None):
cls.__definition_name = cls.__name__
else:
cls.__definition_name = ('%s.%s' % (outer_definition_name, cls.__nam... |
'Get outer definition name.
Returns:
Package for service. Services are never nested inside other definitions.'
| @classmethod
def outer_definition_name(cls):
| return cls.definition_package()
|
'Get package for service.
Returns:
Package name for service.'
| @classmethod
def definition_package(cls):
| try:
return cls.__definition_package
except AttributeError:
cls.__definition_package = util.get_package_for_module(cls.__module__)
return cls.__definition_package
|
'Request state associated with this Service instance.'
| @property
def request_state(self):
| return self.__request_state
|
'Constructor.
Args:
protocol: The protocol implementation for configuration.
name: The name of the protocol configuration.
default_content_type: The default content-type for protocol. If none
provided it will check protocol.CONTENT_TYPE.
alternative_content_types: A list of content-types. If none provided,
it will c... | def __init__(self, protocol, name, default_content_type=None, alternative_content_types=None):
| self.__protocol = protocol
self.__name = name
self.__default_content_type = (default_content_type or protocol.CONTENT_TYPE).lower()
if (alternative_content_types is None):
alternative_content_types = getattr(protocol, 'ALTERNATIVE_CONTENT_TYPES', ())
self.__alternative_content_types = tuple(... |
'Encode message.
Args:
message: Message instance to encode.
Returns:
String encoding of Message instance encoded in protocol\'s format.'
| def encode_message(self, message):
| return self.__protocol.encode_message(message)
|
'Decode buffer to Message instance.
Args:
message_type: Message type to decode data to.
encoded_message: Encoded version of message as string.
Returns:
Decoded instance of message_type.'
| def decode_message(self, message_type, encoded_message):
| return self.__protocol.decode_message(message_type, encoded_message)
|
'Constructor.'
| def __init__(self):
| self.__by_name = {}
self.__by_content_type = {}
|
'Add a protocol configuration to protocol mapping.
Args:
config: A ProtocolConfig.
Raises:
ServiceConfigurationError if protocol.name is already registered
or any of it\'s content-types are already registered.'
| def add_protocol_config(self, config):
| if (config.name in self.__by_name):
raise ServiceConfigurationError(('Protocol name %r is already in use' % config.name))
for content_type in config.content_types:
if (content_type in self.__by_content_type):
raise ServiceConfigurationError(('Content type %r ... |
'Add a protocol configuration from basic parameters.
Simple helper method that creates and registeres a ProtocolConfig instance.'
| def add_protocol(self, *args, **kwargs):
| self.add_protocol_config(ProtocolConfig(*args, **kwargs))
|
'Look up a ProtocolConfig by name.
Args:
name: Name of protocol to look for.
Returns:
ProtocolConfig associated with name.
Raises:
KeyError if there is no protocol for name.'
| def lookup_by_name(self, name):
| return self.__by_name[name.lower()]
|
'Look up a ProtocolConfig by content-type.
Args:
content_type: Content-type to find protocol configuration for.
Returns:
ProtocolConfig associated with content-type.
Raises:
KeyError if there is no protocol for content-type.'
| def lookup_by_content_type(self, content_type):
| return self.__by_content_type[content_type.lower()]
|
'Create default protocols configuration.
Returns:
New Protocols instance configured for protobuf and protorpc.'
| @classmethod
def new_default(cls):
| protocols = cls()
protocols.add_protocol(protobuf, 'protobuf')
protocols.add_protocol(protojson, 'protojson')
return protocols
|
'Get the global default Protocols instance.
Returns:
Current global default Protocols instance.'
| @classmethod
def get_default(cls):
| default_protocols = cls.__default_protocols
if (default_protocols is None):
with cls.__lock:
default_protocols = cls.__default_protocols
if (default_protocols is None):
default_protocols = cls.new_default()
cls.__default_protocols = default_protoco... |
'Set the global default Protocols instance.
Args:
protocols: A Protocols instance.
Raises:
TypeError: If protocols is not an instance of Protocols.'
| @classmethod
def set_default(cls, protocols):
| if (not isinstance(protocols, Protocols)):
raise TypeError(('Expected value of type "Protocols", found %r' % protocols))
with cls.__lock:
cls.__default_protocols = protocols
|
'Return dictionary instance from a message object.
Args:
value: Value to get dictionary for. If not encodable, will
call superclasses default method.'
| def default(self, value):
| if isinstance(value, messages.Enum):
return str(value)
if isinstance(value, messages.Message):
result = {}
for field in value.all_fields():
item = value.get_assigned_value(field.name)
if (item not in (None, [], ())):
if isinstance(field, messages.B... |
'DEPRECATED: please use MessageJSONEncoder instead.'
| def __init__(self, *args, **kwds):
| logging.warning('_MessageJSONEncoder has been renamed to MessageJSONEncoder, please update any references')
super(_MessageJSONEncoder, self).__init__(*args, **kwds)
|
'Prints string with field name if present on exception.'
| def __str__(self):
| message = Error.__str__(self)
try:
field_name = self.field_name
except AttributeError:
return message
else:
return message
|
'Constructor.'
| def __init__(cls, name, bases, dct):
| type.__init__(cls, name, bases, dct)
if (cls.__bases__ != (object,)):
cls.__initialized = True
|
'Get outer Message definition that contains this definition.
Returns:
Containing Message definition if definition is contained within one,
else None.'
| def message_definition(cls):
| try:
return cls._message_definition()
except AttributeError:
return None
|
'Overridden so that cannot set variables on definition classes after init.
Setting attributes on a class must work during the period of initialization
to set the enumation value class variables and build the name/number maps.
Once __init__ has set the __initialized flag to True prohibits setting any
more values on the ... | def __setattr__(cls, name, value):
| if (cls.__initialized and (name not in _POST_INIT_ATTRIBUTE_NAMES)):
raise AttributeError(('May not change values: %s' % name))
else:
type.__setattr__(cls, name, value)
|
'Overridden so that cannot delete varaibles on definition classes.'
| def __delattr__(cls, name):
| raise TypeError('May not delete attributes on definition class')
|
'Helper method for creating definition name.
Names will be generated to include the classes package name, scope (if the
class is nested in another definition) and class name.
By default, the package name for a definition is derived from its module
name. However, this value can be overriden by placing a \'package\' att... | def definition_name(cls):
| outer_definition_name = cls.outer_definition_name()
if (outer_definition_name is None):
return unicode(cls.__name__)
else:
return (u'%s.%s' % (outer_definition_name, cls.__name__))
|
'Helper method for creating outer definition name.
Returns:
If definition is nested, will return the outer definitions name, else the
package name.'
| def outer_definition_name(cls):
| outer_definition = cls.message_definition()
if (not outer_definition):
return util.get_package_for_module(cls.__module__)
else:
return outer_definition.definition_name()
|
'Helper method for creating creating the package of a definition.
Returns:
Name of package that definition belongs to.'
| def definition_package(cls):
| outer_definition = cls.message_definition()
if (not outer_definition):
return util.get_package_for_module(cls.__module__)
else:
return outer_definition.definition_package()
|
'Iterate over all values of enum.
Yields:
Enumeration instances of the Enum class in arbitrary order.'
| def __iter__(cls):
| return cls.__by_number.itervalues()
|
'Get all names for Enum.
Returns:
An iterator for names of the enumeration in arbitrary order.'
| def names(cls):
| return cls.__by_name.iterkeys()
|
'Get all numbers for Enum.
Returns:
An iterator for all numbers of the enumeration in arbitrary order.'
| def numbers(cls):
| return cls.__by_number.iterkeys()
|
'Look up Enum by name.
Args:
name: Name of enum to find.
Returns:
Enum sub-class instance of that value.'
| def lookup_by_name(cls, name):
| return cls.__by_name[name]
|
'Look up Enum by number.
Args:
number: Number of enum to find.
Returns:
Enum sub-class instance of that value.'
| def lookup_by_number(cls, number):
| return cls.__by_number[number]
|
'Acts as look-up routine after class is initialized.
The purpose of overriding __new__ is to provide a way to treat
Enum subclasses as casting types, similar to how the int type
functions. A program can pass a string or an integer and this
method with "convert" that value in to an appropriate Enum instance.
Args:
inde... | def __new__(cls, index):
| if isinstance(index, cls):
return index
if isinstance(index, (int, long)):
try:
return cls.lookup_by_number(index)
except KeyError:
pass
if isinstance(index, basestring):
try:
return cls.lookup_by_name(index)
except KeyError:
... |
'Initialize new Enum instance.
Since this should only be called during class initialization any
calls that happen after the class is frozen raises an exception.'
| def __init__(self, name, number=None):
| if getattr(type(self), '_DefinitionClass__initialized'):
return
object.__setattr__(self, 'name', name)
object.__setattr__(self, 'number', number)
|
'Order is by number.'
| def __cmp__(self, other):
| if isinstance(other, type(self)):
return cmp(self.number, other.number)
return NotImplemented
|
'Make dictionary version of enumerated class.
Dictionary created this way can be used with def_num.
Returns:
A dict (name) -> number'
| @classmethod
def to_dict(cls):
| return dict(((item.name, item.number) for item in iter(cls)))
|
'Define enum class from dictionary.
Args:
dct: Dictionary of enumerated values for type.
name: Name of enum.'
| @staticmethod
def def_enum(dct, name):
| return type(name, (Enum,), dct)
|
'Create new Message class instance.
The __new__ method of the _MessageClass type is overridden so as to
allow the translation of Field instances to slots.'
| def __new__(cls, name, bases, dct):
| by_number = {}
by_name = {}
variant_map = {}
if (bases != (object,)):
if (bases != (Message,)):
raise MessageDefinitionError('Message types may only inherit from Message')
enums = []
messages = []
for (key, field) in dct.items():
... |
'Initializer required to assign references to new class.'
| def __init__(cls, name, bases, dct):
| if (bases != (object,)):
for value in dct.itervalues():
if (isinstance(value, _DefinitionClass) and (not (value is Message))):
value._message_definition = weakref.ref(cls)
for field in cls.all_fields():
field._message_definition = weakref.ref(cls)
_Definit... |
'Initialize internal messages state.
Args:
A message can be initialized via the constructor by passing in keyword
arguments corresponding to fields. For example:
class Date(Message):
day = IntegerField(1)
month = IntegerField(2)
year = IntegerField(3)
Invoking:
date = Date(day=6, month=6, year=1911)
is the same as doi... | def __init__(self, **kwargs):
| self.__tags = {}
self.__unrecognized_fields = {}
assigned = set()
for (name, value) in kwargs.iteritems():
setattr(self, name, value)
assigned.add(name)
for field in self.all_fields():
if (field.repeated and (field.name not in assigned)):
setattr(self, field.name,... |
'Check class for initialization status.
Check that all required fields are initialized
Raises:
ValidationError: If message is not initialized.'
| def check_initialized(self):
| for (name, field) in self.__by_name.iteritems():
value = getattr(self, name)
if (value is None):
if field.required:
raise ValidationError(('Message %s is missing required field %s' % (type(self).__name__, name)))
else:
try:
... |
'Get initialization status.
Returns:
True if message is valid, else False.'
| def is_initialized(self):
| try:
self.check_initialized()
except ValidationError:
return False
else:
return True
|
'Get all field definition objects.
Ordering is arbitrary.
Returns:
Iterator over all values in arbitrary order.'
| @classmethod
def all_fields(cls):
| return cls.__by_name.itervalues()
|
'Get field by name.
Returns:
Field object associated with name.
Raises:
KeyError if no field found by that name.'
| @classmethod
def field_by_name(cls, name):
| return cls.__by_name[name]
|
'Get field by number.
Returns:
Field object associated with number.
Raises:
KeyError if no field found by that number.'
| @classmethod
def field_by_number(cls, number):
| return cls.__by_number[number]
|
'Get the assigned value of an attribute.
Get the underlying value of an attribute. If value has not been set, will
not return the default for the field.
Args:
name: Name of attribute to get.
Returns:
Value of attribute, None if it has not been set.'
| def get_assigned_value(self, name):
| message_type = type(self)
try:
field = message_type.field_by_name(name)
except KeyError:
raise AttributeError(('Message %s has no field %s' % (message_type.__name__, name)))
return self.__tags.get(field.number)
|
'Reset assigned value for field.
Resetting a field will return it to its default value or None.
Args:
name: Name of field to reset.'
| def reset(self, name):
| message_type = type(self)
try:
field = message_type.field_by_name(name)
except KeyError:
if (name not in message_type.__by_name):
raise AttributeError(('Message %s has no field %s' % (message_type.__name__, name)))
self.__tags.pop(field.number, None)
|
'Get the names of all unrecognized fields in this message.'
| def all_unrecognized_fields(self):
| return self.__unrecognized_fields.keys()
|
'Get the value and variant of an unknown field in this message.
Args:
key: The name or number of the field to retrieve.
value_default: Value to be returned if the key isn\'t found.
variant_default: Value to be returned as variant if the key isn\'t
found.
Returns:
(value, variant), where value and variant are whatever w... | def get_unrecognized_field_info(self, key, value_default=None, variant_default=None):
| (value, variant) = self.__unrecognized_fields.get(key, (value_default, variant_default))
return (value, variant)
|
'Set an unrecognized field, used when decoding a message.
Args:
key: The name or number used to refer to this unknown value.
value: The value of the field.
variant: Type information needed to interpret the value or re-encode it.
Raises:
TypeError: If the variant is not an instance of messages.Variant.'
| def set_unrecognized_field(self, key, value, variant):
| if (not isinstance(variant, Variant)):
raise TypeError(('Variant type %s is not valid.' % variant))
self.__unrecognized_fields[key] = (value, variant)
|
'Change set behavior for messages.
Messages may only be assigned values that are fields.
Does not try to validate field when set.
Args:
name: Name of field to assign to.
vlaue: Value to assign to field.
Raises:
AttributeError when trying to assign value that is not a field.'
| def __setattr__(self, name, value):
| if ((name in self.__by_name) or name.startswith('_Message__')):
object.__setattr__(self, name, value)
else:
raise AttributeError(('May not assign arbitrary value %s to message %s' % (name, type(self).__name__)))
|
'Make string representation of message.
Example:
class MyMessage(messages.Message):
integer_value = messages.IntegerField(1)
string_value = messages.StringField(2)
my_message = MyMessage()
my_message.integer_value = 42
my_message.string_value = u\'A string\'
print my_message
>>> <MyMessage
... integer_value: 42
... s... | def __repr__(self):
| body = ['<', type(self).__name__]
for field in sorted(self.all_fields(), key=(lambda f: f.number)):
attribute = field.name
value = self.get_assigned_value(field.name)
if (value is not None):
body.append(('\n %s: %s' % (attribute, repr(value))))
body.append('>')
... |
'Equality operator.
Does field by field comparison with other message. For
equality, must be same type and values of all fields must be
equal.
Messages not required to be initialized for comparison.
Does not attempt to determine equality for values that have
default values that are not set. In other words:
class HasD... | def __eq__(self, other):
| if (self is other):
return True
if (type(self) is not type(other)):
return False
return (self.__tags == other.__tags)
|
'Not equals operator.
Does field by field comparison with other message. For
non-equality, must be different type or any value of a field must be
non-equal to the same field in the other instance.
Messages not required to be initialized for comparison.
Args:
other: Other message to compare with.'
| def __ne__(self, other):
| return (not self.__eq__(other))
|
'Constructor.
Args:
field_instance: Instance of field that validates the list.
sequence: List or tuple to construct list from.'
| def __init__(self, field_instance, sequence):
| if (not field_instance.repeated):
raise FieldDefinitionError('FieldList may only accept repeated fields')
self.__field = field_instance
self.__field.validate(sequence)
list.__init__(self, sequence)
|
'Field that validates list.'
| @property
def field(self):
| return self.__field
|
'Validate slice assignment to list.'
| def __setslice__(self, i, j, sequence):
| self.__field.validate(sequence)
list.__setslice__(self, i, j, sequence)
|
'Validate item assignment to list.'
| def __setitem__(self, index, value):
| self.__field.validate_element(value)
list.__setitem__(self, index, value)
|
'Validate item appending to list.'
| def append(self, value):
| self.__field.validate_element(value)
return list.append(self, value)
|
'Validate extension of list.'
| def extend(self, sequence):
| self.__field.validate(sequence)
return list.extend(self, sequence)
|
'Validate item insertion to list.'
| def insert(self, index, value):
| self.__field.validate_element(value)
return list.insert(self, index, value)
|
'Constructor.
The required and repeated parameters are mutually exclusive. Setting both
to True will raise a FieldDefinitionError.
Sub-class Attributes:
Each sub-class of Field must define the following:
VARIANTS: Set of variant types accepted by that field.
DEFAULT_VARIANT: Default variant type if not specified in co... | @util.positional(2)
def __init__(self, number, required=False, repeated=False, variant=None, default=None):
| if ((not isinstance(number, int)) or (not (1 <= number <= MAX_FIELD_NUMBER))):
raise InvalidNumberError(('Invalid number for field: %s\nNumber must be 1 or greater and %d or less' % (number, MAX_FIELD_NUMBER)))
if (FIRST_RESERVED_FIELD_NUMBER <= number <= LAST_RESE... |
'Setter overidden to prevent assignment to fields after creation.
Args:
name: Name of attribute to set.
value: Value to assign.'
| def __setattr__(self, name, value):
| if (name in _POST_INIT_FIELD_ATTRIBUTE_NAMES):
object.__setattr__(self, name, value)
return
if (not self.__initialized):
object.__setattr__(self, name, value)
else:
raise AttributeError('Field objects are read-only')
|
'Set value on message.
Args:
message_instance: Message instance to set value on.
value: Value to set on message.'
| def __set__(self, message_instance, value):
| if (value is None):
if self.repeated:
raise ValidationError(('May not assign None to repeated field %s' % self.name))
else:
message_instance._Message__tags.pop(self.number, None)
else:
if self.repeated:
value = FieldList(self, valu... |
'Validate single element of field.
This is different from validate in that it is used on individual
values of repeated fields.
Args:
value: Value to validate.
Raises:
ValidationError if value is not expected type.'
| def validate_element(self, value):
| if (not isinstance(value, self.type)):
if (value is None):
if self.required:
raise ValidationError('Required field is missing')
else:
try:
name = self.name
except AttributeError:
raise ValidationError(('Expe... |
'Internal validation function.
Validate an internal value using a function to validate individual elements.
Args:
value: Value to validate.
validate_element: Function to use to validate individual elements.
Raises:
ValidationError if value is not expected type.'
| def __validate(self, value, validate_element):
| if (not self.repeated):
validate_element(value)
elif isinstance(value, (list, tuple)):
for element in value:
if (element is None):
try:
name = self.name
except AttributeError:
raise ValidationError(('Repeated ... |
'Validate value assigned to field.
Args:
value: Value to validate.
Raises:
ValidationError if value is not expected type.'
| def validate(self, value):
| self.__validate(value, self.validate_element)
|
'Validate value as assigned to field default field.
Some fields may allow for delayed resolution of default types necessary
in the case of circular definition references. In this case, the default
value might be a place holder that is resolved when needed after all the
message classes are defined.
Args:
value: Default... | def validate_default_element(self, value):
| self.validate_element(value)
|
'Validate default value assigned to field.
Args:
value: Value to validate.
Raises:
ValidationError if value is not expected type.'
| def validate_default(self, value):
| self.__validate(value, self.validate_default_element)
|
'Get Message definition that contains this Field definition.
Returns:
Containing Message definition for Field. Will return None if for
some reason Field is defined outside of a Message class.'
| def message_definition(self):
| try:
return self._message_definition()
except AttributeError:
return None
|
'Get default value for field.'
| @property
def default(self):
| return self.__default
|
'Validate StringField allowing for str and unicode.
Raises:
ValidationError if a str value is not 7-bit ascii.'
| def validate_element(self, value):
| if isinstance(value, str):
try:
unicode(value)
except UnicodeDecodeError as err:
try:
name = self.name
except AttributeError:
validation_error = ValidationError(('Field encountered non-ASCII string %s: %s' % (value, e... |
'Constructor.
Args:
message_type: Message type for field. Must be subclass of Message.
number: Number of field. Must be unique per message class.
required: Whether or not field is required. Mutually exclusive to
\'repeated\'.
repeated: Whether or not field is repeated. Mutually exclusive to
\'required\'.
variant: W... | @util.positional(3)
def __init__(self, message_type, number, required=False, repeated=False, variant=None):
| valid_type = (isinstance(message_type, basestring) or ((message_type is not Message) and isinstance(message_type, type) and issubclass(message_type, Message)))
if (not valid_type):
raise FieldDefinitionError(('Invalid message class: %s' % message_type))
if isinstance(message_type, basestrin... |
'Message type used for field.'
| @property
def type(self):
| if (self.__type is None):
message_type = find_definition(self.__type_name, self.message_definition())
if (not ((message_type is not Message) and isinstance(message_type, type) and issubclass(message_type, Message))):
raise FieldDefinitionError(('Invalid message class: %s' % mess... |
'Underlying message type used for serialization.
Will always be a sub-class of Message. This is different from type
which represents the python value that message_type is mapped to for
use by the user.'
| @property
def message_type(self):
| return self.type
|
'Convert a message to a value instance.
Used by deserializers to convert from underlying messages to
value of expected user type.
Args:
message: A message instance of type self.message_type.
Returns:
Value of self.type.'
| def value_from_message(self, message):
| if (not isinstance(message, self.message_type)):
raise DecodeError(('Expected type %s, got %s: %r' % (self.message_type.__name__, type(message).__name__, message)))
return message
|
'Convert a value instance to a message.
Used by serializers to convert Python user types to underlying
messages for transmission.
Args:
value: A value of type self.type.
Returns:
An instance of type self.message_type.'
| def value_to_message(self, value):
| if (not isinstance(value, self.type)):
raise EncodeError(('Expected type %s, got %s: %r' % (self.type.__name__, type(value).__name__, value)))
return value
|
'Constructor.
Args:
enum_type: Enum type for field. Must be subclass of Enum.
number: Number of field. Must be unique per message class.
required: Whether or not field is required. Mutually exclusive to
\'repeated\'.
repeated: Whether or not field is repeated. Mutually exclusive to
\'required\'.
variant: Wire-forma... | def __init__(self, enum_type, number, **kwargs):
| valid_type = (isinstance(enum_type, basestring) or ((enum_type is not Enum) and isinstance(enum_type, type) and issubclass(enum_type, Enum)))
if (not valid_type):
raise FieldDefinitionError(('Invalid enum type: %s' % enum_type))
if isinstance(enum_type, basestring):
self.__type_name... |
'Validate default element of Enum field.
Enum fields allow for delayed resolution of default values when the type
of the field has not been resolved. The default value of a field may be
a string or an integer. If the Enum type of the field has been resolved,
the default value is validated against that type.
Args:
val... | def validate_default_element(self, value):
| if isinstance(value, (basestring, int, long)):
if self.__type:
self.__type(value)
return
super(EnumField, self).validate_default_element(value)
|
'Enum type used for field.'
| @property
def type(self):
| if (self.__type is None):
found_type = find_definition(self.__type_name, self.message_definition())
if (not ((found_type is not Enum) and isinstance(found_type, type) and issubclass(found_type, Enum))):
raise FieldDefinitionError(('Invalid enum type: %s' % found_type))
s... |
'Default for enum field.
Will cause resolution of Enum type and unresolved default value.'
| @property
def default(self):
| try:
return self.__resolved_default
except AttributeError:
resolved_default = super(EnumField, self).default
if isinstance(resolved_default, (basestring, int, long)):
resolved_default = self.type(resolved_default)
self.__resolved_default = resolved_default
ret... |
'Convert DateTimeMessage to a datetime.
Args:
A DateTimeMessage instance.
Returns:
A datetime instance.'
| def value_from_message(self, message):
| message = super(DateTimeField, self).value_from_message(message)
if (message.time_zone_offset is None):
return datetime.datetime.utcfromtimestamp((message.milliseconds / 1000.0))
milliseconds = (message.milliseconds - (60000 * message.time_zone_offset))
timezone = util.TimeZoneOffset(message.tim... |
'Constructor.
Args:
message: Message instance to build from parameters.
prefix: Prefix expected at the start of valid parameters.'
| @util.positional(2)
def __init__(self, message, prefix=''):
| self.__parameter_prefix = prefix
self.__messages = {(): message}
self.__checked_indexes = set([()])
|
'Parse a parameter name and build a full path to a message value.
The path of a method is a tuple of 2-tuples describing the names and
indexes within repeated fields from the root message (the message being
constructed by the builder) to an arbitrarily nested message within it.
Each 2-tuple node of a path (name, index)... | def make_path(self, parameter_name):
| if parameter_name.startswith(self.__parameter_prefix):
parameter_name = parameter_name[len(self.__parameter_prefix):]
else:
return None
path = []
name = []
message_type = type(self.__messages[()])
for item in parameter_name.split('.'):
if (not message_type):
r... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.