Python API
You can use req2flatpak’s python api to write a custom python script that makes use of req2flatpak’s functionality. This lets you programmatically tweak and tune the behavior as needed.
Example
You can use the following code as an example to get started with your script. The code demonstrates how to generate a flatpak-builder build module in order to install python packages on a specific flatpak target platform.
# /// script
# dependencies = ["req2flatpak"]
# ///
from req2flatpak import (
DownloadChooser,
FlatpakGenerator,
PlatformFactory,
PypiClient,
RequirementsParser,
)
platforms = [PlatformFactory.from_string("cp314-x86_64")]
requirements = RequirementsParser.parse_file("requirements.txt")
releases = PypiClient.get_releases(requirements)
downloads = {
DownloadChooser.wheel_or_sdist(release, platform)
for release in releases
for platform in platforms
}
FlatpakGenerator.write_build_module_as_json(
"python3-packages.json", requirements, downloads
)
The code starts with a header that declares req2flatpak as a dependency,
so that you can run the script with uv run, which installs req2flatpak automatically.
It continues with the imports from req2flatpak that you need.
It then uses req2flatpak to generate a build module in five steps:
define the target platforms,
specify the python packages to be installed,
query PyPI about available downloads,
choose downloads that are compatible with the target platforms,
generate the flatpak-builder build module and save it to a file.
…if you include the resulting build module in a flatpak build, the module will install the required packages.
Using the python API has the benefit that you can modify and tweak the behavior in a very flexible way. E.g., in each step in the above script, you could modify or tweak the data and/or invocations. For further details, see section Customization Options and the sections below.
The following sections explain in detail how you can use req2flatpak’s python api in your custom script.
For further inspiration you can also have a look at how req2flatpak’s main() method is implemented.
Specifying Target Platforms
A target platform describes everything that pip (or req2flatpak) needs to know when choosing package downloads to install on this platform.
Platforms
Target platforms are represented in req2flatpak as a dataclass, as follows.
- class req2flatpak.Platform(python_version: list[str], python_tags: list[str], arch: str | None = None, glibc_version: str | None = None, runtime: str | None = None, installed_packages: dict[str, str] = <factory>)
Represents a target platform for python package installations.
- arch: str | None = None
The system architecture, either
"x86_64"or"aarch64".
- glibc_version: str | None = None
The version of the C library, for example
"2.44".
- installed_packages: dict[str, str]
The python packages that are already installed, as a dict of name to version.
- python_tags: list[str]
A list of platform tags, similar to
packaging.tags.sys_tags().
- python_version: list[str]
A list of python version numbers, similar to
platform.python_version_tuple().
- runtime: str | None = None
The flatpak runtime ref that this platform was read from.
- without_installed(requirements: Iterable[Requirement]) list[Requirement]
Return the requirements that are not already installed on this platform.
Helper method to filter a list of requirements, omitting those that come installed as part of the platform. Requirements are omitted if they have the same normalized package name and same version as what comes installed.
There are many options how to create platform objects. You can create platform objects any way you wish in your script. And you can use functionality from req2flatpak, as described below.
PlatformFactory
The PlatformFactory provides methods for creating platform objects.
For example:
platform = PlatformFactory.from_string("cp314-x86_64")
There are three ways to specify a target platform with the PlatformFactory.
Use the python version of the flatpak runtime, for example 3.14 if the runtime ships python 3.14.
Wheels that are built for another python version typically cannot be installed.
If you build for more than one platform, create one platform object for each platform.
From a platform string.
The quickest way is a platform string in the format <python version>-<architecture>,
for example cp314-x86_64 or cp314-aarch64.
Such a platform is an approximation:
req2flatpak estimates the wheel tags that the system supports,
and the platform does not know which python packages are installed on the system.
# The format is "<python version>-<architecture>".
# Create one platform object per target platform:
platforms = [
PlatformFactory.from_string("cp314-x86_64"),
PlatformFactory.from_string("cp314-aarch64"),
]
# The same, without parsing a string:
platform = PlatformFactory.from_python_version_and_arch(
minor_version=14, arch="aarch64"
)
# The tags are generated for glibc up to version 2.35 by default.
# If the target platform has a newer glibc, set manylinux_max
# to its minor version, e.g., to 44 for glibc 2.44:
newer_platform = PlatformFactory.from_python_version_and_arch(
minor_version=14, arch="x86_64", manylinux_max=44
)
The estimated tags cover glibc versions up to 2.35 by default.
If the target platform has a newer glibc, set manylinux_max as shown above.
Reading the platform from a runtime (next) avoids estimating.
From a flatpak runtime.
To be exact, read the platform from the flatpak runtime that you build for.
The runtime must be installed already.
req2flatpak runs a small probe inside the runtime,
which reads the python version, the glibc version, the wheel tags
and the python packages that the runtime provides.
The ref of the runtime has the form NAME/ARCH/BRANCH,
where an empty ARCH means the architecture of this machine.
# The runtime must be installed. Its ref has the form NAME/ARCH/BRANCH,
# and an empty ARCH means the architecture of this machine:
platform = PlatformFactory.from_flatpak_runtime(
"org.gnome.Platform//51", installation="user"
)
From a platform info file.
A platform that was read from a runtime can be saved to a platform info file
(req2flatpak --platform-info REF, see Commandline Interface (CLI)),
which you can check into your repository.
Then your build does not need the runtime to be installed:
# Run "req2flatpak --platform-info" on the target system and save the output to a file.
# Then create a platform object from the data in this file:
platform = PlatformFactory.from_file("platform-info.json")
For reproducible and exact results, read the platform from the runtime once, save it to a platform info file, and use this file as target platform. Use a platform string if you only want to try something out quickly.
Documentation of all methods provided by the PlatformFactory class:
- class req2flatpak.PlatformFactory
Provides methods for creating platform objects.
- classmethod from_current_interpreter() Platform
Return a platform object that describes the current interpreter and system.
This method requires the
packagingpackage to be installed because functionality from this package is used to generate the list of tags that are supported by the current platform.The platform object returned by this method obviously depends on the specific python interpreter and system architecture used to run the req2flatpak script. The reason why is that this method reads platform properties from the current interpreter and system.
- classmethod from_file(path: str | Path) Platform
Return a platform object by reading a platform info file.
The file contains the fields of
Platformas JSON, or as YAML if the file name ends with.yamlor.yml. Such a file is created byreq2flatpak --platform-info.- Raises:
FileNotFoundError – if the file does not exist.
ValueError – if the file content is not a valid platform description.
- classmethod from_flatpak_runtime(ref: str, installation: str | None = None) Platform
Return a platform object by reading the platform from a flatpak runtime.
The runtime must be installed already. A small probe script is run inside the runtime, using
flatpak run. It reads the python version, the glibc version, the architecture, the python packages that the runtime provides, and the supported wheel tags. If the runtime offers no way to list the wheel tags, they are derived from the glibc version, and a warning is logged.- Parameters:
ref – a flatpak runtime ref of the form
NAME/ARCH/BRANCH, e.g.,org.gnome.Platform//51ororg.gnome.Platform/aarch64/51. An empty architecture means the architecture of the current machine.installation –
"user"or"system", or the name of another flatpak installation. By default, flatpak chooses the installation, and it fails if the runtime is installed in more than one.
- Raises:
PlatformProbeError – if the platform cannot be read.
- classmethod from_python_version_and_arch(minor_version: int | None = None, arch='x86_64', manylinux_max: int = 35) Platform
Return a platform object that roughly describes a cpython installation on linux.
The tags in the platform object are a rough approximation, trying to match what packaging.tags.sys_tags would return if invoked on a linux system with cpython. No guarantees are made about how closely this approximation matches a real system.
- Parameters:
minor_version – the python 3 minor version, specified as int. Defaults to the current python version.
arch – either “x86_64” or “aarch64”.
manylinux_max – the newest glibc minor version to generate manylinux tags for, e.g., 44 for glibc 2.44. Must be at least 17.
- classmethod from_string(platform_string: str) Platform | None
Return a platform object by parsing a platform string.
- Parameters:
platform_string – A string specifying python version and system architecture. The string format is “{python_version}-{system_architecture}”. For example: “cp313-x86_64” or “cp314-aarch64”. Acceptable values are the same as in
from_python_version_and_arch().
- exception req2flatpak.PlatformProbeError
Reading the platform from a flatpak runtime failed.
Specifying Package Requirements
A requirement describes the name and exact version of a python package that shall be installed.
To provide some context, there are many options for how you may want to manage requirements in your projects.
You will most likely want to use additional tools such as poetry or pip-compile in addition to req2flatpak.
The reason for this is that req2flatpak, by design, does not resolve or freeze dependencies.
In other words, req2flatpak does not resolve or freeze abstract requirement specifications (such as, e.g., packaging >= 24.1) to specific version numbers (such as, e.g., packaging==24.2).
Instead, you need to provide specific (“frozen”) version numbers to req2flatpak.
You can use tools such
pip-compile or
poetry export
(or uv pip compile)
to resolve and freeze dependencies and to export them into a requirements.txt file.
Resolve the versions for the python version of the flatpak runtime, not for your development machine,
for example with the option --python-version of uv pip compile.
This is where req2flatpak comes into play.
It can read your requirements.txt file and convert it into a flatpak-builder build module.
Requirements
Package requirements are represented in req2flatpak as a dataclass, as follows:
RequirementsParser
There are many options for how to create a requirement object in your code.
One option is to use methods from req2flatpak’s RequirementsParser class,
as in the following example:
requirements = RequirementsParser.parse_file("requirements.txt")
Documentation of all methods provided by the RequirementsParser class:
- class req2flatpak.RequirementsParser
Parses requirements.txt files in a very simple way.
This methods expects all versions to be pinned, and it does not resolve dependencies.
- classmethod parse_file(file) list[Requirement]
Parse a requirements.txt file into a list of Requirement objects.
- classmethod parse_string(requirements_txt: str) list[Requirement]
Parse requirements.txt string content into a list of Requirement objects.
It is important to note that req2flatpak’s RequirementsParser expects all package versions to be fully specified.
For example, it will not accept a package version specification such as requests >= 2.0.
Instead, it expects all versions to be pinned using the == operator, such as, e.g., requests == 2.0.
Otherwise, it raises an error.
Skipping packages
There are several reasons why you may not want req2flatpak to install a package. For example, the flatpak runtime or the base app already provides it, you install it in another way, or you do not need it in your flatpak. (Check the runtime that your app runs on, not the SDK that it is built in, because the SDK contains more packages.)
req2flatpak installs exactly the packages that are in your list of requirements. To skip packages, filter the list before querying PyPI. The filter can use any criterion, and you can also add requirements, for example build dependencies:
platforms = [PlatformFactory.from_string("cp314-x86_64")]
requirements = RequirementsParser.parse_file("requirements.txt")
# Remove the packages that this build module shall not install,
# for example because the runtime provides them already.
# Do this before querying PyPI, so that nothing is downloaded or installed for them.
# (canonicalize_name makes "Jinja2", "jinja2" and "JINJA2" the same name.)
from packaging.utils import canonicalize_name
skipped_packages = {"jinja2", "markupsafe"}
requirements = [
r
for r in requirements
if canonicalize_name(r.package) not in skipped_packages
]
releases = PypiClient.get_releases(requirements)
downloads = {
DownloadChooser.wheel_or_sdist(release, platform)
for release in releases
for platform in platforms
}
build_module = FlatpakGenerator.build_module(requirements, downloads)
A fully pinned requirements.txt also lists the dependencies of your packages.
If you skip a package, then check whether you also want to skip its dependencies.
If the packages are skipped because the runtime provides them,
read the platform from the runtime, see choosing the target platform.
This platform knows the python packages that the runtime provides.
platform.without_installed(requirements) leaves out the requirements
that the runtime provides in exactly the same version.
Requirements with another version, and packages that the runtime does not provide, are kept:
# The runtime must be installed. Its ref has the form NAME/ARCH/BRANCH,
# and an empty ARCH means the architecture of this machine:
platform = PlatformFactory.from_flatpak_runtime(
"org.gnome.Platform//51", installation="user"
)
# The platform knows the python packages that the runtime provides.
# Leave out the requirements that the runtime already satisfies:
requirements = RequirementsParser.parse_file("requirements.txt")
requirements = platform.without_installed(requirements)
releases = PypiClient.get_releases(requirements)
downloads = {
DownloadChooser.wheel_or_sdist(release, platform) for release in releases
}
build_module = FlatpakGenerator.build_module(requirements, downloads)
Querying Package Indices for Available Releases
A release describes what is offered by package index (or multiple indices) for a given package requirement.
Release
Releases are represented in req2flatpak as a dataclass, as follows:
- class req2flatpak.Release(package: str, version: str, downloads: list[Download] = <factory>)
Represents a package release as name, version, and downloads.
- downloads: list[Download]
- package: str
A python package name.
- version: str
The exact version of the package.
In other words, a release object combines the name and version of a required package
with a list of available downloads.
You can create release objects in your code as you wish,
or you can use req2flatpak’s PypiClient for this purpose.
PypiClient
The PypiClient class lets you query the “PyPI” python package index about available releases.
For example:
releases = PypiClient.get_releases(requirements)
Documentation of all methods provided by the PypiClient class:
- class req2flatpak.PypiClient
Queries package information from the PyPi package index.
- cache: ClassVar[dict | Shelf] = {}
A dict-like object for caching responses from PyPi.
- classmethod get_release(req: Requirement) Release
Query pypi regarding available releases for this requirement.
- classmethod get_releases(reqs: Iterable[Requirement]) list[Release]
Query pypi regarding available releases for these requirements.
Caching.
PypiClient caches responses to reduce traffic when querying PyPI.
By default, a simple dict is used as an in-memory cache.
To improve caching, you can use a persistent cache as follows:
import shelve
with shelve.open("pypi_cache.tmp") as cache:
PypiClient.cache = cache
releases = PypiClient.get_releases(requirements)
The above code instantiates a persistent shelve.Shelf cache using pypi_cache.tmp as filename.
The code then configures the PypiClient class to use the shelf for caching,
and then uses the cache when querying PyPI.
Clients for other package indices instead of PyPI are not included in req2flatpak. You are free, of course, to implement your own clients for additional package indices in your own script.
Choosing Compatible Downloads
req2flatpak provides methods for choosing the best compatible download for a given target platform.
Background Information
Choosing compatible downloads is important because, generally speaking, only a subset of downloads are compatible with a given target platform. For example, a release may contain wheels for older python interpreters or different system architectures.
In python packaging, the compatibility requirements of any download are encoded in the filename as a set of “tags”, as explained, for example, in pypa’s packaging documentation about tags. A download is compatible with a target platform if (at least) one of the package tags equals one of the target platform’s system tags.
Choosing the “best” compatible download is important because multiple downloads may be compatible, but only one download is needed for installing a package. Pip’s algorithm for choosing the best download uses ranked platform tags; the best download is the one that matches the highest-ranked platform tag.
Multiple implementations exist in related work for choosing the best compatible download:
Pip’s internal behavior is the official reference implementation, but pip recommends against accessing internal pip apis from outside packages, which makes it difficult to re-use the implementation.
Pyodide’s implementation of its find_matching_wheels function is easy to understand and can serve for inspiration.
req2flatpak includes its own implementation in the
DownloadChooserclass.
DownloadChooser
The DownloadChooser class provides the following methods
for filtering compatible downloads and for choosing the “best” download.
For example:
# choose the best wheel for a target platform:
wheel = DownloadChooser.wheel(release, platform)
Preferring source packages.
By default, req2flatpak prefers wheels (prebuilt binary packages) and uses a source package (sdist) only if no suitable wheel exists.
To prefer source packages, choose downloads with sdist_or_wheel instead of wheel_or_sdist:
platforms = [PlatformFactory.from_string("cp314-x86_64")]
requirements = RequirementsParser.parse_file("requirements.txt")
releases = PypiClient.get_releases(requirements)
# sdist_or_wheel prefers the source package,
# and falls back to a wheel if a release has no source package:
downloads = {
DownloadChooser.sdist_or_wheel(release, platform)
for release in releases
for platform in platforms
}
build_module = FlatpakGenerator.build_module(requirements, downloads)
Things to keep in mind:
sdist_or_wheelfalls back to a wheel if a release has no source package. UseDownloadChooser.sdistif you never want a wheel. It returnsNoneif a release has no source package.The generated pip command uses
--no-indexand--no-build-isolation. Packages built from source therefore find their build dependencies (for examplesetuptools,wheelorcython) only if these are installed already or if you add them to your requirements.A source package is not specific to an architecture, so the same download is used for all target platforms.
Preferring source packages, except for some packages. Some packages are difficult to build from source, for example packages with compiled extensions that need a compiler, system libraries or a long build time. You may want source packages for most packages, but binary wheels for these few.
A download chooser is simply a function that takes a release and a platform and returns one download of this release.
You can write your own function with any logic that you need, and use it instead of DownloadChooser.sdist_or_wheel.
Your function can also call the DownloadChooser methods.
The following example prefers source packages, except for the packages that are listed in install_as_wheel:
platforms = [PlatformFactory.from_string("cp314-x86_64")]
requirements = RequirementsParser.parse_file("requirements.txt")
releases = PypiClient.get_releases(requirements)
# Packages that are difficult to build from source,
# and that shall be installed from binary wheels:
install_as_wheel = {"bar", "scipy"}
def choose_download(release, platform):
"""Prefer source packages, except for the packages listed above."""
if release.package in install_as_wheel:
return DownloadChooser.wheel_or_sdist(release, platform)
return DownloadChooser.sdist_or_wheel(release, platform)
downloads = {
choose_download(release, platform)
for release in releases
for platform in platforms
}
build_module = FlatpakGenerator.build_module(requirements, downloads)
For more complex rules, DownloadChooser.downloads(release, platform) yields all downloads that are compatible with the platform,
in the order of preference, and you can pick from them as you wish, for example by looking at a download’s filename.
Documentation of all methods provided by the DownloadChooser class:
- class req2flatpak.DownloadChooser
Provides methods for choosing package downloads.
This class implements logic for filtering wheel and sdist downloads that are compatible with a given target platform.
- classmethod matches(download: Download, platform_tag: str) bool
Return whether a download is compatible with a target platform tag.
- classmethod downloads(release: Release, platform: Platform, wheels_only=False, sdists_only=False) Iterator[Download]
Yield suitable downloads for a specific platform.
The order of downloads matches the order of platform tags, i.e., preferred downloads are returned first.
- classmethod wheel(release: Release, platform: Platform) Download | None
Return the preferred wheel download for this release.
- classmethod sdist(release: Release) Download | None
Return the source package download for this release.
Generating a Build Module for flatpak-builder
The output of req2flatpak is a build module,
intended to be processed by flatpak-builder
as part of a build manifest.
flatpak-builder creates flatpak packages by processing build manifests. A manifest can consist of multiple build modules. Each module adds to the things to be included in the resulting flatpak package. The build modules generated by req2flatpak are no different; when processed by flatpak-builder, they install required python packages to include them into the flatpak package.
FlatpakGenerator
req2flatpak’s FlatpakGenerator class provides methods for generating a build module
that will instruct flatpak-builder to install the required python packages.
Example usage:
# generate a flatpak build module:
build_module = FlatpakGenerator.build_module(requirements, downloads)
To save a build module to a file, use write_build_module_as_json
(as in the example at the top of this page)
or write_build_module_as_yaml, which needs the optional pyyaml package.
The methods build_module_as_str and build_module_as_yaml_str return the text instead.
Passing additional options to pip.
The generated build module runs pip3 install with a fixed set of options.
Sometimes you need more options.
A typical example is --ignore-installed,
which makes pip install a package even if a package of the same name is already installed.
To change the command, modify the pip_install_template:
platforms = [PlatformFactory.from_string("cp314-x86_64")]
requirements = RequirementsParser.parse_file("requirements.txt")
releases = PypiClient.get_releases(requirements)
downloads = {
DownloadChooser.wheel_or_sdist(release, platform)
for release in releases
for platform in platforms
}
# The build module runs a pip command to install the downloaded packages.
# To change it, pass your own command as the pip_install_template argument.
# Here, the default command is extended by one option:
pip_install_template = FlatpakGenerator.default_pip_install_template.replace(
"pip3 install", "pip3 install --ignore-installed"
)
build_module = FlatpakGenerator.build_module(
requirements, downloads, pip_install_template=pip_install_template
)
Documentation of all methods provided by the FlatpakGenerator class:
- class req2flatpak.FlatpakGenerator
Provides methods for generating a flatpak-builder build module.
- static build_module(requirements: Iterable[Requirement], downloads: Iterable[Download], module_name='python3-package-installation', pip_install_template: str = 'pip3 install --verbose --exists-action=i --no-index --find-links="file://${PWD}" --prefix=${FLATPAK_DEST} --no-build-isolation ') dict
Generate a build module for inclusion in a flatpak-builder build manifest.
- classmethod build_module_as_str(*args, indent: int = 2, **kwargs) str
Generate JSON build module for inclusion in a flatpak-builder build manifest.
The args and kwargs are the same as in
build_module(). Theindentkeyword argument sets the number of spaces used for indentation.
- classmethod build_module_as_yaml_str(*args, indent: int = 2, **kwargs) str
Generate YAML build module for inclusion in a flatpak-builder build manifest.
The args and kwargs are the same as in
build_module(). Theindentkeyword argument sets the number of spaces used for indentation.
- default_pip_install_template: str = 'pip3 install --verbose --exists-action=i --no-index --find-links="file://${PWD}" --prefix=${FLATPAK_DEST} --no-build-isolation '
The default pip command. To use another command, pass it as
pip_install_templateargument.
- classmethod write_build_module_as_json(file: str | PathLike | TextIO, *args, indent: int = 2, **kwargs) None
Write a JSON build module for inclusion in a flatpak-builder build manifest.
- Parameters:
file – The path of the output file, or a text stream.
indent – The number of spaces used for indentation.
The other args and kwargs are the same as in
build_module().
- classmethod write_build_module_as_yaml(file: str | PathLike | TextIO, *args, indent: int = 2, **kwargs) None
Write a YAML build module for inclusion in a flatpak-builder build manifest.
This needs the optional
pyyamlpackage.- Parameters:
file – The path of the output file, or a text stream.
indent – The number of spaces used for indentation.
The other args and kwargs are the same as in
build_module().
Customization Options
Using req2flatpak’s Python API gives many options for customization. You have all the freedom in the world to modify each step as you see fit.
For example:
# define your target platforms
platforms = [PlatformFactory.from_string("cp314-x86_64")]
# Optionally pre-process or otherwise tweak your requirements
# before feeding them into req2flatpak,
# e.g., using pip-compile.
# Read (or otherwise create) your requirements list:
requirements = RequirementsParser.parse_file("requirements.txt")
# Optionally tweak the requirements list that was parsed by req2flatpak.
# For example, you may wish to remove package "example" because it comes pre-installed:
requirements = {r for r in requirements if r.package != "example"}
# Optionally query other package indices by implementing a class similar to PyPiClient:
class MyClient(PypiClient):
"""Custom client for querying another package index instead of PyPi."""
releases = MyClient.get_releases(requirements)
# Choose downloads with one of the ``DownloadChooser`` methods.
# (Use ``sdist_or_wheel`` instead if you prefer source packages over wheels.)
downloads = {
DownloadChooser.wheel_or_sdist(release, platform)
for release in releases
for platform in platforms
}
# Optionally tweak the downloads list.
# Optionally modify the commandline options that will be passed to pip-install
# by defining a custom pip_install template. E.g., to ignore preinstalled packages:
custom_template = FlatpakGenerator.default_pip_install_template.replace(
"pip3 install", "pip3 install --ignore-installed"
)
# Generate the flatpak build module:
build_module = FlatpakGenerator.build_module(
requirements, downloads, pip_install_template=custom_template
)
# Optionally, tweak the build module that was generated by req2flatpak.
# For example, to provide a meaningful name for your build module:
build_module["name"] = "my-custom-name"
# Convert to JSON or YAML as you wish:
json_str = FlatpakGenerator.build_module_as_str(
requirements, downloads, pip_install_template=custom_template
)
yaml_str = FlatpakGenerator.build_module_as_yaml_str(
requirements, downloads, pip_install_template=custom_template
)
More examples of how to customize req2flatpak are in the sections above,
for example how to prefer source packages over wheels (source packages),
how to skip packages (skipping packages),
and how to pass additional options to the pip install command (pip options).