class documentation

File is a resource that represents a plain non-interpreted file (although it can look for an extension like .rpy or .cgi and hand the file to a processor for interpretation if you wish). Its constructor takes a file path.

Alternatively, you can give a directory path to the constructor. In this case the resource will represent that directory, and its children will be files underneath that directory. This provides access to an entire filesystem tree with a single Resource.

If you map the URL 'http://server/FILE' to a resource created as File('/tmp'), then http://server/FILE/ will return an HTML-formatted listing of the /tmp/ directory, and http://server/FILE/foo/bar.html will return the contents of /tmp/foo/bar.html .

Method __init__ Create a file with the given path.
Method createSimilarFile Undocumented
Method directoryListing Return a resource that generates an HTML listing of the directory this path represents.
Method getChild If this File"s path refers to a directory, return a File referring to the file named path in that directory.
Method getFileSize Return file size.
Method ignoreExt Ignore the given extension.
Method listEntities Undocumented
Method listNames Undocumented
Method makeProducer Make a StaticProducer that will produce the body of this response.
Method openForReading Open a file and return it.
Method redirect Undocumented
Method render_GET Begin sending the contents of this File (or a subset of the contents, based on the 'range' header) to the given request.
Class Variable childNotFound Resource used to render 404 Not Found error pages.
Class Variable forbidden Resource used to render 403 Forbidden error pages.
Class Variable indexNames Undocumented
Class Variable processors Undocumented
Instance Variable contentEncodings a mapping of extensions to encoding types used to set default value for the Content-Encoding header.
Instance Variable contentTypes a mapping of extensions to MIME types used to set the default value for the Content-Type header. It is initialized with the values returned by loadMimeTypes.
Instance Variable defaultType Undocumented
Instance Variable encoding Undocumented
Instance Variable ignoredExts Undocumented
Instance Variable registry Undocumented
Instance Variable type Undocumented
Method _contentRange Return a string suitable for the value of a Content-Range header for a range with the given offset and size.
Method _doMultipleRangeRequest Set up the response for Range headers that specify a single range.
Method _doSingleRangeRequest Set up the response for Range headers that specify a single range.
Method _parseRangeHeader Parse the value of a Range header into (start, stop) pairs.
Method _rangeToOffsetAndSize Convert a start and end from a Range header to an offset and size.
Method _setContentHeaders Set the Content-length and Content-type headers for this request.

Inherited from Resource:

Method delEntity Undocumented
Method getChildForRequest Deprecated in favor of getChildForRequest.
Method getChildWithDefault Retrieve a static or dynamically generated child resource from me.
Method getDynamicEntity Undocumented
Method getStaticEntity Undocumented
Method listDynamicEntities Undocumented
Method listDynamicNames Undocumented
Method listStaticEntities Undocumented
Method listStaticNames Undocumented
Method putChild Register a static child.
Method reallyPutEntity Undocumented
Method render Render a given resource. See IResource's render method.
Method render_HEAD Default handling of HEAD method.
Class Variable allowedMethods Undocumented
Class Variable isLeaf Signal if this IResource implementor is a "leaf node" or not. If True, getChildWithDefault will not be called on this Resource.
Class Variable server Undocumented
Instance Variable children Undocumented

Inherited from FilePath (via Resource):

Method __cmp__ Undocumented
Method __eq__ Undocumented
Method __ge__ Undocumented
Method __getstate__ Support serialization by discarding cached os.stat results and returning everything else.
Method __gt__ Undocumented
Method __le__ Undocumented
Method __lt__ Undocumented
Method __ne__ Undocumented
Method __repr__ Undocumented
Method asBytesMode Return this FilePath in bytes-mode.
Method asTextMode Return this FilePath in unicode-mode.
Method basename Retrieve the final component of the file path's path (everything after the final path separator).
Method changed Clear any cached information about the state of this path on disk.
Method child Create and return a new FilePath representing a path contained by self.
Method childSearchPreauth Return my first existing child with a name in paths.
Method chmod Changes the permissions on self, if possible. Propagates errors from os.chmod up.
Method clonePath Make an object of the same type as this FilePath, but with path of path.
Method copyTo Copies self to destination.
Method create Exclusively create a file, only if this file previously did not exist.
Method createDirectory Create the directory the FilePath refers to.
Method descendant Retrieve a child or child's child of this path.
Method dirname Retrieve all of the components of the FilePath's path except the last one (everything up to the final path separator).
Method exists Check if this FilePath exists.
Method getAccessTime Retrieve the time that this file was last accessed.
Method getDevice Retrieves the device containing the file. The inode number and device number together uniquely identify the file, but the device number is not necessarily consistent across reboots or system crashes.
Method getGroupID Returns the group ID of the file.
Method getInodeNumber Retrieve the file serial number, also called inode number, which distinguishes this file from all other files on the same device.
Method getModificationTime Retrieve the time of last access from this file.
Method getNumberOfHardLinks Retrieves the number of hard links to the file.
Method getPermissions Returns the permissions of the file. Should also work on Windows, however, those permissions may not be what is expected in Windows.
Method getsize Retrieve the size of this file in bytes.
Method getStatusChangeTime Retrieve the time of the last status change for this file.
Method getUserID Returns the user ID of the file's owner.
Method globChildren Assuming I am representing a directory, return a list of FilePaths representing my children that match the given pattern.
Method isabs Check if this FilePath refers to an absolute path.
Method isBlockDevice Returns whether the underlying path is a block device.
Method isdir Check if this FilePath refers to a directory.
Method isfile Check if this file path refers to a regular file.
Method islink Check if this FilePath points to a symbolic link.
Method isSocket Returns whether the underlying path is a socket.
Method linkTo Creates a symlink to self to at the path in the FilePath linkFilePath.
Method listdir List the base names of the direct children of this FilePath.
Method makedirs Create all directories not yet existing in path segments, using os.makedirs.
Method moveTo Move self to destination - basically renaming self to whatever destination is named.
Method open Open this file using mode or for writing if alwaysCreate is True.
Method parent A file path for the directory containing the file at this file path.
Method parents Retrieve an iterator of all the ancestors of this path.
Method preauthChild Use me if path might have slashes in it, but you know they're safe.
Method realpath Returns the absolute target as a FilePath if self is a link, self otherwise.
Method remove Removes the file or directory that is represented by self. If self.path is a directory, recursively remove all its children before removing the directory. If it's a file or link, just delete it.
Method requireCreate Sets the alwaysCreate variable.
Method restat Re-calculate cached effects of 'stat'. To refresh information on this path after you know the filesystem may have changed, call this method.
Method setContent Replace the file at this path with a new file that contains the given bytes, trying to avoid data-loss in the meanwhile.
Method sibling Return a FilePath with the same directory as this instance but with a basename of path.
Method siblingExtension Attempt to return a path with my name, given the extension at ext.
Method siblingExtensionSearch Attempt to return a path with my name, given multiple possible extensions.
Method splitext Split the file path into a pair (root, ext) such that root + ext == path.
Method temporarySibling Construct a path referring to a sibling of this path.
Method touch Updates the access and last modification times of the file at this file path to the current time. Also creates the file if it does not already exist.
Instance Variable alwaysCreate When opening this file, only succeed if the file does not already exist.
Instance Variable path The path from which 'downward' traversal is permitted.
Property sep Return a filesystem separator.
Method _asBytesPath Return the path of this FilePath as bytes.
Method _asTextPath Return the path of this FilePath as text.
Method _getPathAsSameTypeAs If pattern is bytes, return FilePath.path as bytes. Otherwise, return FilePath.path as unicode.
Class Variable _chunkSize Undocumented
Instance Variable _statinfo Undocumented

Inherited from AbstractFilePath (via Resource, FilePath):

Method __hash__ Hash the same as another AbstractFilePath with the same path as mine.
Method getatime Deprecated. Use getAccessTime instead.
Method getContent Retrieve the contents of the file at this path.
Method getctime Deprecated. Use getStatusChangeTime instead.
Method getmtime Deprecated. Use getModificationTime instead.
Method segmentsFrom Return a list of segments between a child and its ancestor.
Method walk Yield myself, then each of my children, and each of those children's children in turn.
Type Variable Selfish Undocumented
def __init__(self, path: str, defaultType: str = 'text/html', ignoredExts: Sequence[str] = (), registry: Registry|None = None, allowExt: Literal[0] = 0): (source)

Create a file with the given path.

Parameters
path:strThe filename of the file from which this File will serve data.
defaultType:strA major/minor-style MIME type specifier indicating the Content-Type with which this File's data will be served if a MIME type cannot be determined based on path's extension.
ignoredExts:Sequence[str]A sequence giving the extensions of paths in the filesystem which will be ignored for the purposes of child lookup. For example, if ignoredExts is (".bar",) and path is a directory containing a file named "foo.bar", a request for the "foo" child of this resource will succeed with a File pointing to "foo.bar".
registry:RegistryThe registry object being used to handle this request. If None, one will be created.
allowExt:Literal[0]Ignored parameter, only present for backwards compatibility. Do not pass a value for this parameter.
def createSimilarFile(self, path): (source)

Undocumented

def directoryListing(self): (source)

Return a resource that generates an HTML listing of the directory this path represents.

Returns
DirectoryListerA resource that renders the directory to HTML.
def getChild(self, path, request): (source)

If this File"s path refers to a directory, return a File referring to the file named path in that directory.

If path is the empty string, return a DirectoryLister instead.

Parameters
path:bytesThe current path segment.
request:An that provides twisted.web.iweb.IRequest.The incoming request.
Returns
An object that provides resource.IResource.A resource representing the requested file or directory, or NoResource if the path cannot be accessed.
def getFileSize(self): (source)

Return file size.

def ignoreExt(self, ext): (source)

Ignore the given extension.

Serve file.ext if file is requested

def listEntities(self): (source)
def listNames(self): (source)
def makeProducer(self, request, fileForReading): (source)

Make a StaticProducer that will produce the body of this response.

This method will also set the response code and Content-* headers.

Parameters
requestThe twisted.web.http.Request object.
fileForReadingThe file object containing the resource.
Returns
A StaticProducer. Calling .start() on this will begin producing the response.
def openForReading(self): (source)

Open a file and return it.

def redirect(self, request): (source)

Undocumented

def render_GET(self, request): (source)

Begin sending the contents of this File (or a subset of the contents, based on the 'range' header) to the given request.

childNotFound = (source)

Resource used to render 404 Not Found error pages.

forbidden = (source)

Resource used to render 403 Forbidden error pages.

indexNames: list[str] = (source)

Undocumented

processors: Dict[str, Callable[[str, Any], Data]] = (source)

Undocumented

contentEncodings: dict = (source)

a mapping of extensions to encoding types used to set default value for the Content-Encoding header.

contentTypes: dict = (source)

a mapping of extensions to MIME types used to set the default value for the Content-Type header. It is initialized with the values returned by loadMimeTypes.

defaultType = (source)

Undocumented

encoding = (source)

Undocumented

ignoredExts: list[str] = (source)

Undocumented

registry = (source)

Undocumented

Undocumented

def _contentRange(self, offset, size): (source)

Return a string suitable for the value of a Content-Range header for a range with the given offset and size.

The offset and size are not sanity checked in any way.

Parameters
offsetHow far into this resource the range begins.
sizeHow long the range is.
Returns
The value as appropriate for the value of a Content-Range header.
def _doMultipleRangeRequest(self, request, byteRanges): (source)

Set up the response for Range headers that specify a single range.

This method checks if the request is satisfiable and sets the response code and Content-Type and Content-Length headers appropriately. The return value, which is a little complicated, indicates which parts of the resource to return and the boundaries that should separate the parts.

In detail, the return value is a tuple rangeInfo rangeInfo is a list of 3-tuples (partSeparator, partOffset, partSize). The response to this request should be, for each element of rangeInfo, partSeparator followed by partSize bytes of the resource starting at partOffset. Each partSeparator includes the MIME-style boundary and the part-specific Content-type and Content-range headers. It is convenient to return the separator as a concrete string from this method, because this method needs to compute the number of bytes that will make up the response to be able to set the Content-Length header of the response accurately.

Parameters
requestThe Request object.
byteRangesA list of (start, end) values as specified by the header. For each range, at most one of start and end may be None.
Returns
See above.
def _doSingleRangeRequest(self, request, startAndEnd): (source)

Set up the response for Range headers that specify a single range.

This method checks if the request is satisfiable and sets the response code and Content-Range header appropriately. The return value indicates which part of the resource to return.

Parameters
requestThe Request object.
startAndEndA 2-tuple of start of the byte range as specified by the header and the end of the byte range as specified by the header. At most one of the start and end may be None.
Returns
A 2-tuple of the offset and size of the range to return. offset == size == 0 indicates that the request is not satisfiable.
def _parseRangeHeader(self, range): (source)

Parse the value of a Range header into (start, stop) pairs.

In a given pair, either of start or stop can be None, signifying that no value was provided, but not both.

Returns
A list [(start, stop)] of pairs of length at least one.
Raises
ValueErrorif the header is syntactically invalid or if the Bytes-Unit is anything other than "bytes'.
def _rangeToOffsetAndSize(self, start, end): (source)

Convert a start and end from a Range header to an offset and size.

This method checks that the resulting range overlaps with the resource being served (and so has the value of getFileSize() as an indirect input).

Either but not both of start or end can be None:

  • Omitted start means that the end value is actually a start value relative to the end of the resource.
  • Omitted end means the end of the resource should be the end of the range.

End is interpreted as inclusive, as per RFC 2616.

If this range doesn't overlap with any of this resource, (0, 0) is returned, which is not otherwise a value return value.

Parameters
startThe start value from the header, or None if one was not present.
endThe end value from the header, or None if one was not present.
Returns
(offset, size) where offset is how far into this resource this resource the range begins and size is how long the range is, or (0, 0) if the range does not overlap this resource.
def _setContentHeaders(self, request, size=None): (source)

Set the Content-length and Content-type headers for this request.

This method is not appropriate for requests for multiple byte ranges; _doMultipleRangeRequest will set these headers in that case.

Parameters
requestThe twisted.web.http.Request object.
sizeThe size of the response. If not specified, default to self.getFileSize().