Get app version from pyproject.toml inside python code

Question:

I am not very familiar with python, I only done automation with so I am a new with packages and everything.
I am creating an API with Flask, Gunicorn and Poetry.
I noticed that there is a version number inside the pyproject.toml and I would like to create a route /version which returns the version of my app.
My app structure look like this atm:

├── README.md
├── __init__.py
├── poetry.lock
├── pyproject.toml
├── tests
│   └── __init__.py
└── wsgi.py

Where wsgi.py is my main file which run the app.

I saw peoples using importlib but I didn’t find how to make it work as it is used with:
__version__ = importlib.metadata.version("__package__")
But I have no clue what this package mean.

Asked By: pgossa

||

Answers:

You can extract version from pyproject.toml using toml package to read toml file and then display it in a webpage.

Answered By: Jurakin

You should not use __package__, which is the name of the "import package" (or maybe import module, depending on where this line of code is located), and this is not what importlib.metadata.version() expects. This function expects the name of the distribution package (the thing that you pip-install), which is the one you write in pyproject.toml as name = "???".

Answered By: sinoroc