desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Read header lines. Read header lines up to the entirely blank line that terminates them. The (normally blank) line that ends the headers is skipped, but not included in the returned list. If a non-header line ends the headers, (which is an error), an attempt is made to backspace over it; it is never included in the r...
def readheaders(self):
self.dict = {} self.unixfrom = '' self.headers = hlist = [] self.status = '' headerseen = '' firstline = 1 startofline = unread = tell = None if hasattr(self.fp, 'unread'): unread = self.fp.unread elif self.seekable: tell = self.fp.tell while True: if tell...
'Return list of (header, value) tuples.'
def getheaders(self):
if (self.msg is None): raise ResponseNotReady() return self.msg.items()
'Sets up the host and the port for the HTTP CONNECT Tunnelling. The headers argument should be a mapping of extra HTTP headers to send with the CONNECT request. App Engine Note: This method is not supported.'
def set_tunnel(self, host, port=None, headers=None):
raise NotImplementedError('HTTP CONNECT Tunnelling is not supported')
'Send `data\' to the server.'
def send(self, data):
self._body += data
'Send a request to the server. `method\' specifies an HTTP request method, e.g. \'GET\'. `url\' specifies the object being requested, e.g. \'/index.html\'. `skip_host\' if True does not add automatically a \'Host:\' header `skip_accept_encoding\' if True does not add automatically an \'Accept-Encoding:\' header App Eng...
def putrequest(self, method, url, skip_host=0, skip_accept_encoding=0):
self._method = method self._url = url
'Send a request header line to the server. For example: h.putheader(\'Accept\', \'text/html\')'
def putheader(self, header, *values):
hdr = '\r\n DCTB '.join([str(v) for v in values]) self.headers.append((header, hdr))
'Indicate that the last header line has been sent to the server. This method sends the request to the server. The optional message_body argument can be used to pass message body associated with the request. The message body will be sent in the same packet as the message headers if possible. The message_body should b...
def endheaders(self, message_body=None):
if (message_body is not None): self.send(message_body)
'Send a complete request to the server.'
def request(self, method, url, body=None, headers=None):
self._method = method self._url = url try: self._body = body.read() except AttributeError: self._body = body if (headers is None): headers = [] elif hasattr(headers, 'items'): headers = headers.items() self.headers = headers
'Get the response from the server. App Engine Note: buffering is ignored.'
def getresponse(self, buffering=False):
from google.appengine.api import urlfetch import socket if (self.port and (self.port != self.default_port)): host = ('%s:%s' % (self.host, self.port)) else: host = self.host if (not self._url.startswith(self._protocol)): url = ('%s://%s%s' % (self._protocol, host, self._url))...
'Provide a default host, since the superclass requires one.'
def __init__(self, host='', port=None, strict=None):
if (port == 0): port = None self._setup(self._connection_class(host, port, strict))
'Accept arguments to set the host/port, since the superclass doesn\'t.'
def connect(self, host=None, port=None):
self.__init__(host, port)
'Provide a getfile, since the superclass\' does not use this concept.'
def getfile(self):
return self.file
'The superclass allows only one value argument.'
def putheader(self, header, *values):
self._conn.putheader(header, '\r\n DCTB '.join([str(v) for v in values]))
'Compat definition since superclass does not define it. Returns a tuple consisting of: - server status code (e.g. \'200\' if all goes well) - server "reason" corresponding to status code - any RFC822 headers in the response from the server'
def getreply(self, buffering=False):
response = self._conn.getresponse() self.headers = response.msg self.file = response.fp return (response.status, response.reason, response.msg)
'dup() -> socket object Return a new socket object connected to the same system resource.'
def dup(self):
return _socketobject(_sock=self._sock)
'makefile([mode[, bufsize]]) -> file object Return a regular file object corresponding to the socket. The mode and bufsize arguments are as for the built-in open() function.'
def makefile(self, mode='r', bufsize=(-1)):
return _fileobject(self._sock, mode, bufsize)
'Initialize. Initializes self.value to the value in request header, or DEFAULT if not defined in headers. Args: headers: request headers.'
def __init__(self, headers):
self.value = self.DEFAULT for k in headers: if (k.lower() == self.HEADER.lower()): self.value = headers[k] break
'Initialize. Args: filename: a Google Storage filename of form \'/bucket/filename\'. st_size: file size in bytes. long compatible. etag: hex digest of the md5 hash of the file\'s content. str. st_ctime: posix file creation time. float compatible. content_type: content type. str. metadata: a str->str dict of user specif...
def __init__(self, filename, st_size, etag, st_ctime, content_type=None, metadata=None):
self.filename = filename self.st_size = long(st_size) self.st_ctime = float(st_ctime) if ((etag[0] == '"') and (etag[(-1)] == '"')): etag = etag[1:(-1)] self.etag = etag self.content_type = content_type self.metadata = metadata
'Initialize. Args: blob_storage: apphosting.api.blobstore.blobstore_stub.BlobStorage instance'
def __init__(self, blob_storage):
self.blob_storage = blob_storage
'Get blobkey for filename. Args: filename: gs filename of form /bucket/filename. Returns: blobinfo\'s datastore\'s key name, aka, blobkey.'
def _filename_to_blobkey(self, filename):
common.validate_file_path(filename) return blobstore_stub.BlobstoreServiceStub.CreateEncodedGoogleStorageKey(filename)
'Start object creation with a POST. This implements the resumable upload XML API. Args: filename: gs filename of form /bucket/filename. options: a dict containing all user specified request headers. e.g. {\'content-type\': \'foo\', \'x-goog-meta-bar\': \'bar\'}. Returns: a token used for continuing upload. Also used as...
def post_start_creation(self, filename, options):
common.validate_file_path(filename) token = self._filename_to_blobkey(filename) gcs_file = _AE_GCSFileInfo_.get_by_key_name(token) self._cleanup_old_file(gcs_file) new_file = _AE_GCSFileInfo_(key_name=token, filename=filename, finalized=False) new_file.options = options new_file.put() re...
'Clean up the old version of a file. The old version may or may not be finalized yet. Either way, when user tries to create a file that already exists, we delete the old version first. Args: gcs_file: an instance of _AE_GCSFileInfo_.'
def _cleanup_old_file(self, gcs_file):
if gcs_file: if gcs_file.finalized: blobkey = gcs_file.key().name() self.blob_storage.DeleteBlob(blobkey) else: db.delete(_AE_GCSPartialFile_.all().ancestor(gcs_file)) gcs_file.delete()
'Continue object upload with PUTs. This implements the resumable upload XML API. Args: token: upload token returned by post_start_creation. content: object content. content_range: a (start, end) tuple specifying the content range of this chunk. Both are inclusive according to XML API. last: True if this is the last chu...
def put_continue_creation(self, token, content, content_range, last=False):
gcs_file = _AE_GCSFileInfo_.get_by_key_name(token) if (not gcs_file): raise ValueError('Invalid token') if content: (start, end) = content_range if (len(content) != ((end - start) + 1)): raise ValueError(('Invalid content range %d-%d' % content_range)) ...
'End object upload. Args: token: upload token returned by post_start_creation. Raises: ValueError: if token is invalid. Or file is corrupted during upload. Save file content to blobstore. Save blobinfo and _AE_GCSFileInfo.'
def _end_creation(self, token):
gcs_file = _AE_GCSFileInfo_.get_by_key_name(token) if (not gcs_file): raise ValueError('Invalid token') (error_msg, content) = self._get_content(gcs_file) if error_msg: raise ValueError(error_msg) gcs_file.etag = hashlib.md5(content).hexdigest() gcs_file.creation = datetime.da...
'Aggregate all partial content of the gcs_file. Args: gcs_file: an instance of _AE_GCSFileInfo_. Returns: (error_msg, content) tuple. error_msg is set if the file is corrupted during upload. Otherwise content is set to the aggregation of all partial contents.'
@db.transactional def _get_content(self, gcs_file):
content = '' previous_end = 0 error_msg = '' for partial in _AE_GCSPartialFile_.all().ancestor(gcs_file).order('start'): if (not error_msg): if (partial.start < previous_end): error_msg = 'File is corrupted due to missing chunks.' elif (p...
'Get bucket listing with a GET. Args: bucketpath: gs bucket path of form \'/bucket\' prefix: prefix to limit listing. marker: a str after which to start listing. max_keys: max size of listing. See https://developers.google.com/storage/docs/reference-methods#getbucket for details. Returns: A list of CSFileStat sorted by...
def get_bucket(self, bucketpath, prefix, marker, max_keys):
common.validate_bucket_path(bucketpath) q = _AE_GCSFileInfo_.all(namespace='') fully_qualified_prefix = '/'.join([bucketpath, prefix]) if marker: q.filter('filename >', '/'.join([bucketpath, marker])) else: q.filter('filename >=', fully_qualified_prefix) result = [] for...
'Get file content with a GET. Args: filename: gs filename of form \'/bucket/filename\'. start: start offset to request. Inclusive. end: end offset to request. Inclusive. Returns: The segment of file content requested. Raises: ValueError: if file doesn\'t exist.'
def get_object(self, filename, start=0, end=None):
common.validate_file_path(filename) blobkey = self._filename_to_blobkey(filename) gsfileinfo = _AE_GCSFileInfo_.get_by_key_name(blobkey) if ((not gsfileinfo) or (not gsfileinfo.finalized)): raise ValueError('File does not exist.') local_file = self.blob_storage.OpenBlob(blobkey) ...
'Get file stat with a HEAD. Args: filename: gs filename of form \'/bucket/filename\' Returns: A CSFileStat object containing file stat. None if file doesn\'t exist.'
def head_object(self, filename):
common.validate_file_path(filename) blobkey = self._filename_to_blobkey(filename) info = _AE_GCSFileInfo_.get_by_key_name(blobkey) if (info and info.finalized): metadata = common.get_metadata(info.options) filestat = common.CSFileStat(filename=info.filename, st_size=info.size, etag=info....
'Delete file with a DELETE. Args: filename: gs filename of form \'/bucket/filename\' Returns: True if file is deleted. False if file doesn\'t exist.'
def delete_object(self, filename):
common.validate_file_path(filename) blobkey = self._filename_to_blobkey(filename) gsfileinfo = _AE_GCSFileInfo_.get_by_key_name(blobkey) if (not gsfileinfo): return False gsfileinfo.delete() self.blob_storage.DeleteBlob(blobkey) return True
'Initialize a KeyRange object. Args: key_start: The starting key for this range (db.Key or ndb.Key). key_end: The ending key for this range (db.Key or ndb.Key). direction: The direction of the query for this range. include_start: Whether the start key should be included in the range. include_end: Whether the end key sh...
def __init__(self, key_start=None, key_end=None, direction=None, include_start=True, include_end=True, namespace=None, _app=None):
if (direction is None): direction = KeyRange.ASC assert (direction in (KeyRange.ASC, KeyRange.DESC)) self.direction = direction if (ndb is not None): if isinstance(key_start, ndb.Key): key_start = key_start.to_old_key() if isinstance(key_end, ndb.Key): key...
'Updates the start of the range immediately past the specified key. Args: key: A db.Key or ndb.Key.'
def advance(self, key):
self.include_start = False if (ndb is not None): if isinstance(key, ndb.Key): key = key.to_old_key() self.key_start = key
'Add query filter to restrict to this key range. Args: query: A db.Query or ndb.Query instance. filters: optional list of filters to apply to the query. Each filter is a tuple: (<property_name_as_str>, <query_operation_as_str>, <value>). User filters are applied first. Returns: The input query restricted to this key ra...
def filter_query(self, query, filters=None):
if (ndb is not None): if _IsNdbQuery(query): return self.filter_ndb_query(query, filters=filters) assert (not _IsNdbQuery(query)) if filters: for f in filters: query.filter(('%s %s' % (f[0], f[1])), f[2]) if self.include_start: start_comparator = '>=' ...
'Add query filter to restrict to this key range. Args: query: An ndb.Query instance. filters: optional list of filters to apply to the query. Each filter is a tuple: (<property_name_as_str>, <query_operation_as_str>, <value>). User filters are applied first. Returns: The input query restricted to this key range.'
def filter_ndb_query(self, query, filters=None):
assert _IsNdbQuery(query) if filters: for f in filters: query = query.filter(ndb.FilterNode(*f)) if self.include_start: start_comparator = '>=' else: start_comparator = '>' if self.include_end: end_comparator = '<=' else: end_comparator = '<' ...
'Add query filter to restrict to this key range. Args: query: A datastore.Query instance. filters: optional list of filters to apply to the query. Each filter is a tuple: (<property_name_as_str>, <query_operation_as_str>, <value>). User filters are applied first. Returns: The input query restricted to this key range.'
def filter_datastore_query(self, query, filters=None):
assert isinstance(query, datastore.Query) if filters: for f in filters: query.update({('%s %s' % (f[0], f[1])): f[2]}) if self.include_start: start_comparator = '>=' else: start_comparator = '>' if self.include_end: end_comparator = '<=' else: ...
'Check that self.direction is in (KeyRange.ASC, KeyRange.DESC). Args: asc: Argument to return if self.direction is KeyRange.ASC desc: Argument to return if self.direction is KeyRange.DESC Returns: asc or desc appropriately Raises: KeyRangeError: if self.direction is not in (KeyRange.ASC, KeyRange.DESC).'
def __get_direction(self, asc, desc):
if (self.direction == KeyRange.ASC): return asc elif (self.direction == KeyRange.DESC): return desc else: raise KeyRangeError('KeyRange direction unexpected: %s', self.direction)
'Construct a query for this key range, including the scan direction. Args: kind_class: A kind implementation class (a subclass of either db.Model or ndb.Model). keys_only: bool, default False, use keys_only on Query? Returns: A db.Query or ndb.Query instance (corresponding to kind_class). Raises: KeyRangeError: if self...
def make_directed_query(self, kind_class, keys_only=False):
if (ndb is not None): if issubclass(kind_class, ndb.Model): return self.make_directed_ndb_query(kind_class, keys_only=keys_only) assert (self._app is None), '_app is not supported for db.Query' direction = self.__get_direction('', '-') query = db.Query(kind_class, name...
'Construct an NDB query for this key range, including the scan direction. Args: kind_class: An ndb.Model subclass. keys_only: bool, default False, use keys_only on Query? Returns: An ndb.Query instance. Raises: KeyRangeError: if self.direction is not in (KeyRange.ASC, KeyRange.DESC).'
def make_directed_ndb_query(self, kind_class, keys_only=False):
assert issubclass(kind_class, ndb.Model) if keys_only: default_options = ndb.QueryOptions(keys_only=True) else: default_options = None query = kind_class.query(app=self._app, namespace=self.namespace, default_options=default_options) query = self.filter_ndb_query(query) if self._...
'Construct a query for this key range, including the scan direction. Args: kind: A string. keys_only: bool, default False, use keys_only on Query? Returns: A datastore.Query instance. Raises: KeyRangeError: if self.direction is not in (KeyRange.ASC, KeyRange.DESC).'
def make_directed_datastore_query(self, kind, keys_only=False):
direction = self.__get_direction(datastore.Query.ASCENDING, datastore.Query.DESCENDING) query = datastore.Query(kind, _app=self._app, keys_only=keys_only) query.Order(('__key__', direction)) query = self.filter_datastore_query(query) return query
'Construct a query for this key range without setting the scan direction. Args: kind_class: A kind implementation class (a subclass of either db.Model or ndb.Model). keys_only: bool, default False, query only for keys. filters: optional list of filters to apply to the query. Each filter is a tuple: (<property_name_as_s...
def make_ascending_query(self, kind_class, keys_only=False, filters=None):
if (ndb is not None): if issubclass(kind_class, ndb.Model): return self.make_ascending_ndb_query(kind_class, keys_only=keys_only, filters=filters) assert (self._app is None), '_app is not supported for db.Query' query = db.Query(kind_class, namespace=self.namespace, keys_o...
'Construct an NDB query for this key range, without the scan direction. Args: kind_class: An ndb.Model subclass. keys_only: bool, default False, query only for keys. Returns: An ndb.Query instance.'
def make_ascending_ndb_query(self, kind_class, keys_only=False, filters=None):
assert issubclass(kind_class, ndb.Model) if keys_only: default_options = ndb.QueryOptions(keys_only=True) else: default_options = None query = kind_class.query(app=self._app, namespace=self.namespace, default_options=default_options) query = self.filter_ndb_query(query, filters=filte...
'Construct a query for this key range without setting the scan direction. Args: kind: A string. keys_only: bool, default False, use keys_only on Query? filters: optional list of filters to apply to the query. Each filter is a tuple: (<property_name_as_str>, <query_operation_as_str>, <value>). User filters are applied f...
def make_ascending_datastore_query(self, kind, keys_only=False, filters=None):
query = datastore.Query(kind, namespace=self.namespace, _app=self._app, keys_only=keys_only) query.Order(('__key__', datastore.Query.ASCENDING)) query = self.filter_datastore_query(query, filters=filters) return query
'Split this key range into a list of at most two ranges. This method attempts to split the key range approximately in half. Numeric ranges are split in the middle into two equal ranges and string ranges are split lexicographically in the middle. If the key range is smaller than batch_size it is left unsplit. Note that...
def split_range(self, batch_size=0):
key_start = self.key_start key_end = self.key_end include_start = self.include_start include_end = self.include_end key_pairs = [] if (not key_start): key_pairs.append((key_start, include_start, key_end, include_end, KeyRange.ASC)) elif (not key_end): key_pairs.append((key_st...
'Compare two key ranges. Key ranges with a value of None for key_start or key_end, are always considered to have include_start=False or include_end=False, respectively, when comparing. Since None indicates an unbounded side of the range, the include specifier is meaningless. The ordering generated is total but somewh...
def __cmp__(self, other):
if (not isinstance(other, KeyRange)): return 1 self_list = [self.key_start, self.key_end, self.direction, self.include_start, self.include_end, self._app, self.namespace] if (not self.key_start): self_list[3] = False if (not self.key_end): self_list[4] = False other_list = [o...
'Returns a string that is approximately in the middle of the range. (start, end) is treated as a string range, and it is assumed start <= end in the usual lexicographic string ordering. The output key mid is guaranteed to satisfy start <= mid <= end. The method proceeds by comparing initial characters of start and end....
@staticmethod def bisect_string_range(start, end):
if (start == end): return start start += '\x00' end += '\x00' midpoint = [] expected_max = 127 for i in xrange(min(len(start), len(end))): if (start[i] == end[i]): midpoint.append(start[i]) else: ord_sum = (ord(start[i]) + ord(end[i])) ...
'Return a key that is between key_start and key_end inclusive. This method compares components of the ancestor paths of key_start and key_end. The first place in the path that differs is approximately split in half. If the kind components differ, a new non-existent kind halfway between the two is used to split the sp...
@staticmethod def split_keys(key_start, key_end, batch_size):
if (ndb is not None): if isinstance(key_start, ndb.Key): key_start = key_start.to_old_key() if isinstance(key_end, ndb.Key): key_end = key_end.to_old_key() assert (key_start.app() == key_end.app()) assert (key_start.namespace() == key_end.namespace()) path1 = key_...
'Return an id_or_name that is between id_or_name1 an id_or_name2. Attempts to split the range [id_or_name1, id_or_name2] in half, unless maintain_batches is true and the size of the range [id_or_name1, id_or_name2] is less than or equal to batch_size. Args: id_or_name1: A number or string or the id_or_name component of...
@staticmethod def _split_id_or_name(id_or_name1, id_or_name2, batch_size, maintain_batches):
if (isinstance(id_or_name1, (int, long)) and isinstance(id_or_name2, (int, long))): if ((not maintain_batches) or ((id_or_name2 - id_or_name1) > batch_size)): return ((id_or_name1 + id_or_name2) / 2) else: return id_or_name1 elif (isinstance(id_or_name1, basestring) and i...
'Guess the end of a key range with a binary search of probe queries. When the \'key_start\' parameter has a key hierarchy, this function will only determine the key range for keys in a similar hierarchy. That means if the keys are in the form: kind=Foo, name=bar/kind=Stuff, name=meep only this range will be probed: kin...
@staticmethod def guess_end_key(kind, key_start, probe_count=30, split_rate=5):
if (ndb is not None): if isinstance(key_start, ndb.Key): key_start = key_start.to_old_key() app = key_start.app() namespace = key_start.namespace() full_path = key_start.to_path() for (index, piece) in enumerate(full_path): if ((index % 2) == 0): continue ...
'Serialize KeyRange to json. Returns: string with KeyRange json representation.'
def to_json(self):
if (simplejson is None): raise SimplejsonUnavailableError('JSON functionality requires json or simplejson to be available') def key_to_str(key): if key: return str(key) else: return None obj_dict = {'direction': self.direction, 'key_sta...
'Deserialize KeyRange from its json representation. Args: json_str: string with json representation created by key_range_to_json. Returns: deserialized KeyRange instance.'
@staticmethod def from_json(json_str):
if (simplejson is None): raise SimplejsonUnavailableError('JSON functionality requires json or simplejson to be available') def key_from_str(key_str): if key_str: return db.Key(key_str) else: return None json = simplejson.loads(json_str...
'Constructs a new RemoteStub that communicates with the specified server. Args: server: An instance of a subclass of google.appengine.tools.appengine_rpc.AbstractRpcServer. path: The path to the handler this stub should send requests to.'
def __init__(self, server, path, _test_stub_map=None):
self._server = server self._path = path self._test_stub_map = _test_stub_map
'Returns the id of the request associated with the current thread.'
@classmethod def _GetRequestId(cls):
try: return cls._local.request_id except AttributeError: return None
'Set the id of the request associated with the current thread.'
@classmethod def _SetRequestId(cls, request_id):
cls._local.request_id = request_id
'Create an RPC that can be used asynchronously.'
def CreateRPC(self):
return apiproxy_rpc.RealRPC(stub=self)
'Constructor. Args: server: The server name to connect to. path: The URI path on the server. default_result_count: The number of items to fetch, by default, in a datastore Query or Next operation. This affects the batch size of query iterators.'
def __init__(self, server, path, default_result_count=20, _test_stub_map=None):
super(RemoteDatastoreStub, self).__init__(server, path, _test_stub_map) self.default_result_count = default_result_count self.__queries = {} self.__transactions = {} self.__next_local_cursor = 1 self.__local_cursor_lock = threading.Lock() self.__next_local_tx = 1 self.__local_tx_lock = t...
'Create an RPC that can be used asynchronously.'
def CreateRPC(self):
return apiproxy_rpc.RealRPC(stub=self)
'Register this thread with the throttler.'
def Register(self, thread):
thread_id = id(thread) for throttle_name in self.throttles.iterkeys(): self.transferred[throttle_name][thread_id] = 0 self.prior_block[throttle_name][thread_id] = 0 self.totals[throttle_name][thread_id] = 0
'Add a count to the amount this thread has transferred. Each time a thread transfers some data, it should call this method to note the amount sent. The counts may be rotated if sufficient time has passed since the last rotation. Args: throttle_name: The name of the throttle to add to. token_count: The number to add to ...
def AddTransfer(self, throttle_name, token_count):
self.VerifyThrottleName(throttle_name) transferred = self.transferred[throttle_name] try: transferred[id(threading.currentThread())] += token_count except KeyError: thread = threading.currentThread() raise ThreadNotRegisteredError(('Unregistered thread accessing throttle...
'Possibly sleep in order to limit the transfer rate. Note that we sleep based on *prior* transfers rather than what we may be about to transfer. The next transfer could put us under/over and that will be rectified *after* that transfer. Net result is that the average transfer rate will remain within bounds. Spiky behav...
def Sleep(self, throttle_name=None):
if (throttle_name is None): for throttle_name in self.throttles: self.Sleep(throttle_name=throttle_name) return self.VerifyThrottleName(throttle_name) thread = threading.currentThread() while True: duration = (self.get_time() - self.last_rotate[throttle_name]) ...
'Calculate the time to sleep on a throttle. Args: total: The total amount transferred. limit: The amount per second that is allowed to be sent. duration: The amount of time taken to send the total. Returns: A float for the amount of time to sleep.'
def _SleepTime(self, total, limit, duration):
if (not limit): return 0.0 return max(0.0, ((total / limit) - duration))
'Rotate the transfer counters. If sufficient time has passed, then rotate the counters from active to the prior-block of counts. This rotation is interlocked to ensure that multiple threads do not over-rotate the counts. Args: throttle_name: The name of the throttle to rotate.'
def _RotateCounts(self, throttle_name):
self.VerifyThrottleName(throttle_name) self.rotate_mutex[throttle_name].acquire() try: next_rotate_time = (self.last_rotate[throttle_name] + self.ROTATE_PERIOD) if (next_rotate_time >= self.get_time()): return for (name, count) in self.transferred[throttle_name].items(): ...
'Return the total transferred, and over what period. Args: throttle_name: The name of the throttle to total. Returns: A tuple of the total count and running time for the given throttle name.'
def TotalTransferred(self, throttle_name):
total = 0 for count in self.totals[throttle_name].values(): total += count for count in self.transferred[throttle_name].values(): total += count return (total, (self.get_time() - self.start_time))
'Initialize a ThrottleHandler. Args: throttle: A Throttle instance to call for bandwidth and http/https request throttling.'
def __init__(self, throttle):
self.throttle = throttle
'Add to bandwidth throttle for given request. Args: throttle_name: The name of the bandwidth throttle to add to. req: The request whose size will be added to the throttle.'
def AddRequest(self, throttle_name, req):
size = 0 for (key, value) in req.headers.iteritems(): size += len(('%s: %s\n' % (key, value))) for (key, value) in req.unredirected_hdrs.iteritems(): size += len(('%s: %s\n' % (key, value))) (unused_scheme, unused_host_port, url_path, unused_query, unused_fragment) = urlparse.urlsp...
'Add to bandwidth throttle for given response. Args: throttle_name: The name of the bandwidth throttle to add to. res: The response whose size will be added to the throttle.'
def AddResponse(self, throttle_name, res):
content = res.read() def ReturnContent(): return content res.read = ReturnContent size = len(content) headers = res.info() for (key, value) in headers.items(): size += len(('%s: %s\n' % (key, value))) self.throttle.AddTransfer(throttle_name, size)
'Process an HTTP request. If the throttle is over quota, sleep first. Then add request size to throttle before returning it to be sent. Args: req: A urllib2.Request object. Returns: The request passed in.'
def http_request(self, req):
self.throttle.Sleep(BANDWIDTH_UP) self.throttle.Sleep(BANDWIDTH_DOWN) self.AddRequest(BANDWIDTH_UP, req) return req
'Process an HTTPS request. If the throttle is over quota, sleep first. Then add request size to throttle before returning it to be sent. Args: req: A urllib2.Request object. Returns: The request passed in.'
def https_request(self, req):
self.throttle.Sleep(HTTPS_BANDWIDTH_UP) self.throttle.Sleep(HTTPS_BANDWIDTH_DOWN) self.AddRequest(HTTPS_BANDWIDTH_UP, req) return req
'Process an HTTP response. The size of the response is added to the bandwidth throttle and the request throttle is incremented by one. Args: unused_req: The urllib2 request for this response. res: A urllib2 response object. Returns: The response passed in.'
def http_response(self, unused_req, res):
self.AddResponse(BANDWIDTH_DOWN, res) self.throttle.AddTransfer(REQUESTS, 1) return res
'Process an HTTPS response. The size of the response is added to the bandwidth throttle and the request throttle is incremented by one. Args: unused_req: The urllib2 request for this response. res: A urllib2 response object. Returns: The response passed in.'
def https_response(self, unused_req, res):
self.AddResponse(HTTPS_BANDWIDTH_DOWN, res) self.throttle.AddTransfer(HTTPS_REQUESTS, 1) return res
'Initialize a ThrottledHttpRpcServer. Also sets request_manager.rpc_server to the ThrottledHttpRpcServer instance. Args: throttle: A Throttles instance. args: Positional arguments to pass through to appengine_rpc.HttpRpcServer.__init__ kwargs: Keyword arguments to pass through to appengine_rpc.HttpRpcServer.__init__'
def __init__(self, throttle, *args, **kwargs):
self.throttle = throttle appengine_rpc.HttpRpcServer.__init__(self, *args, **kwargs)
'Returns an OpenerDirector that supports cookies and ignores redirects. Returns: A urllib2.OpenerDirector object.'
def _GetOpener(self):
opener = appengine_rpc.HttpRpcServer._GetOpener(self) opener.add_handler(ThrottleHandler(self.throttle)) return opener
'Add costs from the Cost protobuf.'
def AddCost(self, cost_proto):
self.__throttle.AddTransfer(INDEX_MODIFICATIONS, cost_proto.index_writes()) self.__throttle.AddTransfer(ENTITIES_MODIFIED, cost_proto.entity_writes()) self.__throttle.AddTransfer(BANDWIDTH_UP, cost_proto.entity_write_bytes())
'Constructor. Args: service: The name of the service _test_stub_map: An APIProxyStubMap to use for testing purposes.'
def __init__(self, service='datastore_v3', _test_stub_map=None):
super(RemoteDatastoreStub, self).__init__(service) if _test_stub_map: self.__call = _test_stub_map.MakeSyncCall else: self.__call = apiproxy_stub_map.MakeSyncCall
'Handle a RunQuery request. We handle RunQuery by executing a Query and a Next and returning the result of the Next request. This method is DEPRECATED, but left in place for older clients.'
def _Dynamic_RunQuery(self, request, response):
runquery_response = datastore_pb.QueryResult() self.__call('datastore_v3', 'RunQuery', request, runquery_response) if (runquery_response.result_size() > 0): response.CopyFrom(runquery_response) return next_request = datastore_pb.NextRequest() next_request.mutable_cursor().CopyFrom(ru...
'Handle a Transaction request. We handle transactions by accumulating Put and Delete requests on the client end, as well as recording the key and hash of Get requests. When Commit is called, Transaction is invoked, which verifies that all the entities in the precondition list still exist and their hashes match, then pe...
def _Dynamic_Transaction(self, request, response):
begin_request = datastore_pb.BeginTransactionRequest() begin_request.set_app(os.environ['APPLICATION_ID']) begin_request.set_allow_multiple_eg(request.allow_multiple_eg()) tx = datastore_pb.Transaction() self.__call('datastore_v3', 'BeginTransaction', begin_request, tx) preconditions = request.p...
'Fetch unique IDs for a set of paths.'
def _Dynamic_GetIDs(self, request, response, is_xg=False):
for entity in request.entity_list(): assert (entity.property_size() == 0) assert (entity.raw_property_size() == 0) assert (entity.entity_group().element_size() == 0) lastpart = entity.key().path().element_list()[(-1)] assert ((lastpart.id() == 0) and (not lastpart.has_name())...
'Handle a GET. Just show an info page.'
def get(self):
if (not self.CheckIsAdmin()): return rtok = self.request.get('rtok', '0') app_info = {'app_id': os.environ['APPLICATION_ID'], 'rtok': rtok} self.response.headers['Content-Type'] = 'text/plain' self.response.out.write(yaml.dump(app_info))
'Handle POST requests by executing the API call.'
def post(self):
if (not self.CheckIsAdmin()): return self.response.headers['Content-Type'] = 'text/plain' response = remote_api_pb.Response() try: request = remote_api_pb.Request() request.ParseFromString(self.request.body) response_data = self.ExecuteRequest(request) response.se...
'Executes an API invocation and returns the response object.'
def ExecuteRequest(self, request):
service = request.service_name() method = request.method() service_methods = SERVICE_PB_MAP.get(service, {}) (request_class, response_class) = service_methods.get(method, (None, None)) if (not request_class): raise apiproxy_errors.CallNotFoundError() request_data = request_class() re...
'Renders an information page.'
def InfoPage(self):
return '\n<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"\n "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">\n<html><head>\n<title>App Engine API endpoint.</title>\n</head><body>\n<h1>App Engine API endpoint.</h1>\n<p>This is an endpoint for the ...
'Initializes a class that might have property definitions. This method is called when a class is created with the PropertiedClass meta-class. Loads all properties for this model and its base classes in to a dictionary for easy reflection via the \'properties\' method. Configures each property defined in the new class. ...
def __init__(cls, name, bases, dct, map_kind=True):
super(PropertiedClass, cls).__init__(name, bases, dct) _initialize_properties(cls, name, bases, dct) if map_kind: _kind_map[cls.kind()] = cls
'Initializes this Property with the given options. Args: verbose_name: User friendly name of property. name: Storage name for property. By default, uses attribute name as it is assigned in the Model sub-class. default: Default value for property if none is assigned. required: Whether property is required. validator: U...
def __init__(self, verbose_name=None, name=None, default=None, required=False, validator=None, choices=None, indexed=True):
self.verbose_name = verbose_name self.name = name self.default = default self.required = required self.validator = validator self.choices = choices self.indexed = indexed self.creation_counter = Property.creation_counter Property.creation_counter += 1
'Configure property, connecting it to its model. Configure the property so that it knows its property name and what class it belongs to. Args: model_class: Model class which Property will belong to. property_name: Name of property within Model instance to store property values in. By default this will be the property ...
def __property_config__(self, model_class, property_name):
self.model_class = model_class if (self.name is None): self.name = property_name
'Returns the value for this property on the given model instance. See http://docs.python.org/ref/descriptors.html for a description of the arguments to this class and what they mean.'
def __get__(self, model_instance, model_class):
if (model_instance is None): return self try: return getattr(model_instance, self._attr_name()) except AttributeError: return None
'Sets the value for this property on the given model instance. See http://docs.python.org/ref/descriptors.html for a description of the arguments to this class and what they mean.'
def __set__(self, model_instance, value):
value = self.validate(value) setattr(model_instance, self._attr_name(), value)
'Default value for unassigned values. Returns: Default value as provided by __init__(default).'
def default_value(self):
return self.default
'Assert that provided value is compatible with this property. Args: value: Value to validate against this Property. Returns: A valid value, either the input unchanged or adapted to the required type. Raises: BadValueError if the value is not appropriate for this property in any way.'
def validate(self, value):
if self.empty(value): if self.required: raise BadValueError(('Property %s is required' % self.name)) elif self.choices: if (value not in self.choices): raise BadValueError(('Property %s is %r; must be one of %r' % (self.name, value, self.c...
'Determine if value is empty in the context of this property. For most kinds, this is equivalent to "not value", but for kinds like bool, the test is more subtle, so subclasses can override this method if necessary. Args: value: Value to validate against this Property. Returns: True if this value is considered empty in...
def empty(self, value):
return (not value)
'Datastore representation of this property. Looks for this property in the given model instance, and returns the proper datastore representation of the value that can be stored in a datastore entity. Most critically, it will fetch the datastore key value for reference properties. Some properies (e.g. DateTimeProperty,...
def get_value_for_datastore(self, model_instance):
return self.__get__(model_instance, model_instance.__class__)
'Determine new value for auto-updated property. Some properies (e.g. DateTimeProperty, UserProperty) optionally update their value on every put(). This call must return the new desired value for such properties. For all other properties, this call must return AUTO_UPDATE_UNCHANGED. Args: model_instance: Instance to get...
def get_updated_value_for_datastore(self, model_instance):
return AUTO_UPDATE_UNCHANGED
'Native representation of this property. Given a value retrieved from a datastore entity, return a value, possibly converted, to be stored on the model instance. Usually this returns the value unchanged, but a property class may override this when it uses a different datatype on the model instance than on the entity. ...
def make_value_from_datastore(self, value):
return value
'Sets kwds[parameter] to value. If kwds[parameter] exists and is not value, raises ConfigurationError. Args: kwds: The parameter dict, which maps parameter names (strings) to values. parameter: The name of the parameter to set. value: The value to set it to.'
def _require_parameter(self, kwds, parameter, value):
if ((parameter in kwds) and (kwds[parameter] != value)): raise ConfigurationError(('%s must be %s.' % (parameter, value))) kwds[parameter] = value
'Attribute name we use for this property in model instances. DO NOT USE THIS METHOD.'
def _attr_name(self):
return ('_' + self.name)
'Deprecated backwards-compatible accessor method for self.data_type.'
def datastore_type(self):
return self.data_type
'Allow subclasses to call __new__() with arguments. Do NOT list \'cls\' as the first argument, or in the case when the \'unused_kwds\' dictionary contains the key \'cls\', the function will complain about multiple argument values for \'cls\'. Raises: TypeError if there are no positional arguments.'
def __new__(*args, **unused_kwds):
if args: cls = args[0] else: raise TypeError('object.__new__(): not enough arguments') return super(Model, cls).__new__(cls)
'Creates a new instance of this model. To create a new entity, you instantiate a model and then call put(), which saves the entity to the datastore: person = Person() person.name = \'Bret\' person.put() You can initialize properties in the model in the constructor with keyword arguments: person = Person(name=\'Bret\') ...
def __init__(self, parent=None, key_name=None, _app=None, _from_entity=False, **kwds):
namespace = None if isinstance(_app, tuple): if (len(_app) != 2): raise BadArgumentError('_app must have 2 values if type is tuple.') (_app, namespace) = _app key = kwds.get('key', None) if (key is not None): if isinstance(key, (tuple, list)): ...
'Unique key for this entity. This property is only available if this entity is already stored in the datastore or if it has a full key, so it is available if this entity was fetched returned from a query, or after put() is called the first time for new entities, or if a complete key was given when constructed. Returns:...
def key(self):
if self.is_saved(): return self._entity.key() elif self._key: return self._key elif self._key_name: parent = (self._parent_key or (self._parent and self._parent.key())) self._key = Key.from_path(self.kind(), self._key_name, parent=parent, _app=self._app, namespace=self.__name...
'Copies information from this model to provided entity. Args: entity: Entity to save information on.'
def _to_entity(self, entity):
for prop in self.properties().values(): self.__set_property(entity, prop.name, prop.get_value_for_datastore(self)) set_unindexed_properties = getattr(entity, 'set_unindexed_properties', None) if set_unindexed_properties: set_unindexed_properties(self._unindexed_properties)
'Populates self._entity, saving its state to the datastore. After this method is called, calling is_saved() will return True. Returns: Populated self._entity'
def _populate_internal_entity(self, _entity_class=datastore.Entity):
self._entity = self._populate_entity(_entity_class=_entity_class) for prop in self.properties().values(): new_value = prop.get_updated_value_for_datastore(self) if (new_value is not AUTO_UPDATE_UNCHANGED): self.__set_property(self._entity, prop.name, new_value) for attr in ('_key...
'Writes this model instance to the datastore. If this instance is new, we add an entity to the datastore. Otherwise, we update this instance, and the key will remain the same. Args: config: datastore_rpc.Configuration to use for this request. Returns: The key of the instance (either the existing key or a new key). Rais...
def put(self, **kwargs):
self._populate_internal_entity() return datastore.Put(self._entity, **kwargs)
'Internal helper -- Populate self._entity or create a new one if that one does not exist. Does not change any state of the instance other than the internal state of the entity. This method is separate from _populate_internal_entity so that it is possible to call to_xml without changing the state of an unsaved entity t...
def _populate_entity(self, _entity_class=datastore.Entity):
if self.is_saved(): entity = self._entity else: kwds = {'_app': self._app, 'namespace': self.__namespace, 'unindexed_properties': self._unindexed_properties} if (self._key is not None): if self._key.id(): kwds['id'] = self._key.id() else: ...