desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Return the total number of unique entities transferred.'
| def EntitiesTransferred(self):
| return self.result_db.count
|
'Write the contents of the result database.'
| def WorkFinished(self):
| self.exporter.output_entities(self.result_db.AllEntities())
|
'Update the state of the given KeyRangeItem.
Args:
item: A KeyRange instance.'
| def UpdateProgress(self, item):
| if (item.state == STATE_GOT):
count = self.result_db.StoreEntities(item.download_result.keys, item.download_result.entities)
self.db.DeleteKey(item.progress_key)
self.entities_transferred += count
else:
self.db.UpdateState(item.progress_key, item.state)
|
'Initialize the MapperProgressThread instance.
Args:
mapper: A Mapper object for this map run.
progress_queue: A Queue used for tracking progress information.
progress_db: The database for tracking progress information; should
be an instance of ProgressDatabase.'
| def __init__(self, mapper, progress_queue, progress_db):
| _ProgressThreadBase.__init__(self, progress_queue, progress_db)
self.mapper = mapper
|
'Return the total number of unique entities transferred.'
| def EntitiesTransferred(self):
| return self.entities_transferred
|
'Perform actions after map is complete.'
| def WorkFinished(self):
| pass
|
'Update the state of the given KeyRangeItem.
Args:
item: A KeyRange instance.'
| def UpdateProgress(self, item):
| if (item.state == STATE_GOT):
self.entities_transferred += item.count
self.db.DeleteKey(item.progress_key)
else:
self.db.UpdateState(item.progress_key, item.state)
|
'Constructor.
Populates this Loader\'s kind and properties map.
Args:
kind: a string containing the entity kind that this loader handles
properties: list of (name, converter) tuples.
This is used to automatically convert the input columns into
properties. The converter should be a function that takes one
argument, a s... | def __init__(self, kind, properties):
| Validate(kind, (basestring, tuple))
self.kind = kind
self.__openfile = open
self.__create_csv_reader = csv.reader
GetImplementationClass(kind)
Validate(properties, list)
for (name, fn) in properties:
Validate(name, basestring)
assert callable(fn), ('Conversion function ... |
'Register loader and the Loader instance for its kind.
Args:
loader: A Loader instance.'
| @staticmethod
def RegisterLoader(loader):
| Loader.__loaders[loader.kind] = loader
|
'Returns dict {ancestor_path : {kind : id}} with high id values.
The returned dictionary is used to increment the id counters
associated with each ancestor_path and kind to be at least id.'
| def get_high_ids(self):
| return {}
|
'Aliases method names so that Loaders defined with old names work.'
| def alias_old_names(self):
| aliases = (('CreateEntity', 'create_entity'), ('HandleEntity', 'handle_entity'), ('GenerateKey', 'generate_key'))
for (old_name, new_name) in aliases:
setattr(Loader, old_name, getattr(Loader, new_name))
if (hasattr(self.__class__, old_name) and (not (getattr(self.__class__, old_name).im_func ==... |
'Creates a entity from a list of property values.
Args:
values: list/tuple of str
key_name: if provided, the name for the (single) resulting entity
parent: A datastore.Key instance for the parent, or None
Returns:
list of db.Model
The returned entities are populated with the property values from the
argument, converted... | def create_entity(self, values, key_name=None, parent=None):
| Validate(values, (list, tuple))
assert (len(values) == len(self.__properties)), ('Expected %d columns, found %d.' % (len(self.__properties), len(values)))
model_class = GetImplementationClass(self.kind)
properties = {'key_name': key_name, 'parent': parent}
for ((name, converter), val) in... |
'Generates a key_name to be used in creating the underlying object.
The default implementation returns None.
This method can be overridden to control the key generation for
uploaded entities. The value returned should be None (to use a
server generated numeric key), or a string which neither starts
with a digit nor has... | def generate_key(self, i, values):
| return None
|
'Subclasses can override this to add custom entity conversion code.
This is called for each entity, after its properties are populated
from the input but before it is stored. Subclasses can override
this to add custom entity handling code.
The entity to be inserted should be returned. If multiple entities
should be ins... | def handle_entity(self, entity):
| return entity
|
'Performs initialization and validation of the input file.
This implementation checks that the input file exists and can be
opened for reading.
Args:
filename: The string given as the --filename flag argument.
loader_opts: The string given as the --loader_opts flag argument.'
| def initialize(self, filename, loader_opts):
| CheckFile(filename)
|
'Performs finalization actions after the upload completes.'
| def finalize(self):
| pass
|
'Subclasses can override this to add custom data input code.
This method must yield fixed-length lists of strings.
The default implementation uses csv.reader to read CSV rows
from filename.
Args:
filename: The string input for the --filename option.
Yields:
Lists of strings.'
| def generate_records(self, filename):
| csv_generator = CSVGenerator(filename, openfile=self.__openfile, create_csv_reader=self.__create_csv_reader).Records()
return csv_generator
|
'Returns a dict of the Loader instances that have been created.'
| @staticmethod
def RegisteredLoaders():
| return dict(Loader.__loaders)
|
'Returns the loader instance for the given kind if it exists.'
| @staticmethod
def RegisteredLoader(kind):
| return Loader.__loaders[kind]
|
'Find the highest numeric id used for each ancestor-path, kind pair.
Args:
record_generator: A generator of entity_encoding strings.
Returns:
A map from ancestor-path to maps from kind to id. {path : {kind : id}}'
| def _find_high_id(self, record_generator):
| high_id = {}
for values in record_generator:
entity = self.create_entity(values)
key = entity.key()
if (not key.id()):
continue
kind = key.kind()
ancestor_path = []
if key.parent():
ancestor_path = key.parent().to_path()
if (tuple(a... |
'Transform the Reference protobuffer which underlies keys and references.
Args:
entity_namespace: The \'before\' namespace of the entity that has this
reference property. If this value does not match the reference
properties current namespace, then the reference property namespace will
not be modified.
reference_proto... | def rewrite_reference_proto(self, entity_namespace, reference_proto):
| reference_proto.set_app(self.app_id)
if (entity_namespace != reference_proto.name_space()):
return
if self.namespace:
reference_proto.set_name_space(self.namespace)
else:
reference_proto.clear_name_space()
|
'Transform the ReferenceProperties of the given entity to fix app_id.'
| def _translate_entity_proto(self, entity_proto):
| entity_key = entity_proto.mutable_key()
entity_key.set_app(self.app_id)
original_entity_namespace = entity_key.name_space()
if self.namespace:
entity_key.set_name_space(self.namespace)
else:
entity_key.clear_name_space()
for prop in entity_proto.property_list():
prop_valu... |
'Constructor.
Populates this Exporters\'s kind and properties map.
Args:
kind: a string containing the entity kind that this exporter handles
properties: list of (name, converter, default) tuples.
This is used to automatically convert the entities to strings.
The converter should be a function that takes one argument, ... | def __init__(self, kind, properties):
| Validate(kind, basestring)
self.kind = kind
GetImplementationClass(kind)
Validate(properties, list)
for (name, fn, default) in properties:
Validate(name, basestring)
assert callable(fn), ('Conversion function %s for property %s is not callable.' % (fn, name))
... |
'Register exporter and the Exporter instance for its kind.
Args:
exporter: A Exporter instance.'
| @staticmethod
def RegisterExporter(exporter):
| Exporter.__exporters[exporter.kind] = exporter
|
'Converts an entity into a list of string values.
Args:
entity: An entity to extract the properties from.
Returns:
A list of the properties of the entity.
Raises:
MissingPropertyError: if an expected field on the entity is missing.'
| def __ExtractProperties(self, entity):
| encoding = []
for (name, fn, default) in self.__properties:
try:
encoding.append(fn(entity[name]))
except KeyError:
if (name == '__key__'):
encoding.append(fn(entity.key()))
elif (default is None):
raise MissingPropertyError(nam... |
'Convert the given entity into CSV string.
Args:
entity: The entity to encode.
Returns:
A CSV string.'
| def __EncodeEntity(self, entity):
| output = StringIO.StringIO()
writer = csv.writer(output)
writer.writerow(self.__ExtractProperties(entity))
return output.getvalue()
|
'Creates a string representation of an entity.
Args:
entity: The entity to serialize.
Returns:
A serialized representation of an entity.'
| def __SerializeEntity(self, entity):
| encoding = self.__EncodeEntity(entity)
if (not isinstance(encoding, unicode)):
encoding = unicode(encoding, 'utf-8')
encoding = encoding.encode('utf-8')
return encoding
|
'Outputs the downloaded entities.
This implementation writes CSV.
Args:
entity_generator: A generator that yields the downloaded entities
in key order.'
| def output_entities(self, entity_generator):
| CheckOutputFile(self.output_filename)
output_file = open(self.output_filename, 'w')
logger.debug('Export complete, writing to file')
output_file.writelines((self.__SerializeEntity(entity) for entity in entity_generator))
|
'Performs initialization and validation of the output file.
This implementation checks that the input file exists and can be
opened for writing.
Args:
filename: The string given as the --filename flag argument.
exporter_opts: The string given as the --exporter_opts flag argument.'
| def initialize(self, filename, exporter_opts):
| CheckOutputFile(filename)
self.output_filename = filename
|
'Performs finalization actions after the download completes.'
| def finalize(self):
| pass
|
'A value to alter sorting of entities in output_entities entity_generator.
Will only be called if calculate_sort_key_from_entity is true.
Args:
entity: A datastore.Entity.
Returns:
A value to store in the intermediate sqlite table. The table will later
be sorted by this value then by the datastore key, so the sort_key ... | def sort_key_from_entity(self, entity):
| return ''
|
'Returns a dictionary of the exporter instances that have been created.'
| @staticmethod
def RegisteredExporters():
| return dict(Exporter.__exporters)
|
'Returns an exporter instance for the given kind if it exists.'
| @staticmethod
def RegisteredExporter(kind):
| return Exporter.__exporters[kind]
|
'Constructor.
Populates this Mappers\'s kind.
Args:
kind: a string containing the entity kind that this mapper handles'
| def __init__(self, kind):
| Validate(kind, basestring)
self.kind = kind
GetImplementationClass(kind)
|
'Register mapper and the Mapper instance for its kind.
Args:
mapper: A Mapper instance.'
| @staticmethod
def RegisterMapper(mapper):
| Mapper.__mappers[mapper.kind] = mapper
|
'Performs initialization.
Args:
mapper_opts: The string given as the --mapper_opts flag argument.'
| def initialize(self, mapper_opts):
| pass
|
'Performs finalization actions after the download completes.'
| def finalize(self):
| pass
|
'Return whether this mapper should iterate over only keys or not.
Override this method in subclasses to return True values.
Returns:
True or False'
| def map_over_keys_only(self):
| return False
|
'Returns a dictionary of the mapper instances that have been created.'
| @staticmethod
def RegisteredMappers():
| return dict(Mapper.__mappers)
|
'Returns an mapper instance for the given kind if it exists.'
| @staticmethod
def RegisteredMapper(kind):
| return Mapper.__mappers[kind]
|
'Initialize a QueueJoinThread.
Args:
queue: The queue for this thread to join.'
| def __init__(self, queue):
| threading.Thread.__init__(self)
self.setDaemon(True)
assert isinstance(queue, (Queue.Queue, ReQueue))
self.queue = queue
|
'Perform the queue join in this thread.'
| def run(self):
| self.queue.join()
|
'Instantiate a BulkTransporterApp.
Uploads or downloads data to or from application using HTTP requests.
When run, the class will spin up a number of threads to read entities
from the data source, pass those to a number of worker threads
for sending to the application, and track all of the progress in a
small database ... | def __init__(self, arg_dict, input_generator_factory, throttle, progress_db, progresstrackerthread_factory, max_queue_size=DEFAULT_QUEUE_SIZE, request_manager_factory=RequestManager, datasourcethread_factory=DataSourceThread, progress_queue_factory=Queue.Queue, thread_pool_factory=adaptive_thread_pool.AdaptiveThreadPoo... | self.app_id = arg_dict['application']
self.post_url = arg_dict['url']
self.kind = arg_dict['kind']
self.batch_size = arg_dict['batch_size']
self.input_generator_factory = input_generator_factory
self.num_threads = arg_dict['num_threads']
self.email = arg_dict['email']
self.passin = arg_d... |
'Method that gets called after authentication.'
| def RunPostAuthentication(self):
| if isinstance(self.kind, basestring):
return [self.kind]
return self.kind
|
'Perform the work of the BulkTransporterApp.
Raises:
AuthenticationError: If authentication is required and fails.
Returns:
Error code suitable for sys.exit, e.g. 0 on success, 1 on failure.'
| def Run(self):
| self.error = False
thread_pool = self.thread_pool_factory(self.num_threads, queue_size=self.max_queue_size)
progress_queue = self.progress_queue_factory(self.max_queue_size)
self.request_manager = self.request_manager_factory(self.app_id, self.host_port, self.url_path, self.kind, self.throttle, self.bat... |
'Display a message reporting the final status of the transfer.'
| def ReportStatus(self):
| raise NotImplementedError()
|
'Display a message reporting the final status of the transfer.'
| def ReportStatus(self):
| (total_up, duration) = self.throttle.TotalTransferred(remote_api_throttle.BANDWIDTH_UP)
(s_total_up, unused_duration) = self.throttle.TotalTransferred(remote_api_throttle.HTTPS_BANDWIDTH_UP)
total_up += s_total_up
total = total_up
logger.info('%d entities total, %d previously transfer... |
'Display a message reporting the final status of the transfer.'
| def ReportStatus(self):
| (total_down, duration) = self.throttle.TotalTransferred(remote_api_throttle.BANDWIDTH_DOWN)
(s_total_down, unused_duration) = self.throttle.TotalTransferred(remote_api_throttle.HTTPS_BANDWIDTH_DOWN)
total_down += s_total_down
total = total_down
existing_count = self.progress_thread.existing_count
... |
'Display a message reporting the final status of the transfer.'
| def ReportStatus(self):
| (total_down, duration) = self.throttle.TotalTransferred(remote_api_throttle.BANDWIDTH_DOWN)
(s_total_down, unused_duration) = self.throttle.TotalTransferred(remote_api_throttle.HTTPS_BANDWIDTH_DOWN)
total_down += s_total_down
total = total_down
xfer_count = self.progress_thread.EntitiesTransferred()... |
'JSON string representing the rejected value.
Calling this will fail on the base class since it relies on Message and
Errors being implemented on the class. It is up to a subclass to implement
these methods.
Returns:
JSON string representing the rejected value.'
| def ToJson(self):
| return json.dumps({'error': {'errors': self.Errors(), 'code': 400, 'message': self.Message()}})
|
'Constructor for EnumRejectionError.
Args:
parameter_name: String; the name of the enum parameter which had a value
rejected.
value: The actual value passed in for the enum. Usually string.
allowed_values: List of strings allowed for the enum.'
| def __init__(self, parameter_name, value, allowed_values):
| self.parameter_name = parameter_name
self.value = value
self.allowed_values = allowed_values
|
'A descriptive message describing the error.'
| def Message(self):
| return (_INVALID_ENUM_TEMPLATE % (self.value, self.allowed_values))
|
'A list containing the errors associated with the rejection.
Intended to mimic those returned from an API in production in Google\'s API
infrastructure.
Returns:
A list with a single element that is a dictionary containing the error
information.'
| def Errors(self):
| return [{'domain': 'global', 'reason': 'invalidParameter', 'message': self.Message(), 'locationType': 'parameter', 'location': self.parameter_name}]
|
'Constructor.
Args:
base_env_dict: Dictionary of CGI environment parameters.
dev_appserver: used to call standard SplitURL method.
request: AppServerRequest. Can be None.'
| def __init__(self, base_env_dict, dev_appserver, request=None):
| self.cgi_env = base_env_dict
self.headers = {}
self.http_method = base_env_dict['REQUEST_METHOD']
self.port = base_env_dict['SERVER_PORT']
if request:
(self.path, self.query) = dev_appserver.SplitURL(request.relative_url)
self.body = request.infile.read()
for header in reques... |
'Proxies GET request to discovery service API.
Args:
path: URL path relative to discovery service.
body: HTTP POST request body.
Returns:
HTTP response body or None if it failed.'
| def _DispatchRequest(self, path, body):
| full_path = (self._DISCOVERY_API_PATH_PREFIX + path)
headers = {'Content-type': 'application/json'}
connection = httplib.HTTPSConnection(self._DISCOVERY_PROXY_HOST)
try:
connection.request('POST', full_path, body, headers)
response = connection.getresponse()
response_body = respo... |
'Generates a discovery document from an API file.
Args:
api_config: .api file contents as string.
api_format: \'rest\' or \'rpc\' depending on the which kind of discvoery doc.
Returns:
Discovery doc as JSON string.
Raises:
ValueError: When api_format is invalid.'
| def GenerateDiscoveryDoc(self, api_config, api_format):
| if (api_format not in ['rest', 'rpc']):
raise ValueError('Invalid API format')
path = ('apis/generate/' + api_format)
request_dict = {'config': json.dumps(api_config)}
request_body = json.dumps(request_dict)
return self._DispatchRequest(path, request_body)
|
'Generates an API directory from a list of API files.
Args:
api_configs: list of strings which are the .api file contents.
Returns:
API directory as JSON string.'
| def GenerateDirectory(self, api_configs):
| request_dict = {'configs': api_configs}
request_body = json.dumps(request_dict)
return self._DispatchRequest('apis/generate/directory', request_body)
|
'Returns static content via a GET request.
Args:
path: URL path after the domain.
Returns:
Tuple of (response, response_body):
response: HTTPResponse object.
response_body: Response body as string.'
| def GetStaticFile(self, path):
| connection = httplib.HTTPSConnection(self._STATIC_PROXY_HOST)
try:
connection.request('GET', path, None, {})
response = connection.getresponse()
response_body = response.read()
finally:
connection.close()
return (response, response_body)
|
'Initializes an instance of the DiscoveryService.
Args:
config_manager: an instance of ApiConfigManager.
api_request: an instance of ApiRequest.
outfile: the CGI file object to write the response to.'
| def __init__(self, config_manager, api_request, outfile):
| self._config_manager = config_manager
self._params = json.loads((api_request.body or '{}'))
self._outfile = outfile
self._discovery_proxy = DiscoveryApiProxy()
|
'Sends an HTTP 200 json success response.
Args:
response: Response body as string to return.
Returns:
Sends back an HTTP 200 json success response.'
| def _SendSuccessResponse(self, response):
| headers = {'Content-Type': 'application/json; charset=UTF-8'}
return SendCGIResponse('200', headers, response, self._outfile)
|
'Sends back HTTP response with API directory.
Args:
api_format: Either \'rest\' or \'rpc\'. Sends CGI response containing
the discovery doc for the api/version.
Returns:
None.'
| def _GetRpcOrRest(self, api_format):
| api = self._params['api']
version = self._params['version']
lookup_key = (api, version)
api_config = self._config_manager.configs.get(lookup_key)
if (not api_config):
logging.warn('No discovery doc for version %s of api %s', version, api)
SendCGINotFoundRespon... |
'Sends HTTP response containing the API directory.'
| def _List(self):
| api_configs = []
for api_config in self._config_manager.configs.itervalues():
if (not (api_config == self.API_CONFIG)):
api_configs.append(json.dumps(api_config))
directory = self._discovery_proxy.GenerateDirectory(api_configs)
if (not directory):
logging.error('Failed to ... |
'Returns the result of a discovery service request.
Args:
path: the SPI API path
Returns:
JSON string with result of discovery service API request.'
| def HandleDiscoveryRequest(self, path):
| if (path == self._GET_REST_API):
self._GetRest()
elif (path == self._GET_RPC_API):
self._GetRpc()
elif (path == self._LIST_API):
self._List()
else:
return False
return True
|
'Checks if an SPI is registered with this App.
Args:
config: Parsed app.yaml as an appinfo proto.
Returns:
True if any handler is registered for (/_ah/spi/.*).'
| @staticmethod
def HasSpiEndpoint(config):
| return any((h.url.startswith('/_ah/spi/') for h in config.handlers))
|
'Parses a json api config and registers methods for dispatch.
Side effects:
Parses method name, etc for all methods and updates the indexing
datastructures with the information.
Args:
body: body of getApiConfigs response'
| def ParseApiConfigResponse(self, body):
| try:
response_obj = json.loads(body)
except ValueError as unused_err:
logging.error('Cannot parse BackendService.getApiConfigs response: %s', body)
else:
self._AddDiscoveryConfig()
for api_config_json in response_obj.get('items', []):
try:
... |
'Get a copy of \'methods\' sorted the same way AppEngine sorts them.
Args:
methods: Json configuration of an API\'s methods.
Returns:
The same configuration with the methods sorted based on what order
they\'ll be checked by the server.'
| def _GetSortedMethods(self, methods):
| if (not methods):
return methods
def _SortMethodsComparison(method_info1, method_info2):
"Sort method info by path and http_method.\n\n Args:\n method_info1: Method name and info for the first method ... |
'Creates a safe string to be used as a regex group name.
Only alphanumeric characters and underscore are allowed in variable name
tokens, and numeric are not allowed as the first character.
We cast the matched_parameter to base32 (since the alphabet is safe),
strip the padding (= not safe) and prepend with _, since we ... | @staticmethod
def _ToSafePathParamName(matched_parameter):
| return ('_' + base64.b32encode(matched_parameter).rstrip('='))
|
'Takes a safe regex group name and converts it back to the original value.
Only alphanumeric characters and underscore are allowed in variable name
tokens, and numeric are not allowed as the first character.
The safe_parameter is a base32 representation of the actual value.
Args:
safe_parameter: String, safe regex grou... | @staticmethod
def _FromSafePathParamName(safe_parameter):
| assert safe_parameter.startswith('_')
safe_parameter_as_base32 = safe_parameter[1:]
padding_length = ((- len(safe_parameter_as_base32)) % 8)
padding = ('=' * padding_length)
return base64.b32decode((safe_parameter_as_base32 + padding))
|
'Generates a compiled regex pattern for a path pattern.
e.g. \'/{!name}/{!version}/notes/{id}\'
returns re.compile(r\'/([^:/?#\[\]{}]*)\'
r\'/([^:/?#\[\]{}]*)\'
r\'/notes/(?P<id>[^:/?#\[\]{}]*)\')
Note in this example that !name and !version are reserved variable names
used to match the API name and version that should... | @staticmethod
def CompilePathPattern(pattern):
| def ReplaceReservedVariable(match):
'Replaces a {!variable} with a regex to match it not by name.\n\n Args:\n match: The matching regex group as sent by re.sub()\n\n Returns:... |
'Store JsonRpc api methods in a map for lookup at call time.
(rpcMethodName, apiVersion) => method.
Args:
method_name: Name of the API method
version: Version of the API
method: method descriptor (as in the api config file).'
| def SaveRpcMethod(self, method_name, version, method):
| self._rpc_method_dict[(method_name, version)] = method
|
'Lookup the JsonRPC method at call time.
The method is looked up in self._rpc_method_dict, the dictionary that
it is saved in for SaveRpcMethod().
Args:
method_name: String name of the method
version: String version of the API
Returns:
Method descriptor as specified in the API configuration.'
| def LookupRpcMethod(self, method_name, version):
| method = self._rpc_method_dict.get((method_name, version))
return method
|
'Store Rest api methods in a list for lookup at call time.
The list is self._rest_methods, a list of tuples:
[(<compiled_path>, <path_pattern>, <method_dict>), ...]
where:
<compiled_path> is a compiled regex to match against the incoming URL
<path_pattern> is a string representing the original path pattern,
checked on ... | def SaveRestMethod(self, method_name, version, method):
| path_pattern = (_API_REST_PATH_FORMAT % method.get('path', ''))
http_method = method.get('httpMethod', '').lower()
for (_, path, methods) in self._rest_methods:
if (path == path_pattern):
methods[(http_method, version)] = (method_name, method)
break
else:
self._re... |
'Gets path parameters from a regular expression match.
Args:
match: _sre.SRE_Match object for a path.
Returns:
A dictionary containing the variable names converted from base64'
| @staticmethod
def _GetPathParams(match):
| result = {}
for (var_name, value) in match.groupdict().iteritems():
actual_var_name = ApiConfigManager._FromSafePathParamName(var_name)
result[actual_var_name] = value
return result
|
'Look up the rest method at call time.
The method is looked up in self._rest_methods, the list it is saved
in for SaveRestMethod.
Args:
path: Path from the URL of the request.
http_method: HTTP method of the request.
Returns:
Tuple of (<method name>, <method>, <params>)
Where:
<method name> is the string name of the me... | def LookupRestMethod(self, path, http_method):
| for (compiled_path_pattern, unused_path, methods) in self._rest_methods:
match = compiled_path_pattern.match(path)
if match:
params = self._GetPathParams(match)
version = match.group(2)
method_key = (http_method.lower(), version)
(method_name, method) ... |
'Returns the next n times that match the schedule, starting at time start.
Arguments:
start: a datetime to start from. Matches will start from after this time.
n: the number of matching times to return
Returns:
a list of n datetime objects'
| def GetMatches(self, start, n):
| out = []
for _ in range(n):
start = self.GetMatch(start)
out.append(start)
return out
|
'Returns the next match after time start.
Must be implemented in subclasses.
Arguments:
start: a datetime to start from. Matches will start from after this time.
This may be in any pytz time zone, or it may be timezone-naive
(interpreted as UTC).
Returns:
a datetime object in the timezone of the input \'start\''
| def GetMatch(self, start):
| raise NotImplementedError
|
'Returns the next match after \'start\'.
Arguments:
start: a datetime to start from. Matches will start from after this time.
This may be in any pytz time zone, or it may be timezone-naive
(interpreted as UTC).
Returns:
a datetime object in the timezone of the input \'start\''
| def GetMatch(self, start):
| if (self.start_time is None):
return (start + datetime.timedelta(seconds=self.seconds))
t = _ToTimeZone(start, self.timezone)
start_time = self._GetPreviousDateTime(t, self.start_time)
t_delta = (t - start_time)
t_delta_seconds = (((t_delta.days * 60) * 24) + t_delta.seconds)
num_interva... |
'Returns true if \'t\' falls between start_time and end_time, inclusive.
Arguments:
t: a datetime object, in self.timezone
Returns:
a boolean'
| def _TimeIsInRange(self, t):
| previous_start_time = self._GetPreviousDateTime(t, self.start_time)
previous_end_time = self._GetPreviousDateTime(t, self.end_time)
if (previous_start_time > previous_end_time):
return True
else:
return (t == previous_end_time)
|
'Returns the latest datetime <= \'t\' that has the time target_time.
Arguments:
t: a datetime.datetime object, in self.timezone
target_time: a datetime.time object, in self.timezone
Returns:
a datetime.datetime object, in self.timezone'
| @staticmethod
def _GetPreviousDateTime(t, target_time):
| date = t.date()
while True:
result = IntervalTimeSpecification._CombineDateAndTime(date, target_time)
if (result <= t):
return result
date -= datetime.timedelta(days=1)
|
'Returns the earliest datetime > \'t\' that has the time target_time.
Arguments:
t: a datetime.datetime object, in self.timezone
target_time: a time object, in self.timezone
Returns:
a datetime.datetime object, in self.timezone'
| @staticmethod
def _GetNextDateTime(t, target_time):
| date = t.date()
while True:
result = IntervalTimeSpecification._CombineDateAndTime(date, target_time)
if (result > t):
return result
date += datetime.timedelta(days=1)
|
'Creates a datetime object from date and time objects.
This is similar to the datetime.combine method, but its timezone
calculations are designed to work with pytz.
Arguments:
date: a datetime.date object, in any timezone
time: a datetime.time object, in any timezone
Returns:
a datetime.datetime object, in the timezone... | @staticmethod
def _CombineDateAndTime(date, time):
| if time.tzinfo:
naive_result = datetime.datetime(date.year, date.month, date.day, time.hour, time.minute, time.second)
try:
return time.tzinfo.localize(naive_result, is_dst=None)
except AmbiguousTimeError:
return min(time.tzinfo.localize(naive_result, is_dst=True), ti... |
'Returns matching days for the given year and month.
For the given year and month, return the days that match this instance\'s
day specification, based on either (a) the ordinals and weekdays, or
(b) the explicitly specified monthdays. If monthdays are specified,
dates that fall outside the range of the month will not... | def _MatchingDays(self, year, month):
| (start_day, last_day) = calendar.monthrange(year, month)
if self.monthdays:
return sorted([day for day in self.monthdays if (day <= last_day)])
out_days = []
start_day = ((start_day + 1) % 7)
for ordinal in self.ordinals:
for weekday in self.weekdays:
day = (((weekday - s... |
'Creates a generator that produces results from the set \'matches\'.
Matches must be >= \'start\'. If none match, the wrap counter is incremented,
and the result set is reset to the full set. Yields a 2-tuple of (match,
wrapcount).
Arguments:
start: first set of matches will be >= this value (an int)
matches: the set o... | def _NextMonthGenerator(self, start, matches):
| potential = matches = sorted(matches)
after = (start - 1)
wrapcount = 0
while True:
potential = [x for x in potential if (x > after)]
if (not potential):
wrapcount += 1
potential = matches
after = potential[0]
(yield (after, wrapcount))
|
'Returns the next match after time start.
Must be implemented in subclasses.
Arguments:
start: a datetime to start from. Matches will start from after this time.
This may be in any pytz time zone, or it may be timezone-naive
(interpreted as UTC).
Returns:
a datetime object in the timezone of the input \'start\''
| def GetMatch(self, start):
| start_time = _ToTimeZone(start, self.timezone).replace(tzinfo=None)
if self.months:
months = self._NextMonthGenerator(start_time.month, self.months)
while True:
(month, yearwraps) = months.next()
candidate_month = start_time.replace(day=1, month=month, year=(start_time.year + yearwra... |
'Raise an exception if the input fails to parse correctly.
Overriding the default, which normally just prints a message to
stderr.
Arguments:
msg: the error message
Raises:
GrocException: always.'
| def emitErrorMessage(self, msg):
| raise GrocException(msg)
|
'Raise an exception if the input fails to parse correctly.
Overriding the default, which normally just prints a message to
stderr.
Arguments:
msg: the error message
Raises:
GrocException: always.'
| def emitErrorMessage(self, msg):
| raise GrocException(msg)
|
'Constructor.
Args:
query: Starting query, a datastore_pb.Query.
last_cursor: A compiled cursor, the last from a result list.
offset: The number of entities we\'ve seen so far.'
| def __init__(self, query, last_cursor, offset):
| self.__count = _MAX_INT_32
if query.has_count():
self.__count = query.count()
elif query.has_limit():
self.__count = query.limit()
self.__query = query
self.__last_cursor = last_cursor
self.__creation = time.time()
self.__offset = offset
|
'Constructor.
Args:
app_id: string
datastore_location: location of datastore server
history_file: DEPRECATED. No-op.
require_indexes: bool, default False. If True, composite indexes must
exist in index.yaml for queries that need them.
service_name: Service name expected for all calls.
trusted: bool, default False. If... | def __init__(self, app_id, datastore_location, history_file=None, require_indexes=False, service_name='datastore_v3', trusted=False, root_path='/var/apps/'):
| super(DatastoreDistributed, self).__init__(service_name)
assert (isinstance(app_id, basestring) and (app_id != ''))
self.__app_id = app_id
self.__datastore_location = datastore_location
self.__index_cache = {}
self.__is_encrypted = True
res = self.__datastore_location.split(':')
if (len(... |
'Gets a cursor identifier.'
| def __getCursorID(self):
| self.__cursor_lock.acquire()
self.__cursor_id += 1
cursor_id = self.__cursor_id
self.__cursor_lock.release()
return cursor_id
|
'Clears the datastore by deleting all currently stored entities and
queries.'
| def Clear(self):
| pass
|
'Set/clear the trusted bit in the stub.
This bit indicates that the app calling the stub is trusted. A
trusted app can write to datastores of other apps.
Args:
trusted: boolean.'
| def SetTrusted(self, trusted):
| self.__trusted = trusted
|
'Verify that this is the stub for app_id.
Args:
app_id: An application ID.
Raises:
datastore_errors.BadRequestError: if this is not the stub for app_id.'
| def __ValidateAppId(self, app_id):
| assert app_id
if ((not self.__trusted) and (app_id != self.__app_id)):
raise datastore_errors.BadRequestError(("app %s cannot access app %s's data" % (self.__app_id, app_id)))
|
'Validate this key.
Args:
key: entity_pb.Reference
Raises:
datastore_errors.BadRequestError: if the key is invalid'
| def __ValidateKey(self, key):
| assert isinstance(key, entity_pb.Reference)
self.__ValidateAppId(key.app())
for elem in key.path().element_list():
if (elem.has_id() == elem.has_name()):
raise datastore_errors.BadRequestError(('each key path element should have id or name but not both: ... |
'Get (app, kind) tuple from given key.
The (app, kind) tuple is used as an index into several internal
dictionaries, e.g. __entities.
Args:
key: entity_pb.Reference
Returns:
Tuple (app, kind), both are unicode strings.'
| def _AppIdNamespaceKindForKey(self, key):
| last_path = key.path().element_list()[(-1)]
return (datastore_types.EncodeAppIdNamespace(key.app(), key.name_space()), last_path.type())
|
'Does Nothing'
| def Read(self):
| return
|
'Does Nothing'
| def Write(self):
| return
|
'Does Nothing'
| def Flush(self):
| return
|
'The main RPC entry point. service must be \'datastore_v3\'.'
| def MakeSyncCall(self, service, call, request, response, request_id=None):
| self.assertPbIsInitialized(request)
super(DatastoreDistributed, self).MakeSyncCall(service, call, request, response, request_id)
self.assertPbIsInitialized(response)
|
'Raises an exception if the given PB is not initialized and valid.'
| def assertPbIsInitialized(self, pb):
| explanation = []
assert pb.IsInitialized(explanation), explanation
pb.Encode()
|
'Returns a dict that maps Query PBs to times they\'ve been run.'
| def QueryHistory(self):
| return []
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.