desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Returns a dict containing the WSGI environ for the request.'
def get_request_environ(self, request_id):
return os.environ
'Returns the name of the module serving this request. Args: request_id: The string id of the request making the API call. Returns: A str containing the module name.'
def get_module(self, request_id):
return 'default'
'Returns the version of the module serving this request. Args: request_id: The string id of the request making the API call. Returns: A str containing the version.'
def get_version(self, request_id):
return '1'
'Returns the instance serving this request. Args: request_id: The string id of the request making the API call. Returns: An opaque representation of the instance serving this request. It should only be passed to dispatcher methods expecting an instance.'
def get_instance(self, request_id):
return object()
'Returns the Dispatcher. Returns: The Dispatcher instance.'
def get_dispatcher(self):
return _local_dispatcher
'Construct a datastore index instance. Args: index_id: Required long; Uniquely identifies the index kind: Required string; Specifies the kind of the entities to index has_ancestor: Required boolean; indicates if the index supports a query that filters entities by the entity group parent properties: Required list of (st...
def __init__(self, index_id, kind, has_ancestor, properties):
argument_error = datastore_errors.BadArgumentError datastore_types.ValidateInteger(index_id, 'index_id', argument_error, zero_ok=True) datastore_types.ValidateString(kind, 'kind', argument_error, empty_ok=True) if (not isinstance(properties, (list, tuple))): raise argument_error('properties m...
'Returns the index id, a long.'
def _Id(self):
return self.__id
'Returns the index kind, a string. Empty string (\'\') if none.'
def _Kind(self):
return self.__kind
'Indicates if this is an ancestor index, a boolean.'
def _HasAncestor(self):
return self.__has_ancestor
'Returns the index properties. a tuple of (index name as a string, [ASCENDING|DESCENDING]) tuples.'
def _Properties(self):
return self.__properties
'Constructor. Takes the kind and transaction root, which cannot be changed after the entity is constructed, and an optional parent. Raises BadArgumentError or BadKeyError if kind is invalid or parent is not an existing Entity or Key in the datastore. Args: # this entity\'s kind kind: string # if provided, this entity\'...
def __init__(self, kind, parent=None, _app=None, name=None, id=None, unindexed_properties=[], namespace=None, **kwds):
ref = entity_pb.Reference() _app = datastore_types.ResolveAppId(_app) ref.set_app(_app) _namespace = kwds.pop('_namespace', None) if kwds: raise datastore_errors.BadArgumentError(('Excess keyword arguments ' + repr(kwds))) if (namespace is None): namespace = _namespace ...
'Returns the name of the application that created this entity, a string or None if not set.'
def app(self):
return self.__key.app()
'Returns the namespace of this entity, a string or None.'
def namespace(self):
return self.__key.namespace()
'Returns this entity\'s kind, a string.'
def kind(self):
return self.__key.kind()
'Returns if this entity has been saved to the datastore.'
def is_saved(self):
last_path = self.__key._Key__reference.path().element_list()[(-1)] return ((last_path.has_name() ^ last_path.has_id()) and self.__key.has_id_or_name())
'Returns if this entity is a projection from full entity. Projected entities: - may not contain all properties from the original entity; - only contain single values for lists; - may not contain values with the same type as the original entity.'
def is_projection(self):
return self.__projection
'Returns this entity\'s primary key, a Key instance.'
def key(self):
return self.__key
'Returns this entity\'s parent, as a Key. If this entity has no parent, returns None.'
def parent(self):
return self.key().parent()
'Returns this entity\'s entity group as a Key. Note that the returned Key will be incomplete if this is a a root entity and its key is incomplete.'
def entity_group(self):
return self.key().entity_group()
'Returns this entity\'s unindexed properties, as a frozenset of strings.'
def unindexed_properties(self):
return getattr(self, '_Entity__unindexed_properties', [])
'Implements the [] operator. Used to set property value(s). If the property name is the empty string or not a string, raises BadPropertyError. If the value is not a supported type, raises BadValueError.'
def __setitem__(self, name, value):
datastore_types.ValidateProperty(name, value) dict.__setitem__(self, name, value)
'If the property exists, returns its value. Otherwise sets it to value. If the property name is the empty string or not a string, raises BadPropertyError. If the value is not a supported type, raises BadValueError.'
def setdefault(self, name, value):
datastore_types.ValidateProperty(name, value) return dict.setdefault(self, name, value)
'Updates this entity\'s properties from the values in other. If any property name is the empty string or not a string, raises BadPropertyError. If any value is not a supported type, raises BadValueError.'
def update(self, other):
for (name, value) in other.items(): self.__setitem__(name, value)
'The copy method is not supported.'
def copy(self):
raise NotImplementedError('Entity does not support the copy() method.')
'Returns an XML representation of this entity. Atom and gd:namespace properties are converted to XML according to their respective schemas. For more information, see: http://www.atomenabled.org/developers/syndication/ http://code.google.com/apis/gdata/common-elements.html This is *not* optimized. It shouldn\'t be used ...
def ToXml(self):
xml = (u'<entity kind=%s' % saxutils.quoteattr(self.kind())) if self.__key.has_id_or_name(): xml += (' key=%s' % saxutils.quoteattr(str(self.__key))) xml += '>' if self.__key.has_id_or_name(): xml += ('\n <key>%s</key>' % self.__key.ToTagUri()) properties = self.keys() ...
'Returns a list of the XML representations of each of the given properties. Ignores properties that don\'t exist in this entity. Arg: properties: string or list of strings Returns: list of strings'
def _PropertiesToXml(self, properties):
xml_properties = [] for propname in properties: if (not self.has_key(propname)): continue propname_xml = saxutils.quoteattr(propname) values = self[propname] if (not isinstance(values, list)): values = [values] proptype = datastore_types.PropertyTy...
'Returns a list of the XML-escaped string values for the given property. Raises an AssertionError if the property doesn\'t exist. Arg: property: string Returns: list of strings'
def _XmlEscapeValues(self, property):
assert self.has_key(property) xml = [] values = self[property] if (not isinstance(values, list)): values = [values] for val in values: if hasattr(val, 'ToXml'): xml.append(val.ToXml()) elif (val is None): xml.append('') else: xml.ap...
'Converts this Entity to its protocol buffer representation. Returns: entity_pb.Entity'
def ToPb(self):
return self._ToPb(False)
'Converts this Entity to its protocol buffer representation. Not intended to be used by application developers. Returns: entity_pb.Entity'
def _ToPb(self, mark_key_as_saved=True):
pb = entity_pb.EntityProto() pb.mutable_key().CopyFrom(self.key()._ToPb()) last_path = pb.key().path().element_list()[(-1)] if (mark_key_as_saved and last_path.has_name() and last_path.has_id()): last_path.clear_id() group = pb.mutable_entity_group() if self.__key.has_id_or_name(): ...
'Static factory method. Returns the Entity representation of the given protocol buffer (datastore_pb.Entity). Args: pb: datastore_pb.Entity or str encoding of a datastore_pb.Entity validate_reserved_properties: deprecated default_kind: str, the kind to use if the pb has no key. Returns: Entity: the Entity representatio...
@staticmethod def FromPb(pb, validate_reserved_properties=True, default_kind='<not specified>'):
if isinstance(pb, str): real_pb = entity_pb.EntityProto() real_pb.ParsePartialFromString(pb) pb = real_pb return Entity._FromPb(pb, require_valid_key=False, default_kind=default_kind)
'Static factory method. Returns the Entity representation of the given protocol buffer (datastore_pb.Entity). Not intended to be used by application developers. The Entity PB\'s key must be complete. If it isn\'t, an AssertionError is raised. Args: # a protocol buffer Entity pb: datastore_pb.Entity default_kind: str, t...
@staticmethod def _FromPb(pb, require_valid_key=True, default_kind='<not specified>'):
if (not pb.key().path().element_size()): pb.mutable_key().CopyFrom(Key.from_path(default_kind, 0)._ToPb()) last_path = pb.key().path().element_list()[(-1)] if require_valid_key: assert (last_path.has_id() ^ last_path.has_name()) if last_path.has_id(): assert (last_path.id...
'Constructor. Raises BadArgumentError if kind is not a string. Raises BadValueError or BadFilterError if filters is not a dictionary of valid filters. Args: namespace: string, the namespace to query. kind: string, the kind of entities to query, or None. filters: dict, initial set of filters. keys_only: boolean, if keys...
def __init__(self, kind=None, filters={}, _app=None, keys_only=False, compile=True, cursor=None, namespace=None, end_cursor=None, projection=None, distinct=None, _namespace=None):
if (namespace is None): namespace = _namespace elif (_namespace is not None): raise datastore_errors.BadArgumentError('Must not set both _namespace and namespace parameters.') if (kind is not None): datastore_types.ValidateString(kind, 'kind', datastore_errors.Ba...
'Specify how the query results should be sorted. Result entities will be sorted by the first property argument, then by the second, and so on. For example, this: > query = Query(\'Person\') > query.Order(\'bday\', (\'age\', Query.DESCENDING)) sorts everyone in order of their birthday, starting with January 1. People wi...
def Order(self, *orderings):
orderings = list(orderings) for (order, i) in zip(orderings, range(len(orderings))): if (not (isinstance(order, basestring) or (isinstance(order, tuple) and (len(order) in [2, 3])))): raise datastore_errors.BadArgumentError(('Order() expects strings or 2- or 3-tuples; re...
'Sets a hint for how this query should run. The query hint gives us information about how best to execute your query. Currently, we can only do one index scan, so the query hint should be used to indicates which index we should scan against. Use FILTER_FIRST if your first filter will only match a few results. In this c...
def Hint(self, hint):
if (hint is not self.__query_options.hint): self.__query_options = datastore_query.QueryOptions(hint=hint, config=self.__query_options) return self
'Sets an ancestor for this query. This restricts the query to only return result entities that are descended from a given entity. In other words, all of the results will have the ancestor as their parent, or parent\'s parent, or etc. Raises BadArgumentError or BadKeyError if parent is not an existing Entity or Key in t...
def Ancestor(self, ancestor):
self.__ancestor_pb = _GetCompleteKeyOrError(ancestor)._ToPb() return self
'Returns True if this query is keys only, false otherwise.'
def IsKeysOnly(self):
return self.__query_options.keys_only
'Returns a datastore_query.QueryOptions for the current instance.'
def GetQueryOptions(self):
return self.__query_options
'Returns a datastore_query.Query for the current instance.'
def GetQuery(self):
return datastore_query.Query(app=self.__app, namespace=self.__namespace, kind=self.__kind, ancestor=self.__ancestor_pb, filter_predicate=self.GetFilterPredicate(), order=self.GetOrder(), group_by=self.__group_by)
'Gets a datastore_query.Order for the current instance. Returns: datastore_query.Order or None if there are no sort orders set on the current Query.'
def GetOrder(self):
orders = [datastore_query.PropertyOrder(property, direction) for (property, direction) in self.__orderings] if orders: return datastore_query.CompositeOrder(orders) return None
'Returns a datastore_query.FilterPredicate for the current instance. Returns: datastore_query.FilterPredicate or None if no filters are set on the current Query.'
def GetFilterPredicate(self):
ordered_filters = [(i, f) for (f, i) in self.__filter_order.iteritems()] ordered_filters.sort() property_filters = [] for (_, filter_str) in ordered_filters: if (filter_str not in self): continue values = self[filter_str] match = self._CheckFilter(filter_str, values) ...
'Returns True if the current instance is distinct. Returns: A boolean indicating if the distinct flag is set.'
def GetDistinct(self):
return self.__distinct
'Get the index list from the last run of this query. Returns: A list of indexes used by the last run of this query. Raises: AssertionError: The query has not yet been run.'
def GetIndexList(self):
index_list_function = self.__index_list_source if index_list_function: return index_list_function() raise AssertionError('No index list available because this query has not been executed')
'Get the cursor from the last run of this query. The source of this cursor varies depending on what the last call was: - Run: A cursor that points immediately after the last result pulled off the returned iterator. - Get: A cursor that points immediately after the last result in the returned list. - Count: A cursor tha...
def GetCursor(self):
cursor_function = self.__cursor_source if cursor_function: cursor = cursor_function() if cursor: return cursor raise AssertionError('No cursor available, either this query has not been executed or there is no compilation available f...
'Runs this query and returns a datastore_query.Batcher. This is not intended to be used by application developers. Use Get() instead! Args: config: Optional Configuration to use for this request. Returns: # an iterator that provides access to the query results Iterator'
def GetBatcher(self, config=None):
query_options = self.GetQueryOptions().merge(config) if (self.__distinct and (query_options.projection != self.__group_by)): raise datastore_errors.BadArgumentError('cannot override projection when distinct is set') return self.GetQuery().run(_GetConnection(), query_options)
'Runs this query. If a filter string is invalid, raises BadFilterError. If a filter value is invalid, raises BadValueError. If an IN filter is provided, and a sort order on another property is provided, raises BadQueryError. If you know in advance how many results you want, use limit=#. It\'s more efficient. Args: kwar...
def Run(self, **kwargs):
config = _GetConfigFromKwargs(kwargs, convert_rpc=True, config_class=datastore_query.QueryOptions) itr = Iterator(self.GetBatcher(config=config)) self.__index_list_source = itr.GetIndexList self.__cursor_source = itr.cursor self.__compiled_query_source = itr._compiled_query return itr
'Deprecated, use list(Run(...)) instead. Args: limit: int or long representing the maximum number of entities to return. offset: int or long representing the number of entities to skip kwargs: Any keyword arguments accepted by datastore_query.QueryOptions(). Returns: # a list of entities [Entity, ...]'
def Get(self, limit, offset=0, **kwargs):
if (limit is None): kwargs.setdefault('batch_size', _MAX_INT_32) return list(self.Run(limit=limit, offset=offset, **kwargs))
'Returns the number of entities that this query matches. Args: limit, a number or None. If there are more results than this, stop short and just return this number. Providing this argument makes the count operation more efficient. config: Optional Configuration to use for this request. Returns: The number of results.'
def Count(self, limit=1000, **kwargs):
original_offset = kwargs.pop('offset', 0) if (limit is None): offset = _MAX_INT_32 else: offset = min((limit + original_offset), _MAX_INT_32) kwargs['limit'] = 0 kwargs['offset'] = offset config = _GetConfigFromKwargs(kwargs, convert_rpc=True, config_class=datastore_query.QueryOp...
'Implements the [] operator. Used to set filters. If the filter string is empty or not a string, raises BadFilterError. If the value is not a supported type, raises BadValueError.'
def __setitem__(self, filter, value):
if isinstance(value, tuple): value = list(value) datastore_types.ValidateProperty(' ', value) match = self._CheckFilter(filter, value) property = match.group(1) operator = match.group(3) dict.__setitem__(self, filter, value) if ((operator in self.INEQUALITY_OPERATORS) and (propert...
'If the filter exists, returns its value. Otherwise sets it to value. If the property name is the empty string or not a string, raises BadPropertyError. If the value is not a supported type, raises BadValueError.'
def setdefault(self, filter, value):
datastore_types.ValidateProperty(' ', value) self._CheckFilter(filter, value) return dict.setdefault(self, filter, value)
'Implements the del [] operator. Used to remove filters.'
def __delitem__(self, filter):
dict.__delitem__(self, filter) del self.__filter_order[filter] match = Query.FILTER_REGEX.match(filter) property = match.group(1) operator = match.group(3) if (operator in self.INEQUALITY_OPERATORS): assert (self.__inequality_count >= 1) assert (property == self.__inequality_prop...
'Updates this query\'s filters from the ones in other. If any filter string is invalid, raises BadFilterError. If any value is not a supported type, raises BadValueError.'
def update(self, other):
for (filter, value) in other.items(): self.__setitem__(filter, value)
'The copy method is not supported.'
def copy(self):
raise NotImplementedError('Query does not support the copy() method.')
'Type check a filter string and list of values. Raises BadFilterError if the filter string is empty, not a string, or invalid. Raises BadValueError if the value type is not supported. Args: filter: String containing the filter text. values: List of associated filter values. Returns: re.MatchObject (never None) that mat...
def _CheckFilter(self, filter, values):
try: match = Query.FILTER_REGEX.match(filter) if (not match): raise datastore_errors.BadFilterError(('Could not parse filter string: %s' % str(filter))) except TypeError: raise datastore_errors.BadFilterError(('Could not parse filter string: %s' ...
'Deprecated, use Run() instead.'
def _Run(self, limit=None, offset=None, prefetch_count=None, next_count=None, **kwargs):
return self.Run(limit=limit, offset=offset, prefetch_size=prefetch_count, batch_size=next_count, **kwargs)
'Returns the internal-only pb representation of the last query run. Do not use. Raises: AssertionError: Query not compiled or not yet executed.'
def _GetCompiledQuery(self):
compiled_query_function = self.__compiled_query_source if compiled_query_function: compiled_query = compiled_query_function() if compiled_query: return compiled_query raise AssertionError('No compiled query available, either this query has not been e...
'Deprecated, use list(Run(...)) instead. Args: limit: int or long representing the maximum number of entities to return. offset: int or long representing the number of entities to skip kwargs: Any keyword arguments accepted by datastore_query.QueryOptions(). Returns: A list of entities with at most "limit" entries (les...
def Get(self, limit, offset=0, **kwargs):
if (limit is None): kwargs.setdefault('batch_size', _MAX_INT_32) return list(self.Run(limit=limit, offset=offset, **kwargs))
'Ctor. Args: entity_iterator: an iterator of entities which will be wrapped. orderings: an iterable of (identifier, order) pairs. order should be either Query.ASCENDING or Query.DESCENDING.'
def __init__(self, entity_iterator, orderings):
self.__entity_iterator = entity_iterator self.__entity = None self.__min_max_value_cache = {} try: self.__entity = entity_iterator.next() except StopIteration: pass else: self.__orderings = orderings
'Gets the wrapped entity.'
def GetEntity(self):
return self.__entity
'Wrap and return the next entity. The entity is retrieved from the iterator given at construction time.'
def GetNext(self):
return MultiQuery.SortOrderEntity(self.__entity_iterator, self.__orderings)
'Compare two entities and return their relative order. Compares self to that based on the current sort orderings and the key orders between them. Returns negative, 0, or positive depending on whether self is less, equal to, or greater than that. This comparison returns as if all values were to be placed in ascending or...
def CmpProperties(self, that):
if (not self.__entity): return cmp(self.__entity, that.__entity) for (identifier, order) in self.__orderings: value1 = self.__GetValueForId(self, identifier, order) value2 = self.__GetValueForId(that, identifier, order) result = cmp(value1, value2) if (order == Query.DESC...
'Compare self to that w.r.t. values defined in the sort order. Compare an entity with another, using sort-order first, then the key order to break ties. This can be used in a heap to have faster min-value lookup. Args: that: other entity to compare to Returns: negative: if self is less than that in sort order zero: if ...
def __cmp__(self, that):
property_compare = self.CmpProperties(that) if property_compare: return property_compare else: return cmp(self.__entity.key(), that.__entity.key())
'This function extracts the range of results to consider. Since MultiQuery dedupes in memory, we must apply the offset and limit in memory. The results that should be considered are results[lower_bound:upper_bound]. We also pass the offset=0 and limit=upper_bound to the base queries to optimize performance. Args: confi...
def _ExtractBounds(self, config):
if (config is None): return (0, None, None) lower_bound = (config.offset or 0) upper_bound = config.limit if lower_bound: if (upper_bound is not None): upper_bound = min((lower_bound + upper_bound), _MAX_INT_32) config = datastore_query.QueryOptions(offset=0, limit=up...
'Returns a tuple of (original projection, projeciton override). If projection is None, there is no projection. If override is None, projection is sufficent for this query.'
def __GetProjectionOverride(self, config):
projection = datastore_query.QueryOptions.projection(config) if (projection is None): projection = self.__projection else: projection = projection if (not projection): return (None, None) override = set() for (prop, _) in self.__orderings: if (prop not in projecti...
'Return an iterable output with all results in order. Merge sort the results. First create a list of iterators, then walk though them and yield results in order. Args: kwargs: Any keyword arguments accepted by datastore_query.QueryOptions(). Returns: An iterator for the result set.'
def Run(self, **kwargs):
config = _GetConfigFromKwargs(kwargs, convert_rpc=True, config_class=datastore_query.QueryOptions) if (config and config.keys_only): raise datastore_errors.BadRequestError('keys only queries are not supported by multi-query.') (lower_bound, upper_bound, config) = self._ExtractBo...
'Return the number of matched entities for this query. Will return the de-duplicated count of results. Will call the more efficient Get() function if a limit is given. Args: limit: maximum number of entries to count (for any result > limit, return limit). config: Optional Configuration to use for this request. Returns...
def Count(self, limit=1000, **kwargs):
kwargs['limit'] = limit config = _GetConfigFromKwargs(kwargs, convert_rpc=True, config_class=datastore_query.QueryOptions) (projection, override) = self.__GetProjectionOverride(config) if (not projection): config = datastore_query.QueryOptions(keys_only=True, config=config) elif override: ...
'Internal only, do not use.'
def _GetCompiledQuery(self):
raise AssertionError('No compilation available for a MultiQuery (queries using "IN" or "!=" operators)')
'Add a new filter by setting it on all subqueries. If any of the setting operations raise an exception, the ones that succeeded are undone and the exception is propagated upward. Args: query_filter: a string of the form "property operand". value: the value that the given property is compared against.'
def __setitem__(self, query_filter, value):
saved_items = [] for (index, query) in enumerate(self.__bound_queries): saved_items.append(query.get(query_filter, None)) try: query[query_filter] = value except: for (q, old_value) in itertools.izip(self.__bound_queries[:index], saved_items): if (...
'Delete a filter by deleting it from all subqueries. If a KeyError is raised during the attempt, it is ignored, unless every subquery raised a KeyError. If any other exception is raised, any deletes will be rolled back. Args: query_filter: the filter to delete. Raises: KeyError: No subquery had an entry containing quer...
def __delitem__(self, query_filter):
subquery_count = len(self.__bound_queries) keyerror_count = 0 saved_items = [] for (index, query) in enumerate(self.__bound_queries): try: saved_items.append(query.get(query_filter, None)) del query[query_filter] except KeyError: keyerror_count += 1 ...
'Returns the list of indexes used to perform the query.'
def GetIndexList(self):
tuple_index_list = super(Iterator, self).index_list() return [index for (index, state) in tuple_index_list]
'Constructor. Args: email: An optional string of the user\'s email address. It defaults to the current user\'s email address. federated_identity: federated identity of user. It defaults to the current user\'s federated identity. federated_provider: federated provider url of user. Raises: UserNotFoundError: Raised if th...
def __init__(self, email=None, _auth_domain=None, _user_id=None, federated_identity=None, federated_provider=None, _strict_mode=True):
if (_auth_domain is None): _auth_domain = os.environ.get('AUTH_DOMAIN') assert _auth_domain if ((email is None) and (federated_identity is None)): email = os.environ.get('USER_EMAIL', email) _user_id = os.environ.get('USER_ID', _user_id) federated_identity = os.environ.get('F...
'Return this user\'s nickname. The nickname will be a unique, human readable identifier for this user with respect to this application. It will be an email address for some users, part of the email address for some users, and the federated identity for federated users who have not asserted an email address.'
def nickname(self):
if (self.__email and self.__auth_domain and self.__email.endswith(('@' + self.__auth_domain))): suffix_len = (len(self.__auth_domain) + 1) return self.__email[:(- suffix_len)] elif self.__federated_identity: return self.__federated_identity else: return self.__email
'Return this user\'s email address.'
def email(self):
return self.__email
'Return either a permanent unique identifying string or None. If the email address was set explicity, this will return None.'
def user_id(self):
return self.__user_id
'Return this user\'s auth domain. This method is internal and should not be used by client applications.'
def auth_domain(self):
return self.__auth_domain
'Return this user\'s federated identity, None if not a federated user.'
def federated_identity(self):
return self.__federated_identity
'Return this user\'s federated provider, None if not a federated user.'
def federated_provider(self):
return self.__federated_provider
'Remove current thread from the dict of currently running threads.'
def __delete(self):
try: with _active_limbo_lock: del _active[_get_ident()] except KeyError: if ('dummy_threading' not in _sys.modules): raise
'Stop the timer if it hasn\'t finished yet'
def cancel(self):
self.finished.set()
'Add a header to be used by the HTTP interface only e.g. u.addheader(\'Accept\', \'sound/basic\')'
def addheader(self, *args):
self.addheaders.append(args)
'Use URLopener().open(file) instead of open(file, \'r\').'
def open(self, fullurl, data=None):
fullurl = unwrap(toBytes(fullurl)) fullurl = quote(fullurl, safe="%/:=&?~#+!$,;'@()*[]|") if (self.tempcache and (fullurl in self.tempcache)): (filename, headers) = self.tempcache[fullurl] fp = open(filename, 'rb') return addinfourl(fp, headers, fullurl) (urltype, url) = splittyp...
'Overridable interface to open unknown URL type.'
def open_unknown(self, fullurl, data=None):
(type, url) = splittype(fullurl) raise IOError, ('url error', 'unknown url type', type)
'Overridable interface to open unknown URL type.'
def open_unknown_proxy(self, proxy, fullurl, data=None):
(type, url) = splittype(fullurl) raise IOError, ('url error', ('invalid proxy for %s' % type), proxy)
'retrieve(url) returns (filename, headers) for a local object or (tempfilename, headers) for a remote object.'
def retrieve(self, url, filename=None, reporthook=None, data=None):
url = unwrap(toBytes(url)) if (self.tempcache and (url in self.tempcache)): return self.tempcache[url] (type, url1) = splittype(url) if ((filename is None) and ((not type) or (type == 'file'))): try: fp = self.open_local_file(url1) hdrs = fp.info() fp....
'Use HTTP protocol.'
def open_http(self, url, data=None):
import httplib user_passwd = None proxy_passwd = None if isinstance(url, str): (host, selector) = splithost(url) if host: (user_passwd, host) = splituser(host) host = unquote(host) realhost = host else: (host, selector) = url (proxy_pas...
'Handle http errors. Derived class can override this, or provide specific handlers named http_error_DDD where DDD is the 3-digit error code.'
def http_error(self, url, fp, errcode, errmsg, headers, data=None):
name = ('http_error_%d' % errcode) if hasattr(self, name): method = getattr(self, name) if (data is None): result = method(url, fp, errcode, errmsg, headers) else: result = method(url, fp, errcode, errmsg, headers, data) if result: return resul...
'Default error handler: close the connection and raise IOError.'
def http_error_default(self, url, fp, errcode, errmsg, headers):
fp.close() raise IOError, ('http error', errcode, errmsg, headers)
'Use local file or FTP depending on form of URL.'
def open_file(self, url):
if (not isinstance(url, str)): raise IOError, ('file error', 'proxy support for file protocol currently not implemented') if ((url[:2] == '//') and (url[2:3] != '/') and (url[2:12].lower() != 'localhost/')): return self.open_ftp(url) else: return self.open_loc...
'Use local file.'
def open_local_file(self, url):
import mimetypes, mimetools, email.utils try: from cStringIO import StringIO except ImportError: from StringIO import StringIO (host, file) = splithost(url) localname = url2pathname(file) try: stats = os.stat(localname) except OSError as e: raise IOError(e.err...
'Use FTP protocol.'
def open_ftp(self, url):
if (not isinstance(url, str)): raise IOError, ('ftp error', 'proxy support for ftp protocol currently not implemented') import mimetypes, mimetools try: from cStringIO import StringIO except ImportError: from StringIO import StringIO (host, path) = spl...
'Use "data" URL.'
def open_data(self, url, data=None):
if (not isinstance(url, str)): raise IOError, ('data error', 'proxy support for data protocol currently not implemented') import mimetools try: from cStringIO import StringIO except ImportError: from StringIO import StringIO try: [type, data] =...
'Default error handling -- don\'t raise an exception.'
def http_error_default(self, url, fp, errcode, errmsg, headers):
return addinfourl(fp, headers, ('http:' + url), errcode)
'Error 302 -- relocated (temporarily).'
def http_error_302(self, url, fp, errcode, errmsg, headers, data=None):
self.tries += 1 if (self.maxtries and (self.tries >= self.maxtries)): if hasattr(self, 'http_error_500'): meth = self.http_error_500 else: meth = self.http_error_default self.tries = 0 return meth(url, fp, 500, 'Internal Server Error: Redirect ...
'Error 301 -- also relocated (permanently).'
def http_error_301(self, url, fp, errcode, errmsg, headers, data=None):
return self.http_error_302(url, fp, errcode, errmsg, headers, data)
'Error 303 -- also relocated (essentially identical to 302).'
def http_error_303(self, url, fp, errcode, errmsg, headers, data=None):
return self.http_error_302(url, fp, errcode, errmsg, headers, data)
'Error 307 -- relocated, but turn POST into error.'
def http_error_307(self, url, fp, errcode, errmsg, headers, data=None):
if (data is None): return self.http_error_302(url, fp, errcode, errmsg, headers, data) else: return self.http_error_default(url, fp, errcode, errmsg, headers)
'Error 401 -- authentication required. This function supports Basic authentication only.'
def http_error_401(self, url, fp, errcode, errmsg, headers, data=None):
if (not ('www-authenticate' in headers)): URLopener.http_error_default(self, url, fp, errcode, errmsg, headers) stuff = headers['www-authenticate'] import re match = re.match('[ DCTB ]*([^ DCTB ]+)[ DCTB ]+realm="([^"]*)"', stuff) if (not match): URLopener.http_error_defa...
'Error 407 -- proxy authentication required. This function supports Basic authentication only.'
def http_error_407(self, url, fp, errcode, errmsg, headers, data=None):
if (not ('proxy-authenticate' in headers)): URLopener.http_error_default(self, url, fp, errcode, errmsg, headers) stuff = headers['proxy-authenticate'] import re match = re.match('[ DCTB ]*([^ DCTB ]+)[ DCTB ]+realm="([^"]*)"', stuff) if (not match): URLopener.http_error_...
'Override this in a GUI environment!'
def prompt_user_passwd(self, host, realm):
import getpass try: user = raw_input(('Enter username for %s at %s: ' % (realm, host))) passwd = getpass.getpass(('Enter password for %s in %s at %s: ' % (user, realm, host))) return (user, passwd) except KeyboardInterrupt: print ...
'Add header for field key handling repeats.'
def addheader(self, key, value):
prev = self.dict.get(key) if (prev is None): self.dict[key] = value else: combined = ', '.join((prev, value)) self.dict[key] = combined
'Add more field data from a continuation line.'
def addcontinue(self, key, more):
prev = self.dict[key] self.dict[key] = ((prev + '\n ') + more)