torf Reference

class torf.Torrent(path=None, name=None, exclude=(), trackers=(), webseeds=(), httpseeds=(), private=False, comment=None, source=None, creation_date=None, created_by='torf/2.1.0', piece_size=None, include_md5=False, randomize_infohash=False)

Torrent metainfo representation

Create a new Torrent object:

>>> from torf import Torrent
>>> torrent = Torrent('path/to/My Torrent',
...                   trackers=['https://localhost:123/announce'],
...                   comment='This is my first torrent. Be gentle.')

Convenient access to metainfo via properties:

>>> torrent.comment
'This is my first torrent. Be gentle.'
>>> torrent.comment = "This is my first torrent. Let's rock!"
>>> torrent.private = True

Full control over unencoded metainfo:

>>> torrent.metainfo['info']['private']
True
>>> torrent.metainfo['more stuff'] = {'foo': 12,
...                                   'bar': ('x', 'y', 'z')}

Hash pieces and update progress once per second:

>>> def callback(torrent, filepath, pieces_done, pieces_total):
...     print(f'{pieces_done/pieces_total*100:3.0f} % done')
>>> success = torrent.generate(callback, interval=1)
  1 % done
  2 % done
  [...]
100 % done

Write torrent file:

>>> torrent.write('my_torrent.torrent')

Create magnet link:

>>> torrent.magnet()
'magnet:?xt=urn:btih:e167b1fbb42ea72f051f4f50432703308efb8fd1&dn=My+Torrent&xl=142631&tr=https%3A%2F%2Flocalhost%3A123%2Fannounce'

Read torrent from file:

>>> t = Torrent.read('my_torrent.torrent')
>>> t.comment
"This is my first torrent. Let's rock!"
metainfo

Unencoded torrent metainfo as mutable mapping

You can put anything in here as long as keys are convertable to bytes and values are convertable to bytes, int, list or dict. See also convert() and validate().

The info key is guaranteed to exist.

path

Path to torrent content

The properties name and piece_size are changed implicitly when this property is set.

Setting this property sets name and piece length in metainfo['info'] as well as length if path is a file or files if path is a directory.

If set to None, the following keys are removed (if present) from metainfo['info']: piece length, pieces, name, length, md5sum, files

Raises:PathEmptyError – if path contains no data (i.e. empty file, empty directory or directory containing only empty files)
files

Yield relative file paths specified in metainfo

Each paths starts with name.

Note that the paths may not exist. See filepaths for existing files.

filepaths

Yield absolute paths to existing files in path

Any files that match patterns in exclude as well as hidden and empty files are not included.

filetree

files as a dictionary tree

Each node is a dict that maps directory/file names to child nodes. Each child node is a dict for directories and None for files.

If path is None, this is an empty dict.

size

Total size of content in bytes or None if path is None

piece_size

Piece size/length or None

If set to None and size is not None, use the return value of calculate_piece_size.

Setting this property sets piece length in metainfo ['info'].

calculate_piece_size(size)

Return the piece size for a total torrent size of size bytes

For torrents up to 1 GiB, the maximum number of pieces is 1000 which means the maximum piece size is 1 MiB. With increasing torrent size, both the number of pieces and the maximum piece size are increased. For torrents between 32 and 80 GiB a maximum piece size of 8 MiB is maintained by increasing the number of pieces up to 10,000. For torrents larger than 80 GiB the piece size is 16 MiB, using as many pieces as necessary.

You may override this method if you need a different algorithm.

Raises:RuntimeError – if size returns None
Returns:calculated piece size
pieces

Number of pieces the content is split into or None if piece_size returns None

name

Name of the torrent

Default to last item in path or None if path is None.

Setting this property sets or removes name in metainfo ['info'].

trackers

List of tiers of announce URLs or None for no trackers

A tier is either a single announce URL (str) or an Iterable (e.g. list) of announce URLs.

Setting this property sets or removes announce and announce-list in metainfo. announce is set to the first tracker of the first tier.

Raises:URLError – if any of the announce URLs is invalid
webseeds

List of webseed URLs or None for no webseeds

http://bittorrent.org/beps/bep_0019.html

httpseeds

List of httpseed URLs or None for no httpseeds

http://bittorrent.org/beps/bep_0017.html

private

Whether torrent should use trackers exclusively for peer discovery

Setting this property sets or removes private in metainfo['info'].

comment

Comment string or None for no comment

Setting this property sets or removes comment in metainfo.

creation_date

datetime.datetime instance or None for no creation date

int and float are also allowed and converted with datetime.datetime.fromtimestamp().

Setting this property sets or removes creation date in metainfo.

created_by

Application name or None for no creator

Setting this property sets or removes created by in metainfo.

source

Source string or None for no source

Setting this property sets or removes source in metainfo['info'].

exclude

List of file/directory name patterns to exclude

Every file path is split at the directory separator and each part, from base directory to file, is matched against each pattern.

Matching is done with fnmatch.fnmatch(), which uses these special characters:

*
matches everything
?
matches any single character
[seq]
matches any character in seq
[!seq]
matches any char not in seq
Raises:PathEmptyError – if all files are excluded
include_md5

Whether to include MD5 sums for each file

This takes only effect when generate() is called.

infohash

SHA1 info hash

infohash_base32

Base32 encoded SHA1 info hash

randomize_infohash

Whether to ensure that infohash is always different

This allows cross-seeding without changing piece_size manually.

Setting this property to True sets entropy in metainfo['info'] to a random integer. Setting it to False removes that value.

is_ready

Whether this torrent is ready to be exported to a file or magnet link

generate(callback=None, interval=0)

Hash pieces and report progress to callback

This method sets pieces in metainfo['info'] when all pieces are hashed successfully.

Parameters:
  • callback (callable) – Callable with signature (torrent, filepath, pieces_done, pieces_total); if callback returns anything else than None, hashing is canceled
  • interval (float) – Minimum number of seconds between calls to callback (if 0, callback is called once per piece)
Raises:
Returns:

True if all pieces were successfully hashed, False otherwise

convert()

Return metainfo with all keys encoded to bytes and all values encoded to bytes, int, list or OrderedDict

Raises:MetainfoError – on values that cannot be converted properly
validate()

Check if all mandatory keys exist in metainfo and are of expected types

The necessary values are documented here:

Note that announce is not considered mandatory because clients can find peers via DHT.

Raises:MetainfoError – if metainfo would not generate a valid torrent file or magnet link
dump(validate=True)

Create bencoded metainfo (i.e. the content of a torrent file)

Parameters:validate (bool) – Whether to run validate() first
Returns:metainfo as bencoded bytes
write_stream(stream, validate=True)

Write metainfo to a file-like object

Before any data is written, stream is truncated if possible.

Parameters:
  • stream – Writable file-like object (e.g. io.BytesIO)
  • validate (bool) – Whether to run validate() first
Raises:
write(filepath, validate=True, overwrite=False, mode=438)

Write metainfo to torrent file

This method is essentially equivalent to:

>>> with open('my.torrent', 'wb') as f:
...     f.write(torrent.dump())
Parameters:
  • filepath – Path of the torrent file
  • validate (bool) – Whether to run validate() first
  • overwrite (bool) – Whether to silently overwrite filepath (only if all pieces were hashed successfully)
  • mode – File permissions of filepath
Raises:
magnet(name=True, size=True, trackers=True, tracker=False, validate=True)

BTIH Magnet URI

Parameters:
  • name (bool) – Whether to include the name
  • size (bool) – Whether to include the size
  • trackers (bool) – Whether to include all trackers
  • tracker (bool) – Whether to include only the first tracker of the first tier (overrides trackers)
  • validate (bool) – Whether to run validate() first
classmethod read_stream(stream, validate=True)

Read torrent metainfo from file-like object

Parameters:
  • stream – Readable file-like object (e.g. io.BytesIO)
  • validate (bool) – Whether to run validate() on the new Torrent object
Raises:
  • ReadError – if reading from stream fails
  • ParseError – if stream does not produce a valid bencoded byte string
  • MetainfoError – if validate is True and the read metainfo is invalid
Returns:

New Torrent object

classmethod read(filepath, validate=True)

Read torrent metainfo from file

Parameters:
  • filepath – Path of the torrent file
  • validate (bool) – Whether to run validate() on the new Torrent object
Raises:
  • ReadError – if reading from filepath fails
  • ParseError – if filepath does not contain a valid bencoded byte string
  • MetainfoError – if validate is True and the read metainfo is invalid
Returns:

New Torrent object

copy()

Return a new object with the same metainfo

Internally, this simply copies the internal metainfo dictionary with copy.deepcopy() and gives it to the new instance.

exception torf.TorfError

Base exception for all exceptions raised by torf

errno

Error code (see errno module)

exception torf.MetainfoError(msg)

Invalid torrent metainfo

exception torf.ParseError(filepath=None)

Invalid bencoded metainfo

exception torf.PathNotFoundError(path)

Path does not exist

exception torf.PathEmptyError(path)

Empty file or directory or directory that contains only empty files

exception torf.ReadError(error_code, path=None)

Unreadable file or stream

path

File path that caused the error

exception torf.WriteError(error_code, path=None)

Unwritable file or stream

path

File path that caused the error

exception torf.URLError(url)

Invalid URL

exception torf.PieceSizeError(min=None, max=None, size=None)

Invalid piece size