desc
stringlengths 3
26.7k
| decl
stringlengths 11
7.89k
| bodies
stringlengths 8
553k
|
---|---|---|
'Check correct index use and value relative to a given path.
Check that for a given path the index is present for repeated fields
and that it is in range for the existing list that it will be inserted
in to or appended to.
Args:
parent_path: Path to check against name and index.
name: Name of field to check for existance.
index: Index to check. If field is repeated, should be a number within
range of the length of the field, or point to the next item for
appending.'
| def __check_index(self, parent_path, name, index):
| if (not index):
return True
parent = self.__messages.get(parent_path, None)
value_list = getattr(parent, name, None)
if (not value_list):
return False
return (len(value_list) >= index)
|
'Check that all indexes are valid and in the right order.
This method must iterate over the path and check that all references
to indexes point to an existing message or to the end of the list, meaning
the next value should be appended to the repeated field.
Args:
path: Path to check indexes for. Tuple of 2-tuples (name, index). See
make_path for more information.
Returns:
True if all the indexes of the path are within range, else False.'
| def __check_indexes(self, path):
| if (path in self.__checked_indexes):
return True
parent_path = ()
for (name, index) in path:
next_path = (parent_path + ((name, index),))
if (next_path not in self.__checked_indexes):
if (not self.__check_index(parent_path, name, index)):
return False
self.__checked_indexes.add(next_path)
parent_path = next_path
return True
|
'Get a message from the messages cache or create it and add it.
This method will also create any parent messages based on the path.
When a new instance of a given message is created, it is stored in
__message by its path.
Args:
path: Path of message to get. Path must be valid, in other words
__check_index(path) returns true. Tuple of 2-tuples (name, index).
See make_path for more information.
Returns:
Message instance if the field being pointed to by the path is a
message, else will return None for non-message fields.'
| def __get_or_create_path(self, path):
| message = self.__messages.get(path, None)
if message:
return message
parent_path = ()
parent = self.__messages[()]
for (name, index) in path:
field = parent.field_by_name(name)
next_path = (parent_path + ((name, index),))
next_message = self.__messages.get(next_path, None)
if (next_message is None):
message_type = field.type
next_message = message_type()
self.__messages[next_path] = next_message
if (not field.repeated):
setattr(parent, field.name, next_message)
else:
list_value = getattr(parent, field.name, None)
if (list_value is None):
setattr(parent, field.name, [next_message])
else:
list_value.append(next_message)
parent_path = next_path
parent = next_message
return parent
|
'Add a single parameter.
Adds a single parameter and its value to the request message.
Args:
parameter: Query string parameter to map to request.
values: List of values to assign to request message.
Returns:
True if parameter was valid and added to the message, else False.
Raises:
DecodeError if the parameter refers to a valid field, and the values
parameter does not have one and only one value. Non-valid query
parameters may have multiple values and should not cause an error.'
| def add_parameter(self, parameter, values):
| path = self.make_path(parameter)
if (not path):
return False
if (not self.__check_indexes(path)):
return False
parent_path = path[:(-1)]
parent = self.__get_or_create_path(parent_path)
(name, index) = path[(-1)]
field = parent.field_by_name(name)
if (len(values) != 1):
raise messages.DecodeError(('Found repeated values for field %s.' % field.name))
value = values[0]
if isinstance(field, messages.IntegerField):
converted_value = int(value)
elif isinstance(field, message_types.DateTimeField):
try:
converted_value = util.decode_datetime(value)
except ValueError as e:
raise messages.DecodeError(e)
elif isinstance(field, messages.MessageField):
self.__get_or_create_path(path)
return True
elif isinstance(field, messages.StringField):
converted_value = value.decode('utf-8')
elif isinstance(field, messages.BooleanField):
converted_value = (((value.lower() == 'true') and True) or False)
else:
try:
converted_value = field.type(value)
except TypeError:
raise messages.DecodeError(('Invalid enum value "%s"' % value))
if field.repeated:
value_list = getattr(parent, field.name, None)
if (value_list is None):
setattr(parent, field.name, [converted_value])
elif (index == len(value_list)):
value_list.append(converted_value)
else:
value_list[index] = converted_value
else:
setattr(parent, field.name, converted_value)
return True
|
'Constructor.
Args:
http_methods: Set of HTTP methods supported by mapper.
default_content_type: Default content type supported by mapper.
protocol: The protocol implementation. Must implement encode_message and
decode_message.
content_types: Set of additionally supported content types.'
| @util.positional(4)
def __init__(self, http_methods, default_content_type, protocol, content_types=None):
| self.__http_methods = frozenset(http_methods)
self.__default_content_type = default_content_type
self.__protocol = protocol
if (content_types is None):
content_types = []
self.__content_types = frozenset(([self.__default_content_type] + content_types))
|
'Build request message based on request.
Each request mapper implementation is responsible for converting a
request to an appropriate message instance.
Args:
handler: RequestHandler instance that is servicing request.
Must be initialized with request object and been previously determined
to matching the protocol of the RPCMapper.
request_type: Message type to build.
Returns:
Instance of request_type populated by protocol buffer in request body.
Raises:
RequestError if the mapper implementation is not able to correctly
convert the request to the appropriate message.'
| def build_request(self, handler, request_type):
| try:
return self.__protocol.decode_message(request_type, handler.request.body)
except (messages.ValidationError, messages.DecodeError) as err:
raise RequestError(('Unable to parse request content: %s' % err))
|
'Build response based on service object response message.
Each request mapper implementation is responsible for converting a
response message to an appropriate handler response.
Args:
handler: RequestHandler instance that is servicing request.
Must be initialized with request object and been previously determined
to matching the protocol of the RPCMapper.
response: Response message as returned from the service object.
Raises:
ResponseError if the mapper implementation is not able to correctly
convert the message to an appropriate response.'
| def build_response(self, handler, response, pad_string=False):
| try:
encoded_message = self.__protocol.encode_message(response)
except messages.ValidationError as err:
raise ResponseError(('Unable to encode message: %s' % err))
else:
handler.response.headers['Content-Type'] = self.default_content_type
handler.response.out.write(encoded_message)
|
'Constructor.
Args:
service_factory: Service factory to instantiate and provide to
service handler.'
| def __init__(self, service_factory):
| self.__service_factory = service_factory
self.__request_mappers = []
|
'Get all request mappers.
Returns:
Iterator of all request mappers used by this service factory.'
| def all_request_mappers(self):
| return iter(self.__request_mappers)
|
'Add request mapper to end of request mapper list.'
| def add_request_mapper(self, mapper):
| self.__request_mappers.append(mapper)
|
'Construct a new service handler instance.'
| def __call__(self):
| return ServiceHandler(self, self.__service_factory())
|
'Service factory associated with this factory.'
| @property
def service_factory(self):
| return self.__service_factory
|
'Check a path parameter.
Make sure a provided path parameter is compatible with the
webapp URL mapping.
Args:
path: Path to check. This is a plain path, not a regular expression.
Raises:
ValueError if path does not start with /, path ends with /.'
| @staticmethod
def __check_path(path):
| if path.endswith('/'):
raise ValueError(('Path %s must not end with /.' % path))
|
'Convenience method to map service to application.
Args:
path: Path to map service to. It must be a simple path
with a leading / and no trailing /.
Returns:
Mapping from service URL to service handler factory.'
| def mapping(self, path):
| self.__check_path(path)
service_url_pattern = ('(%s)%s' % (path, _METHOD_PATTERN))
return (service_url_pattern, self)
|
'Convenience method to map default factory configuration to application.
Creates a standardized default service factory configuration that pre-maps
the URL encoded protocol handler to the factory.
Args:
service_factory: Service factory to instantiate and provide to
service handler.
method_parameter: The name of the form parameter used to determine the
method to invoke used by the URLEncodedRPCMapper. If None, no
parameter is used and the mapper will only match against the form
path-name. Defaults to \'method\'.
parameter_prefix: If provided, all the parameters in the form are
expected to begin with that prefix by the URLEncodedRPCMapper.
Returns:
Mapping from service URL to service handler factory.'
| @classmethod
def default(cls, service_factory, parameter_prefix=''):
| factory = cls(service_factory)
factory.add_request_mapper(ProtobufRPCMapper())
factory.add_request_mapper(JSONRPCMapper())
return factory
|
'Constructor.
Args:
factory: Instance of ServiceFactory used for constructing new service
instances used for handling requests.
service: Service instance used for handling RPC.'
| def __init__(self, factory, service):
| self.__factory = factory
self.__service = service
|
'Handler method for GET requests.
Args:
service_path: Service path derived from request URL.
remote_method: Sub-path after service path has been matched.'
| def get(self, service_path, remote_method):
| self.handle('GET', service_path, remote_method)
|
'Handler method for POST requests.
Args:
service_path: Service path derived from request URL.
remote_method: Sub-path after service path has been matched.'
| def post(self, service_path, remote_method):
| self.handle('POST', service_path, remote_method)
|
'Not supported for services.'
| def redirect(self, uri, permanent=False):
| raise NotImplementedError('Services do not currently support redirection.')
|
'Send error to caller without embedded message.'
| def __send_simple_error(self, code, message, pad=True):
| self.response.headers['content-type'] = 'text/plain; charset=utf-8'
logging.error(message)
self.response.set_status(code, message)
response_message = httplib.responses.get(code, 'Unknown Error')
if pad:
response_message = util.pad_string(response_message)
self.response.out.write(response_message)
|
'Handle a service request.
The handle method will handle either a GET or POST response.
It is up to the individual mappers from the handler factory to determine
which request methods they can service.
If the protocol is not recognized, the request does not provide a correct
request for that protocol or the service object does not support the
requested RPC method, will return error code 400 in the response.
Args:
http_method: HTTP method of request.
service_path: Service path derived from request URL.
remote_method: Sub-path after service path has been matched.'
| def handle(self, http_method, service_path, remote_method):
| self.response.headers['x-content-type-options'] = 'nosniff'
if ((not remote_method) and (http_method == 'GET')):
self.error(405)
self.__show_info(service_path, remote_method)
return
content_type = self.__get_content_type()
try:
state_initializer = self.service.initialize_request_state
except AttributeError:
pass
else:
server_port = self.request.environ.get('SERVER_PORT', None)
if server_port:
server_port = int(server_port)
request_state = remote.HttpRequestState(remote_host=self.request.environ.get('REMOTE_HOST', None), remote_address=self.request.environ.get('REMOTE_ADDR', None), server_host=self.request.environ.get('SERVER_HOST', None), server_port=server_port, http_method=http_method, service_path=service_path, headers=list(self.__headers(content_type)))
state_initializer(request_state)
if (not content_type):
self.__send_simple_error(400, 'Invalid RPC request: missing content-type')
return
for mapper in self.__factory.all_request_mappers():
if (content_type in mapper.content_types):
break
else:
if (http_method == 'GET'):
self.error(httplib.UNSUPPORTED_MEDIA_TYPE)
self.__show_info(service_path, remote_method)
else:
self.__send_simple_error(httplib.UNSUPPORTED_MEDIA_TYPE, ('Unsupported content-type: %s' % content_type))
return
try:
if (http_method not in mapper.http_methods):
if (http_method == 'GET'):
self.error(httplib.METHOD_NOT_ALLOWED)
self.__show_info(service_path, remote_method)
else:
self.__send_simple_error(httplib.METHOD_NOT_ALLOWED, ('Unsupported HTTP method: %s' % http_method))
return
try:
try:
method = getattr(self.service, remote_method)
method_info = method.remote
except AttributeError as err:
self.__send_error(400, remote.RpcState.METHOD_NOT_FOUND_ERROR, ('Unrecognized RPC method: %s' % remote_method), mapper)
return
request = mapper.build_request(self, method_info.request_type)
except (RequestError, messages.DecodeError) as err:
self.__send_error(400, remote.RpcState.REQUEST_ERROR, ('Error parsing ProtoRPC request (%s)' % err), mapper)
return
try:
response = method(request)
except remote.ApplicationError as err:
self.__send_error(400, remote.RpcState.APPLICATION_ERROR, err.message, mapper, err.error_name)
return
mapper.build_response(self, response)
except Exception as err:
logging.error('An unexpected error occured when handling RPC: %s', err, exc_info=1)
self.__send_error(500, remote.RpcState.SERVER_ERROR, 'Internal Server Error', mapper)
return
|
'Constructor.
Args:
parameter_prefix: If provided, all the parameters in the form are
expected to begin with that prefix.'
| def __init__(self, parameter_prefix=''):
| super(URLEncodedRPCMapper, self).__init__(['POST'], _URLENCODED_CONTENT_TYPE, self)
self.__parameter_prefix = parameter_prefix
|
'Encode a message using parameter prefix.
Args:
message: Message to URL Encode.
Returns:
URL encoded message.'
| def encode_message(self, message):
| return protourlencode.encode_message(message, prefix=self.__parameter_prefix)
|
'Prefix all form parameters are expected to begin with.'
| @property
def parameter_prefix(self):
| return self.__parameter_prefix
|
'Build request from URL encoded HTTP request.
Constructs message from names of URL encoded parameters. If this service
handler has a parameter prefix, parameters must begin with it or are
ignored.
Args:
handler: RequestHandler instance that is servicing request.
request_type: Message type to build.
Returns:
Instance of request_type populated by protocol buffer in request
parameters.
Raises:
RequestError if message type contains nested message field or repeated
message field. Will raise RequestError if there are any repeated
parameters.'
| def build_request(self, handler, request_type):
| request = request_type()
builder = protourlencode.URLEncodedRequestBuilder(request, prefix=self.__parameter_prefix)
for argument in sorted(handler.request.arguments()):
values = handler.request.get_all(argument)
try:
builder.add_parameter(argument, values)
except messages.DecodeError as err:
raise RequestError(str(err))
return request
|
'Serve known static files.
If static file is not known, will return 404 to client.
Response items are cached for 300 seconds.
Args:
relative: Name of static file relative to main FormsHandler.'
| def get(self, relative):
| content_type = self.__RESOURCE_MAP.get(relative, None)
if (not content_type):
self.response.set_status(404)
self.response.out.write('Resource not found.')
return
path = os.path.join(_TEMPLATES_DIR, relative)
self.response.headers['Content-Type'] = content_type
static_file = open(path)
try:
contents = static_file.read()
finally:
static_file.close()
self.response.out.write(contents)
|
'Constructor.
When configuring a FormsHandler to use with a webapp application do not
pass the request handler class in directly. Instead use new_factory to
ensure that the FormsHandler is created with the correct registry path
for each request.
Args:
registry_path: Absolute path on server where the ProtoRPC RegsitryService
is located.'
| def __init__(self, registry_path=DEFAULT_REGISTRY_PATH):
| assert registry_path
self.__registry_path = registry_path
|
'Send forms and method page to user.
By default, displays a web page listing all services and methods registered
on the server. Methods have links to display the actual method form.
If both parameters are set, will display form for method.
Query Parameters:
service_path: Path to service to display method of. Optional.
method_name: Name of method to display form for. Optional.'
| def get(self):
| params = {'forms_path': self.request.path.rstrip('/'), 'hostname': self.request.host, 'registry_path': self.__registry_path}
service_path = self.request.get('path', None)
method_name = self.request.get('method', None)
if (service_path and method_name):
form_template = _METHODS_TEMPLATE
params['service_path'] = service_path
params['method_name'] = method_name
else:
form_template = _FORMS_TEMPLATE
self.response.out.write(template.render(form_template, params))
|
'Construct a factory for use with WSGIApplication.
This method is called automatically with the correct registry path when
services are configured via service_handlers.service_mapping.
Args:
registry_path: Absolute path on server where the ProtoRPC RegsitryService
is located.
Returns:
Factory function that creates a properly configured FormsHandler instance.'
| @classmethod
def new_factory(cls, registry_path=DEFAULT_REGISTRY_PATH):
| def forms_factory():
return cls(registry_path)
return forms_factory
|
'No encoding available for type.
Args:
value: Value to encode.
Raises:
NotImplementedError at all times.'
| def no_encoding(self, value):
| raise NotImplementedError()
|
'Encode an enum value.
Args:
value: Enum to encode.'
| def encode_enum(self, value):
| self.putVarInt32(value.number)
|
'Encode a Message in to an embedded message.
Args:
value: Message instance to encode.'
| def encode_message(self, value):
| self.putPrefixedString(encode_message(value))
|
'Helper to properly pb encode unicode strings to UTF-8.
Args:
value: String value to encode.'
| def encode_unicode_string(self, value):
| if isinstance(value, unicode):
value = value.encode('utf-8')
self.putPrefixedString(value)
|
'No decoding available for type.
Raises:
NotImplementedError at all times.'
| def no_decoding(self):
| raise NotImplementedError()
|
'Decode a unicode string.
Returns:
Next value in stream as a unicode string.'
| def decode_string(self):
| return self.getPrefixedString().decode('UTF-8')
|
'Decode a boolean value.
Returns:
Next value in stream as a boolean.'
| def decode_boolean(self):
| return bool(self.getBoolean())
|
'Constructor.
Args:
registry: Map of name to service class. This map is not copied and may
be modified after the reigstry service has been configured.
modules: Module dict to draw descriptors from. Defaults to sys.modules.'
| @util.positional(2)
def __init__(self, registry, modules=None):
| self.__registry = registry
if (modules is None):
modules = sys.modules
self.__modules = modules
self.__definition_to_modules = {}
|
'Find modules referred to by a message type.
Determines the entire list of modules ultimately referred to by message_type
by iterating over all of its message and enum fields. Includes modules
referred to fields within its referred messages.
Args:
message_type: Message type to find all referring modules for.
Returns:
Set of modules referred to by message_type by traversing all its
message and enum fields.'
| def __find_modules_for_message(self, message_type):
| def get_dependencies(message_type, seen=None):
"Get all dependency definitions of a message type.\n\n This function works by collecting the types of all enumeration and message\n fields defined within the message type. When encountering a message\n field, it will recursivly find all of the associated message's\n dependencies. It will terminate on circular dependencies by keeping track\n of what definitions it already via the seen set.\n\n Args:\n message_type: Message type to get dependencies for.\n seen: Set of definitions that have already been visited.\n\n Returns:\n All dependency message and enumerated types associated with this message\n including the message itself.\n "
if (seen is None):
seen = set()
seen.add(message_type)
for field in message_type.all_fields():
if isinstance(field, messages.MessageField):
if (field.type not in seen):
get_dependencies(field.type, seen)
elif isinstance(field, messages.EnumField):
seen.add(field.type)
return seen
found_modules = self.__definition_to_modules.setdefault(message_type, set())
if (not found_modules):
dependencies = get_dependencies(message_type)
found_modules.update((self.__modules[definition.__module__] for definition in dependencies))
return found_modules
|
'Get file-set for named services.
Args:
names: List of names to get file-set for.
Returns:
descriptor.FileSet containing all the descriptors for all modules
ultimately referred to by all service types request by names parameter.'
| def __describe_file_set(self, names):
| service_modules = set()
if names:
for service in (self.__registry[name] for name in names):
found_modules = self.__definition_to_modules.setdefault(service, set())
if (not found_modules):
found_modules.add(self.__modules[service.__module__])
for method_name in service.all_remote_methods():
method = getattr(service, method_name)
for message_type in (method.remote.request_type, method.remote.response_type):
found_modules.update(self.__find_modules_for_message(message_type))
service_modules.update(found_modules)
return descriptor.describe_file_set(service_modules)
|
'Get service registry associated with this service instance.'
| @property
def registry(self):
| return self.__registry
|
'Get all registered services.'
| @remote.method(response_type=ServicesResponse)
def services(self, request):
| response = ServicesResponse()
response.services = []
for (name, service_class) in self.__registry.iteritems():
mapping = ServiceMapping()
mapping.name = name.decode('utf-8')
mapping.definition = service_class.definition_name().decode('utf-8')
response.services.append(mapping)
return response
|
'Get file-set for registered servies.'
| @remote.method(GetFileSetRequest, GetFileSetResponse)
def get_file_set(self, request):
| response = GetFileSetResponse()
response.file_set = self.__describe_file_set(request.names)
return response
|
'Constructor.
Args:
output: File-like object to wrap.
indent_space: Number of spaces each level of indentation will be.'
| @util.positional(2)
def __init__(self, output, indent_space=2):
| self.__output = output
self.__indent_space = (indent_space * ' ')
self.__indentation = 0
|
'Current level of indentation for IndentWriter.'
| @property
def indent_level(self):
| return self.__indentation
|
'Write line to wrapped file-like object using correct indentation.
The line is written with the current level of indentation printed before it
and terminated by a new line.
Args:
line: Line to write to wrapped file-like object.'
| def write_line(self, line):
| if (line != ''):
self.__output.write((self.__indentation * self.__indent_space))
self.__output.write(line)
self.__output.write('\n')
|
'Begin a level of indentation.'
| def begin_indent(self):
| self.__indentation += 1
|
'Undo the most recent level of indentation.
Raises:
IndentationError when called with no indentation levels.'
| def end_indent(self):
| if (not self.__indentation):
raise IndentationError('Unable to un-indent further')
self.__indentation -= 1
|
'Create indentation level compatible with the Python \'with\' keyword.'
| @contextlib.contextmanager
def indent(self):
| self.begin_indent()
(yield)
self.end_indent()
|
'Syntactic sugar for write_line method.
Args:
line: Line to write to wrapped file-like object.'
| def __lshift__(self, line):
| self.write_line(line)
|
'Constructor for JSONEncoder, with sensible defaults.
If skipkeys is false, then it is a TypeError to attempt
encoding of keys that are not str, int, long, float or None. If
skipkeys is True, such items are simply skipped.
If ensure_ascii is true, the output is guaranteed to be str
objects with all incoming unicode characters escaped. If
ensure_ascii is false, the output will be unicode object.
If check_circular is true, then lists, dicts, and custom encoded
objects will be checked for circular references during encoding to
prevent an infinite recursion (which would cause an OverflowError).
Otherwise, no such check takes place.
If allow_nan is true, then NaN, Infinity, and -Infinity will be
encoded as such. This behavior is not JSON specification compliant,
but is consistent with most JavaScript based encoders and decoders.
Otherwise, it will be a ValueError to encode such floats.
If sort_keys is true, then the output of dictionaries will be
sorted by key; this is useful for regression tests to ensure
that JSON serializations can be compared on a day-to-day basis.
If indent is a string, then JSON array elements and object members
will be pretty-printed with a newline followed by that string repeated
for each level of nesting. ``None`` (the default) selects the most compact
representation without any newlines. For backwards compatibility with
versions of simplejson earlier than 2.1.0, an integer is also accepted
and is converted to a string with that many spaces.
If specified, separators should be a (item_separator, key_separator)
tuple. The default is (\', \', \': \'). To get the most compact JSON
representation you should specify (\',\', \':\') to eliminate whitespace.
If specified, default is a function that gets called for objects
that can\'t otherwise be serialized. It should return a JSON encodable
version of the object or raise a ``TypeError``.
If encoding is not None, then all input strings will be
transformed into unicode using that encoding prior to JSON-encoding.
The default is UTF-8.
If use_decimal is true (not the default), ``decimal.Decimal`` will
be supported directly by the encoder. For the inverse, decode JSON
with ``parse_float=decimal.Decimal``.'
| def __init__(self, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, encoding='utf-8', default=None, use_decimal=False):
| self.skipkeys = skipkeys
self.ensure_ascii = ensure_ascii
self.check_circular = check_circular
self.allow_nan = allow_nan
self.sort_keys = sort_keys
self.use_decimal = use_decimal
if isinstance(indent, (int, long)):
indent = (' ' * indent)
self.indent = indent
if (separators is not None):
(self.item_separator, self.key_separator) = separators
if (default is not None):
self.default = default
self.encoding = encoding
|
'Implement this method in a subclass such that it returns
a serializable object for ``o``, or calls the base implementation
(to raise a ``TypeError``).
For example, to support arbitrary iterators, you could
implement default like this::
def default(self, o):
try:
iterable = iter(o)
except TypeError:
pass
else:
return list(iterable)
return JSONEncoder.default(self, o)'
| def default(self, o):
| raise TypeError((repr(o) + ' is not JSON serializable'))
|
'Return a JSON string representation of a Python data structure.
>>> from simplejson import JSONEncoder
>>> JSONEncoder().encode({"foo": ["bar", "baz"]})
\'{"foo": ["bar", "baz"]}\''
| def encode(self, o):
| if isinstance(o, basestring):
if isinstance(o, str):
_encoding = self.encoding
if ((_encoding is not None) and (not (_encoding == 'utf-8'))):
o = o.decode(_encoding)
if self.ensure_ascii:
return encode_basestring_ascii(o)
else:
return encode_basestring(o)
chunks = self.iterencode(o, _one_shot=True)
if (not isinstance(chunks, (list, tuple))):
chunks = list(chunks)
if self.ensure_ascii:
return ''.join(chunks)
else:
return u''.join(chunks)
|
'Encode the given object and yield each string
representation as available.
For example::
for chunk in JSONEncoder().iterencode(bigobject):
mysocket.write(chunk)'
| def iterencode(self, o, _one_shot=False):
| if self.check_circular:
markers = {}
else:
markers = None
if self.ensure_ascii:
_encoder = encode_basestring_ascii
else:
_encoder = encode_basestring
if (self.encoding != 'utf-8'):
def _encoder(o, _orig_encoder=_encoder, _encoding=self.encoding):
if isinstance(o, str):
o = o.decode(_encoding)
return _orig_encoder(o)
def floatstr(o, allow_nan=self.allow_nan, _repr=FLOAT_REPR, _inf=PosInf, _neginf=(- PosInf)):
if (o != o):
text = 'NaN'
elif (o == _inf):
text = 'Infinity'
elif (o == _neginf):
text = '-Infinity'
else:
return _repr(o)
if (not allow_nan):
raise ValueError(('Out of range float values are not JSON compliant: ' + repr(o)))
return text
key_memo = {}
if (_one_shot and (c_make_encoder is not None) and (self.indent is None)):
_iterencode = c_make_encoder(markers, self.default, _encoder, self.indent, self.key_separator, self.item_separator, self.sort_keys, self.skipkeys, self.allow_nan, key_memo, self.use_decimal)
else:
_iterencode = _make_iterencode(markers, self.default, _encoder, self.indent, floatstr, self.key_separator, self.item_separator, self.sort_keys, self.skipkeys, _one_shot, self.use_decimal)
try:
return _iterencode(o, 0)
finally:
key_memo.clear()
|
'*encoding* determines the encoding used to interpret any
:class:`str` objects decoded by this instance (``\'utf-8\'`` by
default). It has no effect when decoding :class:`unicode` objects.
Note that currently only encodings that are a superset of ASCII work,
strings of other encodings should be passed in as :class:`unicode`.
*object_hook*, if specified, will be called with the result of every
JSON object decoded and its return value will be used in place of the
given :class:`dict`. This can be used to provide custom
deserializations (e.g. to support JSON-RPC class hinting).
*object_pairs_hook* is an optional function that will be called with
the result of any object literal decode with an ordered list of pairs.
The return value of *object_pairs_hook* will be used instead of the
:class:`dict`. This feature can be used to implement custom decoders
that rely on the order that the key and value pairs are decoded (for
example, :func:`collections.OrderedDict` will remember the order of
insertion). If *object_hook* is also defined, the *object_pairs_hook*
takes priority.
*parse_float*, if specified, will be called with the string of every
JSON float to be decoded. By default, this is equivalent to
``float(num_str)``. This can be used to use another datatype or parser
for JSON floats (e.g. :class:`decimal.Decimal`).
*parse_int*, if specified, will be called with the string of every
JSON int to be decoded. By default, this is equivalent to
``int(num_str)``. This can be used to use another datatype or parser
for JSON integers (e.g. :class:`float`).
*parse_constant*, if specified, will be called with one of the
following strings: ``\'-Infinity\'``, ``\'Infinity\'``, ``\'NaN\'``. This
can be used to raise an exception if invalid JSON numbers are
encountered.
*strict* controls the parser\'s behavior when it encounters an
invalid control character in a string. The default setting of
``True`` means that unescaped control characters are parse errors, if
``False`` then control characters will be allowed in strings.'
| def __init__(self, encoding=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, strict=True, object_pairs_hook=None):
| self.encoding = encoding
self.object_hook = object_hook
self.object_pairs_hook = object_pairs_hook
self.parse_float = (parse_float or float)
self.parse_int = (parse_int or int)
self.parse_constant = (parse_constant or _CONSTANTS.__getitem__)
self.strict = strict
self.parse_object = JSONObject
self.parse_array = JSONArray
self.parse_string = scanstring
self.memo = {}
self.scan_once = make_scanner(self)
|
'Return the Python representation of ``s`` (a ``str`` or ``unicode``
instance containing a JSON document)'
| def decode(self, s, _w=WHITESPACE.match):
| (obj, end) = self.raw_decode(s, idx=_w(s, 0).end())
end = _w(s, end).end()
if (end != len(s)):
raise JSONDecodeError('Extra data', s, end, len(s))
return obj
|
'Decode a JSON document from ``s`` (a ``str`` or ``unicode``
beginning with a JSON document) and return a 2-tuple of the Python
representation and the index in ``s`` where the document ended.
This can be used to decode a JSON document from a string that may
have extraneous data at the end.'
| def raw_decode(self, s, idx=0):
| try:
(obj, end) = self.scan_once(s, idx)
except StopIteration:
raise JSONDecodeError('No JSON object could be decoded', s, idx)
return (obj, end)
|
'Initializes a new ThreadPoolExecutor instance.
Args:
max_workers: The maximum number of threads that can be used to
execute the given calls.'
| def __init__(self, max_workers):
| self._max_workers = max_workers
self._work_queue = queue.Queue()
self._threads = set()
self._shutdown = False
self._shutdown_lock = threading.Lock()
|
'Initializes the future. Should not be called by clients.'
| def __init__(self):
| self._condition = threading.Condition()
self._state = PENDING
self._result = None
self._exception = None
self._waiters = []
self._done_callbacks = []
|
'Cancel the future if possible.
Returns True if the future was cancelled, False otherwise. A future
cannot be cancelled if it is running or has already completed.'
| def cancel(self):
| with self._condition:
if (self._state in [RUNNING, FINISHED]):
return False
if (self._state in [CANCELLED, CANCELLED_AND_NOTIFIED]):
return True
self._state = CANCELLED
self._condition.notify_all()
self._invoke_callbacks()
return True
|
'Return True if the future has cancelled.'
| def cancelled(self):
| with self._condition:
return (self._state in [CANCELLED, CANCELLED_AND_NOTIFIED])
|
'Return True if the future is currently executing.'
| def running(self):
| with self._condition:
return (self._state == RUNNING)
|
'Return True of the future was cancelled or finished executing.'
| def done(self):
| with self._condition:
return (self._state in [CANCELLED, CANCELLED_AND_NOTIFIED, FINISHED])
|
'Attaches a callable that will be called when the future finishes.
Args:
fn: A callable that will be called with this future as its only
argument when the future completes or is cancelled. The callable
will always be called by a thread in the same process in which
it was added. If the future has already completed or been
cancelled then the callable will be called immediately. These
callables are called in the order that they were added.'
| def add_done_callback(self, fn):
| with self._condition:
if (self._state not in [CANCELLED, CANCELLED_AND_NOTIFIED, FINISHED]):
self._done_callbacks.append(fn)
return
fn(self)
|
'Return the result of the call that the future represents.
Args:
timeout: The number of seconds to wait for the result if the future
isn\'t done. If None, then there is no limit on the wait time.
Returns:
The result of the call that the future represents.
Raises:
CancelledError: If the future was cancelled.
TimeoutError: If the future didn\'t finish executing before the given
timeout.
Exception: If the call raised then that exception will be raised.'
| def result(self, timeout=None):
| with self._condition:
if (self._state in [CANCELLED, CANCELLED_AND_NOTIFIED]):
raise CancelledError()
elif (self._state == FINISHED):
return self.__get_result()
self._condition.wait(timeout)
if (self._state in [CANCELLED, CANCELLED_AND_NOTIFIED]):
raise CancelledError()
elif (self._state == FINISHED):
return self.__get_result()
else:
raise TimeoutError()
|
'Return the exception raised by the call that the future represents.
Args:
timeout: The number of seconds to wait for the exception if the
future isn\'t done. If None, then there is no limit on the wait
time.
Returns:
The exception raised by the call that the future represents or None
if the call completed without raising.
Raises:
CancelledError: If the future was cancelled.
TimeoutError: If the future didn\'t finish executing before the given
timeout.'
| def exception(self, timeout=None):
| with self._condition:
if (self._state in [CANCELLED, CANCELLED_AND_NOTIFIED]):
raise CancelledError()
elif (self._state == FINISHED):
return self._exception
self._condition.wait(timeout)
if (self._state in [CANCELLED, CANCELLED_AND_NOTIFIED]):
raise CancelledError()
elif (self._state == FINISHED):
return self._exception
else:
raise TimeoutError()
|
'Mark the future as running or process any cancel notifications.
Should only be used by Executor implementations and unit tests.
If the future has been cancelled (cancel() was called and returned
True) then any threads waiting on the future completing (though calls
to as_completed() or wait()) are notified and False is returned.
If the future was not cancelled then it is put in the running state
(future calls to running() will return True) and True is returned.
This method should be called by Executor implementations before
executing the work associated with this future. If this method returns
False then the work should not be executed.
Returns:
False if the Future was cancelled, True otherwise.
Raises:
RuntimeError: if this method was already called or if set_result()
or set_exception() was called.'
| def set_running_or_notify_cancel(self):
| with self._condition:
if (self._state == CANCELLED):
self._state = CANCELLED_AND_NOTIFIED
for waiter in self._waiters:
waiter.add_cancelled(self)
return False
elif (self._state == PENDING):
self._state = RUNNING
return True
else:
LOGGER.critical('Future %s in unexpected state: %s', id(self.future), self.future._state)
raise RuntimeError('Future in unexpected state')
|
'Sets the return value of work associated with the future.
Should only be used by Executor implementations and unit tests.'
| def set_result(self, result):
| with self._condition:
self._result = result
self._state = FINISHED
for waiter in self._waiters:
waiter.add_result(self)
self._condition.notify_all()
self._invoke_callbacks()
|
'Sets the result of the future as being the given exception.
Should only be used by Executor implementations and unit tests.'
| def set_exception(self, exception):
| with self._condition:
self._exception = exception
self._state = FINISHED
for waiter in self._waiters:
waiter.add_exception(self)
self._condition.notify_all()
self._invoke_callbacks()
|
'Submits a callable to be executed with the given arguments.
Schedules the callable to be executed as fn(*args, **kwargs) and returns
a Future instance representing the execution of the callable.
Returns:
A Future representing the given call.'
| def submit(self, fn, *args, **kwargs):
| raise NotImplementedError()
|
'Returns a iterator equivalent to map(fn, iter).
Args:
fn: A callable that will take take as many arguments as there are
passed iterables.
timeout: The maximum number of seconds to wait. If None, then there
is no limit on the wait time.
Returns:
An iterator equivalent to: map(func, *iterables) but the calls may
be evaluated out-of-order.
Raises:
TimeoutError: If the entire result iterator could not be generated
before the given timeout.
Exception: If fn(*args) raises for any values.'
| def map(self, fn, *iterables, **kwargs):
| timeout = kwargs.get('timeout')
if (timeout is not None):
end_time = (timeout + time.time())
fs = [self.submit(fn, *args) for args in zip(*iterables)]
try:
for future in fs:
if (timeout is None):
(yield future.result())
else:
(yield future.result((end_time - time.time())))
finally:
for future in fs:
future.cancel()
|
'Clean-up the resources associated with the Executor.
It is safe to call this method several times. Otherwise, no other
methods can be called after this one.
Args:
wait: If True then shutdown will not return until all running
futures have finished executing and the resources used by the
executor have been reclaimed.'
| def shutdown(self, wait=True):
| pass
|
'Initializes a new ProcessPoolExecutor instance.
Args:
max_workers: The maximum number of processes that can be used to
execute the given calls. If None or not given then as many
worker processes will be created as the machine has processors.'
| def __init__(self, max_workers=None):
| _remove_dead_thread_references()
if (max_workers is None):
self._max_workers = multiprocessing.cpu_count()
else:
self._max_workers = max_workers
self._call_queue = multiprocessing.Queue((self._max_workers + EXTRA_QUEUED_CALLS))
self._result_queue = multiprocessing.Queue()
self._work_ids = queue.Queue()
self._queue_management_thread = None
self._processes = set()
self._shutdown_thread = False
self._shutdown_process_event = multiprocessing.Event()
self._shutdown_lock = threading.Lock()
self._queue_count = 0
self._pending_work_items = {}
|
'Set up a new instance.'
| def __init__(self, enumtype, index, key):
| self._enumtype = enumtype
self._index = index
self._key = key
|
'Create an enumeration instance.'
| def __init__(self, *keys, **kwargs):
| value_type = kwargs.get('value_type', EnumValue)
if (not keys):
raise EnumEmptyError()
keys = tuple(keys)
values = ([None] * len(keys))
for (i, key) in enumerate(keys):
value = value_type(self, i, key)
values[i] = value
try:
super(Enum, self).__setattr__(key, value)
except TypeError:
raise EnumBadKeyError(key)
self.__dict__['_keys'] = keys
self.__dict__['_values'] = values
|
'Set up a new instance.'
| def __init__(self, *keys):
| pass
|
'Set up test fixtures.'
| def setUp(self):
| from sys import modules
self.module = modules['enum']
|
'Module should have __author_name__ string.'
| def test_author_name_is_string(self):
| mod_author_name = self.module.__author_name__
self.failUnless(isinstance(mod_author_name, basestring))
|
'Module should have __author_email__ string.'
| def test_author_email_is_string(self):
| mod_author_email = self.module.__author_email__
self.failUnless(isinstance(mod_author_email, basestring))
|
'Module should have __author__ string.'
| def test_author_is_string(self):
| mod_author = self.module.__author__
self.failUnless(isinstance(mod_author, basestring))
|
'Module __author__ string should contain author name.'
| def test_author_contains_name(self):
| mod_author = self.module.__author__
mod_author_name = self.module.__author_name__
self.failUnless(mod_author.startswith(mod_author_name))
|
'Module __author__ string should contain author email.'
| def test_author_contains_email(self):
| mod_author = self.module.__author__
mod_author_email = self.module.__author_email__
self.failUnless(mod_author.endswith(('<%(mod_author_email)s>' % vars())))
|
'Module should have __date__ string.'
| def test_date_is_string(self):
| mod_date = self.module.__date__
self.failUnless(isinstance(mod_date, basestring))
|
'Module should have __copyright__ string.'
| def test_copyright_is_string(self):
| mod_copyright = self.module.__copyright__
self.failUnless(isinstance(mod_copyright, basestring))
|
'Module __copyright__ string should contain author name.'
| def test_copyright_contains_name(self):
| mod_copyright = self.module.__copyright__
mod_author_name = self.module.__author_name__
self.failUnless(mod_copyright.endswith(mod_author_name))
|
'Module __copyright__ string should contain beginning year.'
| def test_copyright_contains_begin_year(self):
| mod_copyright = self.module.__copyright__
year_begin = self.module._copyright_year_begin
self.failUnless((year_begin in mod_copyright))
|
'Module __copyright__ string should contain latest year..'
| def test_copyright_contains_latest_year(self):
| mod_copyright = self.module.__copyright__
year_latest = self.module.__date__.split('-')[0]
self.failUnless((year_latest in mod_copyright))
|
'Module should have __license__ string.'
| def test_license_is_string(self):
| mod_license = self.module.__license__
self.failUnless(isinstance(mod_license, basestring))
|
'Module should have __url__ string.'
| def test_url_is_string(self):
| mod_url = self.module.__url__
self.failUnless(isinstance(mod_url, basestring))
|
'Module should have __version__ string.'
| def test_version_is_string(self):
| mod_version = self.module.__version__
self.failUnless(isinstance(mod_version, basestring))
|
'Set up test fixtures.'
| def setUp(self):
| self.valid_exceptions = {enum.EnumEmptyError: dict(min_args=0, types=(enum.EnumException, AssertionError)), enum.EnumBadKeyError: dict(min_args=1, types=(enum.EnumException, TypeError)), enum.EnumImmutableError: dict(min_args=1, types=(enum.EnumException, TypeError))}
for (exc_type, params) in self.valid_exceptions.items():
args = ((None,) * params['min_args'])
instance = exc_type(*args)
self.valid_exceptions[exc_type]['instance'] = instance
|
'The module exception base class should be abstract.'
| def test_EnumException_abstract(self):
| self.failUnlessRaises(NotImplementedError, enum.EnumException)
|
'Exception instance should be created.'
| def test_exception_instance(self):
| for (exc_type, params) in self.valid_exceptions.items():
instance = params['instance']
self.failUnless(instance)
|
'Exception instances should match expected types.'
| def test_exception_types(self):
| for (exc_type, params) in self.valid_exceptions.items():
instance = params['instance']
for match_type in params['types']:
self.failUnless(isinstance(instance, match_type), msg=('instance: %(instance)r, match_type: %(match_type)s' % vars()))
|
'Set up the test fixtures.'
| def setUp(self):
| setup_enum_value_fixtures(self)
|
'Creating an EnumValue instance should succeed.'
| def test_instantiate(self):
| for (enumtype, params) in self.valid_values.items():
for (key, instance) in params['values'].items():
self.failUnless(instance)
|
'EnumValue should export its enum type.'
| def test_enumtype_equal(self):
| for (enumtype, params) in self.valid_values.items():
for (key, instance) in params['values'].items():
self.failUnlessEqual(enumtype, instance.enumtype)
|
'EnumValue should export its string key.'
| def test_key_equal(self):
| for (enumtype, params) in self.valid_values.items():
for (key, instance) in params['values'].items():
self.failUnlessEqual(key, instance.key)
|
'String value for EnumValue should be its key string.'
| def test_str_key(self):
| for (enumtype, params) in self.valid_values.items():
for (key, instance) in params['values'].items():
self.failUnlessEqual(key, str(instance))
|
'EnumValue should export its sequence index.'
| def test_index_equal(self):
| for (enumtype, params) in self.valid_values.items():
for (i, key) in enumerate(params['keys']):
instance = params['values'][key]
self.failUnlessEqual(i, instance.index)
|
'Representation of EnumValue should be meaningful.'
| def test_repr(self):
| for (enumtype, params) in self.valid_values.items():
for (i, key) in enumerate(params['keys']):
instance = params['values'][key]
repr_str = repr(instance)
self.failUnless(repr_str.startswith('EnumValue('))
self.failUnless(repr_str.count(repr(enumtype)))
self.failUnless(repr_str.count(repr(i)))
self.failUnless(repr_str.count(repr(key)))
self.failUnless(repr_str.endswith(')'))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.