desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Call the wrapped function; override this in a subclass to
change how the function is called.'
| def call_func(self, req, *args, **kwargs):
| return self.func(req, *args, **kwargs)
|
'Creates a copy/clone of this object, but with some
parameters rebound'
| def clone(self, func=None, **kw):
| kwargs = {}
if (func is not None):
kwargs['func'] = func
if (self.RequestClass is not self.__class__.RequestClass):
kwargs['RequestClass'] = self.RequestClass
if self.args:
kwargs['args'] = self.args
if self.kwargs:
kwargs['kwargs'] = self.kwargs
kwargs.update(kw)... |
'Creates middleware
Use this like::
@wsgify.middleware
def restrict_ip(app, req, ips):
if req.remote_addr not in ips:
raise webob.exc.HTTPForbidden(\'Bad IP: %s\' % req.remote_addr)
return app
@wsgify
def app(req):
return \'hi\'
wrapped = restrict_ip(app, ips=[\'127.0.0.1\'])
Or if you want to write output-rewriting mi... | @classmethod
def middleware(cls, middle_func=None, app=None, **kw):
| if (middle_func is None):
return _UnboundMiddleware(cls, app, kw)
if (app is None):
return _MiddlewareFactory(cls, middle_func, kw)
return cls(middle_func, middleware_wraps=app, kwargs=kw)
|
'Input stream of the request (wsgi.input).
Setting this property resets the content_length and seekable flag
(unlike setting req.body_file_raw).'
| def _body_file__get(self):
| if (not self.is_body_readable):
return io.BytesIO()
r = self.body_file_raw
clen = self.content_length
if ((not self.is_body_seekable) and (clen is not None)):
env = self.environ
(wrapped, raw) = env.get('webob._body_file', (0, 0))
if (raw is not r):
wrapped = ... |
'Get the body of the request (wsgi.input) as a seekable file-like
object. Middleware and routing applications should use this
attribute over .body_file.
If you access this value, CONTENT_LENGTH will also be updated.'
| @property
def body_file_seekable(self):
| if (not self.is_body_seekable):
self.make_body_seekable()
return self.body_file_raw
|
'Return the content type, but leaving off any parameters (like
charset, but also things like the type in ``application/atom+xml;
type=entry``)
If you set this property, you can include parameters, or if
you don\'t include any parameters in the value then existing
parameters will be preserved.'
| def _content_type__get(self):
| return self._content_type_raw.split(';', 1)[0]
|
'All the request headers as a case-insensitive dictionary-like
object.'
| def _headers__get(self):
| if (self._headers is None):
self._headers = EnvironHeaders(self.environ)
return self._headers
|
'The effective client IP address as a string. If the
``HTTP_X_FORWARDED_FOR`` header exists in the WSGI environ, this
attribute returns the client IP address present in that header
(e.g. if the header value is ``192.168.1.1, 192.168.1.2``, the value
will be ``192.168.1.1``). If no ``HTTP_X_FORWARDED_FOR`` header is
pr... | @property
def client_addr(self):
| e = self.environ
xff = e.get('HTTP_X_FORWARDED_FOR')
if (xff is not None):
addr = xff.split(',')[0].strip()
else:
addr = e.get('REMOTE_ADDR')
return addr
|
'The effective server port number as a string. If the ``HTTP_HOST``
header exists in the WSGI environ, this attribute returns the port
number present in that header. If the ``HTTP_HOST`` header exists but
contains no explicit port number: if the WSGI url scheme is "https" ,
this attribute returns "443", if the WSGI ur... | @property
def host_port(self):
| e = self.environ
host = e.get('HTTP_HOST')
if (host is not None):
if (':' in host):
(host, port) = host.split(':', 1)
else:
url_scheme = e['wsgi.url_scheme']
if (url_scheme == 'https'):
port = '443'
else:
port = ... |
'The URL through the host (no path)'
| @property
def host_url(self):
| e = self.environ
scheme = e.get('wsgi.url_scheme')
url = (scheme + '://')
host = e.get('HTTP_HOST')
if (host is not None):
if (':' in host):
(host, port) = host.split(':', 1)
else:
port = None
else:
host = e.get('SERVER_NAME')
port = e.get(... |
'The URL including SCRIPT_NAME (no PATH_INFO or query string)'
| @property
def application_url(self):
| bscript_name = bytes_(self.script_name, self.url_encoding)
return (self.host_url + url_quote(bscript_name, PATH_SAFE))
|
'The URL including SCRIPT_NAME and PATH_INFO, but not QUERY_STRING'
| @property
def path_url(self):
| bpath_info = bytes_(self.path_info, self.url_encoding)
return (self.application_url + url_quote(bpath_info, PATH_SAFE))
|
'The path of the request, without host or query string'
| @property
def path(self):
| bscript = bytes_(self.script_name, self.url_encoding)
bpath = bytes_(self.path_info, self.url_encoding)
return (url_quote(bscript, PATH_SAFE) + url_quote(bpath, PATH_SAFE))
|
'The path of the request, without host but with query string'
| @property
def path_qs(self):
| path = self.path
qs = self.environ.get('QUERY_STRING')
if qs:
path += ('?' + qs)
return path
|
'The full request URL, including QUERY_STRING'
| @property
def url(self):
| url = self.path_url
qs = self.environ.get('QUERY_STRING')
if qs:
url += ('?' + qs)
return url
|
'Resolve other_url relative to the request URL.
If ``to_application`` is True, then resolve it relative to the
URL with only SCRIPT_NAME'
| def relative_url(self, other_url, to_application=False):
| if to_application:
url = self.application_url
if (not url.endswith('/')):
url += '/'
else:
url = self.path_url
return urlparse.urljoin(url, other_url)
|
'\'Pops\' off the next segment of PATH_INFO, pushing it onto
SCRIPT_NAME, and returning the popped segment. Returns None if
there is nothing left on PATH_INFO.
Does not return ``\'\'`` when there\'s an empty segment (like
``/path//path``); these segments are just ignored.
Optional ``pattern`` argument is a regexp to m... | def path_info_pop(self, pattern=None):
| path = self.path_info
if (not path):
return None
slashes = ''
while path.startswith('/'):
slashes += '/'
path = path[1:]
idx = path.find('/')
if (idx == (-1)):
idx = len(path)
r = path[:idx]
if ((pattern is None) or re.match(pattern, r)):
self.scri... |
'Returns the next segment on PATH_INFO, or None if there is no
next segment. Doesn\'t modify the environment.'
| def path_info_peek(self):
| path = self.path_info
if (not path):
return None
path = path.lstrip('/')
return path.split('/', 1)[0]
|
'Return any *named* variables matched in the URL.
Takes values from ``environ[\'wsgiorg.routing_args\']``.
Systems like ``routes`` set this value.'
| def _urlvars__get(self):
| if ('paste.urlvars' in self.environ):
return self.environ['paste.urlvars']
elif ('wsgiorg.routing_args' in self.environ):
return self.environ['wsgiorg.routing_args'][1]
else:
result = {}
self.environ['wsgiorg.routing_args'] = ((), result)
return result
|
'Return any *positional* variables matched in the URL.
Takes values from ``environ[\'wsgiorg.routing_args\']``.
Systems like ``routes`` set this value.'
| def _urlargs__get(self):
| if ('wsgiorg.routing_args' in self.environ):
return self.environ['wsgiorg.routing_args'][0]
else:
return ()
|
'Is X-Requested-With header present and equal to ``XMLHttpRequest``?
Note: this isn\'t set by every XMLHttpRequest request, it is
only set if you are using a Javascript library that sets it
(or you set the header yourself manually). Currently
Prototype and jQuery are known to set this header.'
| @property
def is_xhr(self):
| return (self.environ.get('HTTP_X_REQUESTED_WITH', '') == 'XMLHttpRequest')
|
'Host name provided in HTTP_HOST, with fall-back to SERVER_NAME'
| def _host__get(self):
| if ('HTTP_HOST' in self.environ):
return self.environ['HTTP_HOST']
else:
return ('%(SERVER_NAME)s:%(SERVER_PORT)s' % self.environ)
|
'Return the content of the request body.'
| def _body__get(self):
| if (not self.is_body_readable):
return ''
self.make_body_seekable()
r = self.body_file.read(self.content_length)
self.body_file_raw.seek(0)
return r
|
'Access the body of the request as JSON'
| def _json_body__get(self):
| return json.loads(self.body.decode(self.charset))
|
'Get/set the text value of the body'
| def _text__get(self):
| if (not self.charset):
raise AttributeError('You cannot access Request.text unless charset is set')
body = self.body
return body.decode(self.charset)
|
'Return a MultiDict containing all the variables from a form
request. Returns an empty dict-like object for non-form requests.
Form requests are typically POST requests, however PUT requests with
an appropriate Content-Type are also supported.'
| @property
def POST(self):
| env = self.environ
if (self.method not in ('POST', 'PUT')):
return NoVars('Not a form request')
if ('webob._parsed_post_vars' in env):
(vars, body_file) = env['webob._parsed_post_vars']
if (body_file is self.body_file_raw):
return vars
content_type = self.con... |
'Return a MultiDict containing all the variables from the
QUERY_STRING.'
| @property
def GET(self):
| env = self.environ
source = env.get('QUERY_STRING', '')
if ('webob._parsed_query_vars' in env):
(vars, qs) = env['webob._parsed_query_vars']
if (qs == source):
return vars
data = []
if source:
data = parse_qsl_text(source)
vars = GetDict(data, env)
env['we... |
'A dictionary-like object containing both the parameters from
the query string and request body.'
| @property
def params(self):
| params = NestedMultiDict(self.GET, self.POST)
return params
|
'Return a dictionary of cookies as found in the request.'
| @property
def cookies(self):
| return RequestCookies(self.environ)
|
'Copy the request and environment object.
This only does a shallow copy, except of wsgi.input'
| def copy(self):
| self.make_body_seekable()
env = self.environ.copy()
new_req = self.__class__(env)
new_req.copy_body()
return new_req
|
'Copies the request and environment object, but turning this request
into a GET along the way. If this was a POST request (or any other
verb) then it becomes GET, and the request body is thrown away.'
| def copy_get(self):
| env = self.environ.copy()
return self.__class__(env, method='GET', content_type=None, body='')
|
'webob.is_body_readable is a flag that tells us
that we can read the input stream even though
CONTENT_LENGTH is missing. This allows FakeCGIBody
to work and can be used by servers to support
chunked encoding in requests.
For background see https://bitbucket.org/ianb/webob/issue/6'
| def _is_body_readable__get(self):
| if http_method_probably_has_body.get(self.method):
return True
elif (self.content_length is not None):
return True
else:
return self.environ.get('webob.is_body_readable', False)
|
'This forces ``environ[\'wsgi.input\']`` to be seekable.
That means that, the content is copied into a BytesIO or temporary
file and flagged as seekable, so that it will not be unnecessarily
copied again.
After calling this method the .body_file is always seeked to the
start of file and .content_length is not None.
The... | def make_body_seekable(self):
| if self.is_body_seekable:
self.body_file_raw.seek(0)
else:
self.copy_body()
|
'Copies the body, in cases where it might be shared with
another request object and that is not desired.
This copies the body in-place, either into a BytesIO object
or a temporary file.'
| def copy_body(self):
| if (not self.is_body_readable):
self.body = ''
elif (self.content_length is None):
self.body = self.body_file_raw.read()
self._copy_body_tempfile()
else:
did_copy = self._copy_body_tempfile()
if (not did_copy):
self.body = self.body_file.read(self.content_... |
'Copy wsgi.input to tempfile if necessary. Returns True if it did.'
| def _copy_body_tempfile(self):
| tempfile_limit = self.request_body_tempfile_limit
todo = self.content_length
assert isinstance(todo, integer_types), todo
if ((not tempfile_limit) or (todo <= tempfile_limit)):
return False
fileobj = self.make_tempfile()
input = self.body_file
while (todo > 0):
data = input.r... |
'Create a tempfile to store big request body.
This API is not stable yet. A \'size\' argument might be added.'
| def make_tempfile(self):
| return tempfile.TemporaryFile()
|
'Remove headers that make the request conditional.
These headers can cause the response to be 304 Not Modified,
which in some cases you may not want to be possible.
This does not remove headers like If-Match, which are used for
conflict detection.'
| def remove_conditional_headers(self, remove_encoding=True, remove_range=True, remove_match=True, remove_modified=True):
| check_keys = []
if remove_range:
check_keys += ['HTTP_IF_RANGE', 'HTTP_RANGE']
if remove_match:
check_keys.append('HTTP_IF_NONE_MATCH')
if remove_modified:
check_keys.append('HTTP_IF_MODIFIED_SINCE')
if remove_encoding:
check_keys.append('HTTP_ACCEPT_ENCODING')
fo... |
'Get/set/modify the Cache-Control header (`HTTP spec section 14.9
<http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9>`_)'
| def _cache_control__get(self):
| env = self.environ
value = env.get('HTTP_CACHE_CONTROL', '')
(cache_header, cache_obj) = env.get('webob._cache_control', (None, None))
if ((cache_obj is not None) and (cache_header == value)):
return cache_obj
cache_obj = CacheControl.parse(value, updates_to=self._update_cache_control, type=... |
'Return HTTP bytes representing this request.
If skip_body is True, exclude the body.
If skip_body is an integer larger than one, skip body
only if its length is bigger than that number.'
| def as_bytes(self, skip_body=False):
| url = self.url
host = self.host_url
assert url.startswith(host)
url = url[len(host):]
parts = [bytes_(('%s %s %s' % (self.method, url, self.http_version)))]
body = None
if (self.method in ('PUT', 'POST')):
if (skip_body > 1):
if (len(self.body) > skip_body):
... |
'Create a request from HTTP bytes data. If the bytes contain
extra data after the request, raise a ValueError.'
| @classmethod
def from_bytes(cls, b):
| f = io.BytesIO(b)
r = cls.from_file(f)
if (f.tell() != len(b)):
raise ValueError('The string contains more data than expected')
return r
|
'Read a request from a file-like object (it must implement
``.read(size)`` and ``.readline()``).
It will read up to the end of the request, not the end of the
file (unless the request is a POST or PUT and has no
Content-Length, in that case, the entire file is read).
This reads the request as represented by ``str(req)`... | @classmethod
def from_file(cls, fp):
| start_line = fp.readline()
is_text = isinstance(start_line, text_type)
if is_text:
crlf = '\r\n'
colon = ':'
else:
crlf = '\r\n'
colon = ':'
try:
header = start_line.rstrip(crlf)
(method, resource, http_version) = header.split(None, 2)
method =... |
'Call the given WSGI application, returning ``(status_string,
headerlist, app_iter)``
Be sure to call ``app_iter.close()`` if it\'s there.
If catch_exc_info is true, then returns ``(status_string,
headerlist, app_iter, exc_info)``, where the fourth item may
be None, but won\'t be if there was an exception. If you don\... | def call_application(self, application, catch_exc_info=False):
| if self.is_body_seekable:
self.body_file_raw.seek(0)
captured = []
output = []
def start_response(status, headers, exc_info=None):
if ((exc_info is not None) and (not catch_exc_info)):
reraise(exc_info)
captured[:] = [status, headers, exc_info]
return output.a... |
'Like ``.call_application(application)``, except returns a
response object with ``.status``, ``.headers``, and ``.body``
attributes.
This will use ``self.ResponseClass`` to figure out the class
of the response object to return.
If ``application`` is not given, this will send the request to
``self.make_default_send_app(... | def send(self, application=None, catch_exc_info=False):
| if (application is None):
application = self.make_default_send_app()
if catch_exc_info:
(status, headers, app_iter, exc_info) = self.call_application(application, catch_exc_info=True)
del exc_info
else:
(status, headers, app_iter) = self.call_application(application, catch_ex... |
'Create a blank request environ (and Request wrapper) with the
given path (path should be urlencoded), and any keys from
environ.
The path will become path_info, with any query string split
off and used.
All necessary keys will be added to the environ, but the
values you pass in will take precedence. If you pass in
ba... | @classmethod
def blank(cls, path, environ=None, base_url=None, headers=None, POST=None, **kw):
| env = environ_from_url(path)
if base_url:
(scheme, netloc, path, query, fragment) = urlparse.urlsplit(base_url)
if (query or fragment):
raise ValueError(('base_url (%r) cannot have a query or fragment' % base_url))
if scheme:
env['wsgi.url_sch... |
'Create working set from list of path entries (default=sys.path)'
| def __init__(self, entries=None):
| self.entries = []
self.entry_keys = {}
self.by_key = {}
self.callbacks = []
if (entries is None):
entries = sys.path
for entry in entries:
self.add_entry(entry)
|
'Add a path item to ``.entries``, finding any distributions on it
``find_distributions(entry, True)`` is used to find distributions
corresponding to the path entry, and they are added. `entry` is
always appended to ``.entries``, even if it is already present.
(This is because ``sys.path`` can contain the same value mo... | def add_entry(self, entry):
| self.entry_keys.setdefault(entry, [])
self.entries.append(entry)
for dist in find_distributions(entry, True):
self.add(dist, entry, False)
|
'True if `dist` is the active distribution for its project'
| def __contains__(self, dist):
| return (self.by_key.get(dist.key) == dist)
|
'Find a distribution matching requirement `req`
If there is an active distribution for the requested project, this
returns it as long as it meets the version requirement specified by
`req`. But, if there is an active distribution for the project and it
does *not* meet the `req` requirement, ``VersionConflict`` is rais... | def find(self, req):
| dist = self.by_key.get(req.key)
if ((dist is not None) and (dist not in req)):
raise VersionConflict(dist, req)
else:
return dist
|
'Yield entry point objects from `group` matching `name`
If `name` is None, yields all entry points in `group` from all
distributions in the working set, otherwise only ones matching
both `group` and `name` are yielded (in distribution order).'
| def iter_entry_points(self, group, name=None):
| for dist in self:
entries = dist.get_entry_map(group)
if (name is None):
for ep in entries.values():
(yield ep)
elif (name in entries):
(yield entries[name])
|
'Locate distribution for `requires` and run `script_name` script'
| def run_script(self, requires, script_name):
| ns = sys._getframe(1).f_globals
name = ns['__name__']
ns.clear()
ns['__name__'] = name
self.require(requires)[0].run_script(script_name, ns)
|
'Yield distributions for non-duplicate projects in the working set
The yield order is the order in which the items\' path entries were
added to the working set.'
| def __iter__(self):
| seen = {}
for item in self.entries:
for key in self.entry_keys[item]:
if (key not in seen):
seen[key] = 1
(yield self.by_key[key])
|
'Add `dist` to working set, associated with `entry`
If `entry` is unspecified, it defaults to the ``.location`` of `dist`.
On exit from this routine, `entry` is added to the end of the working
set\'s ``.entries`` (if it wasn\'t already present).
`dist` is only added to the working set if it\'s for a project that
doesn\... | def add(self, dist, entry=None, insert=True):
| if insert:
dist.insert_on(self.entries, entry)
if (entry is None):
entry = dist.location
keys = self.entry_keys.setdefault(entry, [])
keys2 = self.entry_keys.setdefault(dist.location, [])
if (dist.key in self.by_key):
return
self.by_key[dist.key] = dist
if (dist.key n... |
'List all distributions needed to (recursively) meet `requirements`
`requirements` must be a sequence of ``Requirement`` objects. `env`,
if supplied, should be an ``Environment`` instance. If
not supplied, it defaults to all distributions available within any
entry or distribution in the working set. `installer`, if... | def resolve(self, requirements, env=None, installer=None):
| requirements = list(requirements)[::(-1)]
processed = {}
best = {}
to_activate = []
while requirements:
req = requirements.pop(0)
if (req in processed):
continue
dist = best.get(req.key)
if (dist is None):
dist = self.by_key.get(req.key)
... |
'Find all activatable distributions in `plugin_env`
Example usage::
distributions, errors = working_set.find_plugins(
Environment(plugin_dirlist)
map(working_set.add, distributions) # add plugins+libs to sys.path
print "Couldn\'t load", errors # display errors
The `plugin_env` should be an ``Environment`` insta... | def find_plugins(self, plugin_env, full_env=None, installer=None, fallback=True):
| plugin_projects = list(plugin_env)
plugin_projects.sort()
error_info = {}
distributions = {}
if (full_env is None):
env = Environment(self.entries)
env += plugin_env
else:
env = (full_env + plugin_env)
shadow_set = self.__class__([])
map(shadow_set.add, self)
... |
'Ensure that distributions matching `requirements` are activated
`requirements` must be a string or a (possibly-nested) sequence
thereof, specifying the distributions and versions required. The
return value is a sequence of the distributions that needed to be
activated to fulfill the requirements; all relevant distrib... | def require(self, *requirements):
| needed = self.resolve(parse_requirements(requirements))
for dist in needed:
self.add(dist)
return needed
|
'Invoke `callback` for all distributions (including existing ones)'
| def subscribe(self, callback):
| if (callback in self.callbacks):
return
self.callbacks.append(callback)
for dist in self:
callback(dist)
|
'Snapshot distributions available on a search path
Any distributions found on `search_path` are added to the environment.
`search_path` should be a sequence of ``sys.path`` items. If not
supplied, ``sys.path`` is used.
`platform` is an optional string specifying the name of the platform
that platform-specific distribu... | def __init__(self, search_path=None, platform=get_supported_platform(), python=PY_MAJOR):
| self._distmap = {}
self._cache = {}
self.platform = platform
self.python = python
self.scan(search_path)
|
'Is distribution `dist` acceptable for this environment?
The distribution must match the platform and python version
requirements specified when this environment was created, or False
is returned.'
| def can_add(self, dist):
| return (((self.python is None) or (dist.py_version is None) or (dist.py_version == self.python)) and compatible_platforms(dist.platform, self.platform))
|
'Remove `dist` from the environment'
| def remove(self, dist):
| self._distmap[dist.key].remove(dist)
|
'Scan `search_path` for distributions usable in this environment
Any distributions found are added to the environment.
`search_path` should be a sequence of ``sys.path`` items. If not
supplied, ``sys.path`` is used. Only distributions conforming to
the platform/python version defined at initialization are added.'
| def scan(self, search_path=None):
| if (search_path is None):
search_path = sys.path
for item in search_path:
for dist in find_distributions(item):
self.add(dist)
|
'Return a newest-to-oldest list of distributions for `project_name`'
| def __getitem__(self, project_name):
| try:
return self._cache[project_name]
except KeyError:
project_name = project_name.lower()
if (project_name not in self._distmap):
return []
if (project_name not in self._cache):
dists = self._cache[project_name] = self._distmap[project_name]
_sort_dists(d... |
'Add `dist` if we ``can_add()`` it and it isn\'t already added'
| def add(self, dist):
| if (self.can_add(dist) and dist.has_version()):
dists = self._distmap.setdefault(dist.key, [])
if (dist not in dists):
dists.append(dist)
if (dist.key in self._cache):
_sort_dists(self._cache[dist.key])
|
'Find distribution best matching `req` and usable on `working_set`
This calls the ``find(req)`` method of the `working_set` to see if a
suitable distribution is already active. (This may raise
``VersionConflict`` if an unsuitable version of the project is already
active in the specified `working_set`.) If a suitable ... | def best_match(self, req, working_set, installer=None):
| dist = working_set.find(req)
if (dist is not None):
return dist
for dist in self[req.key]:
if (dist in req):
return dist
return self.obtain(req, installer)
|
'Obtain a distribution matching `requirement` (e.g. via download)
Obtain a distro that matches requirement (e.g. via download). In the
base ``Environment`` class, this routine just returns
``installer(requirement)``, unless `installer` is None, in which case
None is returned instead. This method is a hook that allows... | def obtain(self, requirement, installer=None):
| if (installer is not None):
return installer(requirement)
|
'Yield the unique project names of the available distributions'
| def __iter__(self):
| for key in self._distmap.keys():
if self[key]:
(yield key)
|
'In-place addition of a distribution or environment'
| def __iadd__(self, other):
| if isinstance(other, Distribution):
self.add(other)
elif isinstance(other, Environment):
for project in other:
for dist in other[project]:
self.add(dist)
else:
raise TypeError(("Can't add %r to environment" % (other,)))
return self
|
'Add an environment or distribution to an environment'
| def __add__(self, other):
| new = self.__class__([], platform=None, python=None)
for env in (self, other):
new += env
return new
|
'Does the named resource exist?'
| def resource_exists(self, package_or_requirement, resource_name):
| return get_provider(package_or_requirement).has_resource(resource_name)
|
'Is the named resource an existing directory?'
| def resource_isdir(self, package_or_requirement, resource_name):
| return get_provider(package_or_requirement).resource_isdir(resource_name)
|
'Return a true filesystem path for specified resource'
| def resource_filename(self, package_or_requirement, resource_name):
| return get_provider(package_or_requirement).get_resource_filename(self, resource_name)
|
'Return a readable file-like object for specified resource'
| def resource_stream(self, package_or_requirement, resource_name):
| return get_provider(package_or_requirement).get_resource_stream(self, resource_name)
|
'Return specified resource as a string'
| def resource_string(self, package_or_requirement, resource_name):
| return get_provider(package_or_requirement).get_resource_string(self, resource_name)
|
'List the contents of the named resource directory'
| def resource_listdir(self, package_or_requirement, resource_name):
| return get_provider(package_or_requirement).resource_listdir(resource_name)
|
'Give an error message for problems extracting file(s)'
| def extraction_error(self):
| old_exc = sys.exc_info()[1]
cache_path = (self.extraction_path or get_default_cache())
err = ExtractionError(("Can't extract file(s) to egg cache\n\nThe following error occurred while trying to extract file(s) to the Python egg\ncache:\n\n %s\n\nThe ... |
'Return absolute location in cache for `archive_name` and `names`
The parent directory of the resulting path will be created if it does
not already exist. `archive_name` should be the base filename of the
enclosing egg (which may not be the name of the enclosing zipfile!),
including its ".egg" extension. `names`, if ... | def get_cache_path(self, archive_name, names=()):
| extract_path = (self.extraction_path or get_default_cache())
target_path = os.path.join(extract_path, (archive_name + '-tmp'), *names)
try:
_bypass_ensure_directory(target_path)
except:
self.extraction_error()
self.cached_files[target_path] = 1
return target_path
|
'Perform any platform-specific postprocessing of `tempname`
This is where Mac header rewrites should be done; other platforms don\'t
have anything special they should do.
Resource providers should call this method ONLY after successfully
extracting a compressed resource. They must NOT call it on resources
that are alr... | def postprocess(self, tempname, filename):
| if (os.name == 'posix'):
mode = ((os.stat(tempname).st_mode | 365) & 4095)
os.chmod(tempname, mode)
|
'Set the base path where resources will be extracted to, if needed.
If you do not call this routine before any extractions take place, the
path defaults to the return value of ``get_default_cache()``. (Which
is based on the ``PYTHON_EGG_CACHE`` environment variable, with various
platform-specific fallbacks. See that ... | def set_extraction_path(self, path):
| if self.cached_files:
raise ValueError("Can't change extraction path, files already extracted")
self.extraction_path = path
|
'Create a metadata provider from a zipimporter'
| def __init__(self, importer):
| self.zipinfo = zipimport._zip_directory_cache[importer.archive]
self.zip_pre = (importer.archive + os.sep)
self.loader = importer
if importer.prefix:
self.module_path = os.path.join(importer.archive, importer.prefix)
else:
self.module_path = importer.archive
self._setup_prefix()
|
'Parse a single entry point from string `src`
Entry point syntax follows the form::
name = some.module:some.attr [extra1,extra2]
The entry name and module name are required, but the ``:attrs`` and
``[extras]`` parts are optional'
| def parse(cls, src, dist=None):
| try:
attrs = extras = ()
(name, value) = src.split('=', 1)
if ('[' in value):
(value, extras) = value.split('[', 1)
req = Requirement.parse(('x[' + extras))
if req.specs:
raise ValueError
extras = req.extras
if (':' in v... |
'Parse an entry point group'
| def parse_group(cls, group, lines, dist=None):
| if (not MODULE(group)):
raise ValueError('Invalid group name', group)
this = {}
for line in yield_lines(lines):
ep = cls.parse(line, dist)
if (ep.name in this):
raise ValueError('Duplicate entry point', group, ep.name)
this[ep.name] = ep
return thi... |
'Parse a map of entry point groups'
| def parse_map(cls, data, dist=None):
| if isinstance(data, dict):
data = data.items()
else:
data = split_sections(data)
maps = {}
for (group, lines) in data:
if (group is None):
if (not lines):
continue
raise ValueError('Entry points must be listed in groups')
... |
'List of Requirements needed for this distro if `extras` are used'
| def requires(self, extras=()):
| dm = self._dep_map
deps = []
deps.extend(dm.get(None, ()))
for ext in extras:
try:
deps.extend(dm[safe_extra(ext)])
except KeyError:
raise UnknownExtra(('%s has no such extra feature %r' % (self, ext)))
return deps
|
'Ensure distribution is importable on `path` (default=sys.path)'
| def activate(self, path=None):
| if (path is None):
path = sys.path
self.insert_on(path)
if (path is sys.path):
fixup_namespace_packages(self.location)
map(declare_namespace, self._get_metadata('namespace_packages.txt'))
|
'Return what this distribution\'s standard .egg filename should be'
| def egg_name(self):
| filename = ('%s-%s-py%s' % (to_filename(self.project_name), to_filename(self.version), (self.py_version or PY_MAJOR)))
if self.platform:
filename += ('-' + self.platform)
return filename
|
'Delegate all unrecognized public attributes to .metadata provider'
| def __getattr__(self, attr):
| if attr.startswith('_'):
raise AttributeError, attr
return getattr(self._provider, attr)
|
'Return a ``Requirement`` that matches this distribution exactly'
| def as_requirement(self):
| return Requirement.parse(('%s==%s' % (self.project_name, self.version)))
|
'Return the `name` entry point of `group` or raise ImportError'
| def load_entry_point(self, group, name):
| ep = self.get_entry_info(group, name)
if (ep is None):
raise ImportError(('Entry point %r not found' % ((group, name),)))
return ep.load()
|
'Return the entry point map for `group`, or the full entry map'
| def get_entry_map(self, group=None):
| try:
ep_map = self._ep_map
except AttributeError:
ep_map = self._ep_map = EntryPoint.parse_map(self._get_metadata('entry_points.txt'), self)
if (group is not None):
return ep_map.get(group, {})
return ep_map
|
'Return the EntryPoint object for `group`+`name`, or ``None``'
| def get_entry_info(self, group, name):
| return self.get_entry_map(group).get(name)
|
'Insert self.location in path before its nearest parent directory'
| def insert_on(self, path, loc=None):
| loc = (loc or self.location)
if (not loc):
return
nloc = _normalize_cached(loc)
bdir = os.path.dirname(nloc)
npath = [((p and _normalize_cached(p)) or p) for p in path]
bp = None
for (p, item) in enumerate(npath):
if (item == nloc):
break
elif ((item == bd... |
'Copy this distribution, substituting in any changed keyword args'
| def clone(self, **kw):
| for attr in ('project_name', 'version', 'py_version', 'platform', 'location', 'precedence'):
kw.setdefault(attr, getattr(self, attr, None))
kw.setdefault('metadata', self._provider)
return self.__class__(**kw)
|
'DO NOT CALL THIS UNDOCUMENTED METHOD; use Requirement.parse()!'
| def __init__(self, project_name, specs, extras):
| (self.unsafe_name, project_name) = (project_name, safe_name(project_name))
(self.project_name, self.key) = (project_name, project_name.lower())
index = [(parse_version(v), state_machine[op], op, v) for (op, v) in specs]
index.sort()
self.specs = [(op, ver) for (parsed, trans, op, ver) in index]
... |
'Return a suite of all tests cases contained in the given module
If the module is a package, load tests from all the modules in it.
If the module has an ``additional_tests`` function, call it and add
the return value to the tests.'
| def loadTestsFromModule(self, module):
| tests = []
if (module.__name__ != 'setuptools.tests.doctest'):
tests.append(TestLoader.loadTestsFromModule(self, module))
if hasattr(module, 'additional_tests'):
tests.append(module.additional_tests())
if hasattr(module, '__path__'):
for file in resource_listdir(module.__name__, ... |
'Build modules, packages, and copy data files to build directory'
| def run(self):
| if ((not self.py_modules) and (not self.packages)):
return
if self.py_modules:
self.build_modules()
if self.packages:
self.build_packages()
self.build_package_data()
self.byte_compile(_build_py.get_outputs(self, include_bytecode=0))
|
'Generate list of \'(package,src_dir,build_dir,filenames)\' tuples'
| def _get_data_files(self):
| self.analyze_manifest()
data = []
for package in (self.packages or ()):
src_dir = self.get_package_dir(package)
build_dir = os.path.join(*([self.build_lib] + package.split('.')))
plen = (len(src_dir) + 1)
filenames = [file[plen:] for file in self.find_data_files(package, src_... |
'Return filenames for package\'s data files in \'src_dir\''
| def find_data_files(self, package, src_dir):
| globs = (self.package_data.get('', []) + self.package_data.get(package, []))
files = self.manifest_files.get(package, [])[:]
for pattern in globs:
files.extend(glob(os.path.join(src_dir, convert_path(pattern))))
return self.exclude_data_files(package, src_dir, files)
|
'Copy data files into build directory'
| def build_package_data(self):
| lastdir = None
for (package, src_dir, build_dir, filenames) in self.data_files:
for filename in filenames:
target = os.path.join(build_dir, filename)
self.mkpath(os.path.dirname(target))
self.copy_file(os.path.join(src_dir, filename), target)
|
'Check namespace packages\' __init__ for declare_namespace'
| def check_package(self, package, package_dir):
| try:
return self.packages_checked[package]
except KeyError:
pass
init_py = _build_py.check_package(self, package, package_dir)
self.packages_checked[package] = init_py
if ((not init_py) or (not self.distribution.namespace_packages)):
return init_py
for pkg in self.distrib... |
'Filter filenames for package\'s data files in \'src_dir\''
| def exclude_data_files(self, package, src_dir, files):
| globs = (self.exclude_package_data.get('', []) + self.exclude_package_data.get(package, []))
bad = []
for pattern in globs:
bad.extend(fnmatch.filter(files, os.path.join(src_dir, convert_path(pattern))))
bad = dict.fromkeys(bad)
seen = {}
return [f for f in files if ((f not in bad) and (... |
'Write an executable file to the scripts directory'
| def write_script(self, script_name, contents, mode='t', *ignored):
| log.info('Installing %s script to %s', script_name, self.install_dir)
target = os.path.join(self.install_dir, script_name)
self.outfiles.append(target)
if (not self.dry_run):
ensure_directory(target)
f = open(target, ('w' + mode))
f.write(contents)
f.close()
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.