ll.url – RFC 2396 compliant URLs
ll.url contains an RFC 2396 compliant implementation of URLs and
classes for accessing resource metadata as well as file like classes for
reading and writing resource data.
These three levels of functionality are implemented in three classes:
URLURLobjects are the names of resources and can be used and modified, regardless of the fact whether these resources actually exits.URLobjects never hits the hard drive or the net.ConnectionConnectionobjects contain functionality that accesses and changes file metadata (like last modified date, permission bits, directory structure etc.). A connection object can be created by calling theconnect()method on aURLobject.ResourceResourceobjects are file like objects that work with the actual bytes that make up the file data. This functionality lives in theResourceclass and its subclasses. Creating a resource is done by calling theopen()method on aConnectionor aURL.
Module documentation
- ll.url.httpdate(dt)[source]
Return a string suitable for a “Last-Modified” and “Expires” header.
dtis adatetime.datetimeobject in UTC.
- class ll.url.Context[source]
Bases:
objectWorking with URLs (e.g. calling
URL.open()orURL.connect()) involvesConnectionobjects. To avoid constantly creating new connections you can pass aContextobject to those methods. Connections will be stored in theContextobject and will be reused by those methods.A
Contextobject can also be used as a context manager. This context object will be used for allopen()andconnect()calls inside thewithblock. (Note that after the end of thewithblock all connections will be closed.)- closeall()[source]
Close and drop all connections in this context.
- class ll.url.Cursor[source]
Bases:
objectA
Cursorobject is used by thewalk()method during directory traversal. It contains information about the state of the traversal and can be used to influence which directories are traversed and in which order.Information about the state of the traversal is provided in the following attributes:
rooturlThe URL where traversal has been started (i.e. the object for which the
walk()method has been called)urlThe current URL being traversed.
eventA string that specifies which event is currently handled. Possible values are:
"beforedir","afterdir"and"file". A"beforedir"event is emitted before a directory is entered."afterdir"is emitted after a directory has been entered."file"is emitted when a file is encountered.isdirTrue if
urlrefers to a directory.isfileTur if
urlrefers to a regular file.
The following attributes specify which part of the tree should be traversed:
beforedirShould the generator yield
"beforedir"events?afterdirShould the generator yield
"afterdir"events?fileShould the generator yield
"file"events?enterdirShould the directory be entered?
Note that if any of these attributes is changed by the code consuming the generator, this new value will be used for the next traversal step once the generator is resumed and will be reset to its initial value (specified in the constructor) afterwards.
- __init__(url, beforedir=True, afterdir=False, file=True, enterdir=False)[source]
Create a new
Cursorobject for a tree traversal rooted at the nodenode.The arguments
beforedir,afterdir,fileandenterdirare used as the initial values for the attributes of the same name. (see the class docstring for info about their use).
- restore()[source]
Restore the attributes
beforedir,afterdir,fileandenterdirto their initial value.
- class ll.url.Connection[source]
Bases:
objectA
Connectionobject is used for accessing and modifying the metadata associated with a file. It is created by calling theconnect()method on aURLobject.- lstat(url)[source]
Return the result of a
stat()call on the fileurl. Likestat(), but does not follow symbolic links.
- chmod(url, mode)[source]
Set the access mode of the file
urltomode.
- chown(url, owner=None, group=None)[source]
Change the owner and/or group of the file
url.
- lchown(url, owner=None, group=None)[source]
Change the owner and/or group of the file
url(ignoring symbolic links).
- uid(url)[source]
Return the user id of the owner of the file
url.
- gid(url)[source]
Return the group id the file
urlbelongs to.
- owner(url)[source]
Return the name of the owner of the file
url.
- group(url)[source]
Return the name of the group the file
urlbelongs to.
- mimetype(url)[source]
Return the mimetype of the file
url.
- exists(url)[source]
Test whether the file
urlexists.
- isfile(url)[source]
Test whether the resource
urlis a file.
- isdir(url)[source]
Test whether the resource
urlis a directory.
- islink(url)[source]
Test whether the resource
urlis a link.
- ismount(url)[source]
Test whether the resource
urlis a mount point.
- access(url, mode)[source]
Test for access to the file/resource
url.
- size(url)[source]
Return the size of the file
url.
- imagesize(url)[source]
Return the size of the image
url(if the resource is an image file) as a(width, height)tuple. This requires the PIL.
- cdate(url)[source]
Return the “metadate change” date of the file/resource
urlas adatetime.datetimeobject in UTC.
- adate(url)[source]
Return the last access date of the file/resource
urlas adatetime.datetimeobject in UTC.
- mdate(url)[source]
Return the last modification date of the file/resource
urlas adatetime.datetimeobject in UTC.
- resheaders(url)[source]
Return the MIME headers for the file/resource
url.
- remove(url)[source]
Remove the file
url.
- rmdir(url)[source]
Remove the directory
url.
- rename(url, target)[source]
Renames
urltotarget. This might not work iftargethas a different scheme thanurl(or is on a different server).
- link(url, target)[source]
Create a hard link from
urltotarget. This will not work iftargethas a different scheme thanurl(or is on a different server).
- symlink(url, target)[source]
Create a symbolic link from
urltotarget. This will not work iftargethas a different scheme thanurl(or is on a different server).
- chdir(url)[source]
Change the current directory to
url.
- mkdir(url, mode=511)[source]
Create the directory
url.
- makedirs(url, mode=511)[source]
Create the directory
urland all intermediate ones.
- walk(url, beforedir=True, afterdir=False, file=True, enterdir=True)[source]
Return an iterator for traversing the directory hierarchy rooted at the directory
url.Each item produced by the iterator is a
Cursorobject. It contains information about the state of the traversal and can be used to influence which parts of the directory hierarchy are traversed and in which order.The arguments
beforedir,afterdir,fileandenterdirspecify how the directory hierarchy should be traversed. For more information see theCursorclass.Note that the
Cursorobject is reused bywalk(), so you can’t rely on any attributes remaining the same across calls tonext().The following example shows how to traverse the current directory, print all files except those in certain directories:
from ll import url for cursor in url.here().walk(beforedir=True, afterdir=False, file=True): if cursor.isdir: if cursor.url.path[-2] in (".git", "build", "dist", "__pycache__"): cursor.enterdir = False else: print(cursor.url)
- listdir(url, include=None, exclude=None, ignorecase=False)[source]
Iterates over items in the directory
url. The items produced areURLobjects relative tourl.With the optional
includeargument, this only lists items whose names match the given pattern. Items matching the optional patternexcludewill not be listed.includeandexcludecan be strings (which will be interpreted asfnmatchstyle filename patterns) or lists of strings. Ifignorecaseis true case-insensitive name matching will be performed.
- files(url, include=None, exclude=None, ignorecase=False)[source]
Iterates over files in the directory
url. The items produced areURLobjects relative tourl.With the optional
includeargument, this only lists files whose names match the given pattern. Files matching the optional patternexcludewill not be listed.includeandexcludecan be strings (which will be interpreted asfnmatchstyle filename patterns) or lists of strings. Ifignorecaseis true case-insensitive name matching will be performed.
- dirs(url, include=None, exclude=None, ignorecase=False)[source]
Iterates over directories in the directory
url. The items produced areURLobjects relative tourl.With the optional
includeargument, this only directories items whose names match the given pattern. Directories matching the optional patternexcludewill not be listed.includeandexcludecan be strings (which will be interpreted asfnmatchstyle filename patterns) or lists of strings. Ifignorecaseis true case-insensitive name matching will be performed.
- walkall(url, include=None, exclude=None, enterdir=None, skipdir=None, ignorecase=False)[source]
Recursively iterate over files and subdirectories. The iterator yields
URLobjects naming each child URL of the directoryurland its descendants relative tourl. This performs a depth-first traversal, returning each directory before all its children.With the optional
includeargument, only yield items whose names match the given pattern. Items matching the optional patternexcludewill not be listed. Directories that don’t match the optional patternenterdiror match the patternskipdirwill not be traversed.include,exclude,enterdirandskipdircan be strings (which will be interpreted asfnmatchstyle filename patterns) or lists of strings. Ifignorecaseis true case-insensitive name matching will be performed.
- walkfiles(url, include=None, exclude=None, enterdir=None, skipdir=None, ignorecase=False)[source]
Return a recursive iterator over files in the directory
url.With the optional
includeargument, only yield files whose names match the given pattern. Files matching the optional patternexcludewill not be listed. Directories that don’t match the optional patternenterdiror match the patternskipdirwill not be traversed.include,exclude,enterdirandskipdircan be strings (which will be interpreted asfnmatchstyle filename patterns) or lists of strings. Ifignorecaseis true case-insensitive name matching will be performed.
- walkdirs(url, include=None, exclude=None, enterdir=None, skipdir=None, ignorecase=False)[source]
Return a recursive iterator over subdirectories in the directory
url.With the optional
includeargument, only yield directories whose names match the given pattern. Items matching the optional patternexcludewill not be listed. Directories that don’t match the optional patternenterdiror match the patternskipdirwill not be traversed.include,exclude,enterdirandskipdircan be strings (which will be interpreted asfnmatchstyle filename patterns) or lists of strings. Ifignorecaseis true case-insensitive name matching will be performed.
- open(url, *args, **kwargs)[source]
Open
urlfor reading or writing.open()returns aResourceobject.Which additional parameters are supported depends on the actual resource created. Some common parameters are:
modestrA string indicating how the file is to be opened (just like the mode argument for the builtin
open()(e.g."rb"or"wb").headersdictAdditional headers to use for an HTTP request.
databytesRequest body to use for an HTTP POST request.
pythonstrorNoneName of the Python interpreter to use on the remote side (used by
sshURLs)niceintorNoneNice level for the remote python (used by
sshURLs)checkboolorNoneWhether
sshhost keys should be checked (used bysshURLs where it defaults toTrueandssh-nocheckURLs where it defaults toFalse).
- class ll.url.LocalConnection[source]
Bases:
ll.url.ConnectionA
LocalConnectionobject is used for accessing and modifying the metadata associated with a file in the local filesystem. It is created by calling theconnect()method on aURLobject with no scheme or thefileorrootscheme.
- class ll.url.SshConnection[source]
Bases:
ll.url.ConnectionA
SshConnectionobject is used for accessing and modifying the metadata associated with a file on a remote filesystem. Remote files will be accessed via code executed remotely on the target host viaexecnet.SshConnectionobjects are created by calling theconnect()method on aURLobject with thesshorssh-nocheckscheme.Note
Using the scheme
ssh-nocheckdisables checks of the host key, i.e. it passes-o "StrictHostKeyChecking=no"to the underlyingsshcommand.If you need to use further options (e.g. when your
known_hostsfile isn’t writable), you should configure that in your~/.ssh/configfile, for example:Host foo Hostname foo.example.org StrictHostKeyChecking no UserKnownHostsfile /dev/null
or for Windows:
Host foo Hostname foo.example.org StrictHostKeyChecking no UserKnownHostsfile nul:
- class ll.url.URLConnection[source]
Bases:
ll.url.ConnectionA
URLConnectionobject is used for accessing and modifying the metadata associated any other resource specified by a URL (except those handled by the otherConnectionsubclasses).
- ll.url.home(user='', scheme='file')[source]
Return the home directory of the current user (or the user named
user, ifuseris specified) as anURLobject:>>> url.home() URL('file:/home/walter/') >>> url.home("andreas") URL('file:/home/andreas/')
- ll.url.File(name, scheme='file')[source]
Turn a filename into an
URLobject:>>> url.File("a#b") URL('file:a%23b')
- ll.url.Dir(name, scheme='file')[source]
Turns a directory name into an
URLobject, just likeFile(), but ensures that the path is terminated with a/:>>> url.Dir("a#b") URL('file:a%23b/')
- ll.url.Ssh(user, host, path='~/')[source]
Return a ssh
URLfor the useruseron the hosthostwith the pathpath.path(defaulting to the users home directory) must be a path in URL notation (i.e. use/as directory separator):>>> url.Ssh("root", "www.example.com", "~joe/public_html/index.html") URL('ssh://root@www.example.com/~joe/public_html/index.html')
If the path starts with
~/it is relative to this users home directory, if it starts with~userit’s relative to the home directory of the useruser. In all other cases the path is considered to be absolute.
- ll.url.first(urls)[source]
Return the first URL from
urlsthat exists as a real file or directory.Noneentries inurlswill be skipped.
- ll.url.firstdir(urls)[source]
Return the first URL from
urlsthat exists as a real directory.Noneentries inurlswill be skipped.
- ll.url.firstfile(urls)[source]
Return the first URL from
urlsthat exists as a real file.Noneentries inurlswill be skipped.
- class ll.url.Resource[source]
Bases:
objectA
Resourceis a base class that provides a file-like interface to local and remote files, URLs and other resources.Each resource object has the following attributes:
In addition to file methods (like
read(),readlines(),write()andclose()) a resource object might provide the following methods:finalurl()Return the real URL of the resource (this might be different from the
urlattribute in case of a redirect).size()Return the size of the file/resource.
mdate()Return the last modification date of the file/resource as a
datetime.datetimeobject in UTC.mimetype()Return the mimetype of the file/resource.
imagesize()Return the size of the image (if the resource is an image file) as a
(width, height)tuple. This requires the PIL.
- class ll.url.FileResource[source]
Bases:
ll.url.ResourceA subclass of
Resourcethat handles local files.
- class ll.url.RemoteFileResource[source]
Bases:
ll.url.ResourceA subclass of
Resourcethat handles remote files (i.e. those using thesshscheme).
- class ll.url.URLResource[source]
Bases:
ll.url.ResourceA subclass of
Resourcethat handles HTTP, FTP and other URLs (i.e. those that are not handled byFileResourceorRemoteFileResource.
- class ll.url.SchemeDefinition[source]
Bases:
objectA
SchemeDefinitioninstance defines the properties of a particular URL scheme.- __init__(scheme, usehierarchy, useserver, usefrag, islocal=False, isremote=False, defaultport=None)[source]
Create a new
SchemeDefinitioninstance. Arguments are:scheme: The name of the scheme;usehierarchy: Specifies whether this scheme uses hierarchical URLs or opaque URLs (i.e. whetherhier_partoropaque_partfrom the BNF in RFC 2396 is used);useserver: Specifies whether this scheme uses an Internet-based serverauthoritycomponent or a registry of naming authorities (only for hierarchical URLs);usefrag: Specifies whether this scheme uses fragments (according to the BNF in RFC 2396 every scheme does, but it doesn’t make sense for e.g."javascript","mailto"or"tel");islocal: Specifies whether URLs with this scheme refer to local files;isremote: Specifies whether URLs with this scheme refer to remote files (there may be schemes which are neither local nor remote, e.g."mailto");defaultport: The default port for this scheme (only for schemes using server based authority).
- connect(url, context=None, **kwargs)[source]
Create a
Connectionfor theURLurl(which must haveselfas the scheme).
- closeall(context)[source]
Close all connections active for this scheme in the context
context.
- class ll.url.URL[source]
Bases:
objectAn RFC 2396 compliant URL.
- __init__(url=None)[source]
Create a new
URLinstance.urlmay be astrobject, or anURL(in which case you’ll get a copy ofurl), orNone(which will create anURLreferring to the “current document”).
- clone()[source]
Return an identical copy
self.
- withfile(file)[source]
Return a new
URLwhere the filename (i.e. the name of last component ofpath_segments) has been replaced withfile.
- __truediv__(other)[source]
Join
selfwith another (possible relative)URLother, to form a newURL.othermay be astrorURLobject. It may beNone(referring to the “current document”) in which caseselfwill be returned. It may also be a list or other iterable. For this case a list (or iterator) will be returned where__div__()will be applied to every item in the list/iterator. E.g. the following expression returns all the files in the current directory as absolute URLs (see the methodfiles()and the functionhere()for further explanations):>>> here = url.here() >>> for f in here/here.files(): ... print(f)
- __rtruediv__(other)[source]
Right hand version of
__div__(). This supports lists and iterables as the left hand side too.
- relative(baseurl, allowschemerel=False)[source]
Return an relative
URLrelsuch thatbaseurl/rel == self, i.e. this is the inverse operation of__div__().If
selfis relative, has a differentschemeorauthoritythanbaseurlor a non-hierarchical scheme, an identical copy ofselfwill be returned.If
allowschemerelis true, scheme relative URLs are allowed, i.e. if bothselfandbaseurluse the same hierarchical scheme, but a different authority (i.e. server), a scheme relative url (//server/path/file.html) will be returned.
- __bool__()[source]
Return whether the
URLis not empty, i.e. whether it is not theURLreferring to the start of the current document.
- __eq__(other)[source]
Return whether two
URLobjects are equal. Note that only properties relevant for the current scheme will be compared.
- __hash__()[source]
Return a hash value for
self, to be able to useURLobjects as dictionary keys. You must be careful not to modify anURLas soon as you use it as a dictionary key.
- abs(scheme=- 1)[source]
Return an absolute version of
self(works only for local URLs).If the argument
schemeis specified, it will be used for the resulting URL otherwise the result will have the same scheme asself.
- real(scheme=- 1)[source]
Return the canonical version of
self, eliminating all symbolic links (works only for local URLs).If the argument
schemeis specified, it will be used for the resulting URL otherwise the result will have the same scheme asself.
- islocal()[source]
Return whether
selfrefers to a local file, i.e. whetherselfis a relativeURLor the scheme isrootorfile).
- local()[source]
Return
selfas a local filename (which will only works ifselfis local (seeislocal()).
- connect(context=None, **kwargs)[source]
Return a
Connectionobject for accessing and modifying the metadata ofself.Whether you get a new connection object, or an existing one depends on the scheme, the URL itself, and the context passed in (as the
contextargument).
- open(*args, **kwargs)[source]
Open
selffor reading or writing.open()returns aResourceobject.Which additional parameters are supported depends on the actual resource created. Some common parameters are:
mode(supported by all resources)A string indicating how the file is to be opened (just like the mode argument for the builtin
open(); e.g."rb"or"wb").context(supported by all resources)open()needs aConnectionfor this URL which it gets from aContextobject.headersAdditional headers to use for an HTTP request.
dataRequest body to use for an HTTP POST request.
pythonName of the Python interpreter to use on the remote side (used by
sshURLs)niceNice level for the remove python (used by
sshURLs)
- import_(name=None)[source]
Import the content of the URL
selfas a Python module.namecan be used the specify the module name (i.e. the__name__attribute of the module). The default determines it from the URL.
Special features of ll.url
The class ll.url.URL supports many common schemes and one additional
special scheme named root that deserves an explanation.
A root URL is supposed to be an URL that is relative to a “project”
directory instead to a base URL of the document that contains the URL.
Suppose we have a document with the following base URL:
>>> from ll import url
>>> base = url.URL("root:company/it/about/index.html")
Now, if we have the following relative URL in this document:
>>> url1 = url.URL("images/logos/spam.png")
the combined URL will be:
>>> base/url1
URL('root:company/it/about/images/logos/spam.png')
Now it we use this combined URL and interpret it relative to the base URL we get back our original relative URL:
>>> (base/url1).relative(base)
URL('images/logos/spam.png')
Let’s try a root URL now:
>>> url2 = url.URL("root:images/logos/spam.png")
Combining this URL with the base URL gives us the same as url2:
>>> base/url2
URL('root:images/logos/spam.png')
But if we interpret this result relative to base, we’ll get:
>>> (base/url2).relative(base)
URL('../../../images/logos/spam.png')
I.e. this gives us a relative URL that references url2 from base when
both URLs are relative to the same root directory.