Poetry is a free and open-source tool designed to manage dependencies and package Python projects efficiently. It provides a streamlined overview of your project’s dependency structure, simplifies dependency installation, and makes it easy to publish your project to PyPI.
This guide will walk you through installing Poetry using Pipx and configuring it to manage a Flask app on Ubuntu 24.04. You’ll also learn how to create a virtual environment and run your Flask project with Poetry and Gunicorn.
Requirements Before You Begin
- You are working on an Ubuntu 24.04 system.
Matching infrastructure at centron
Scripts and services eventually need an environment that keeps running: ccloud³ VMs from €3.12 per month, billed by the hour. Rent a cloud server →
Installing Poetry via Pipx on Ubuntu 24.04
Installing Poetry in an isolated environment is recommended to avoid conflicts between Poetry’s internal components and your system’s global Python packages. Use the steps below to set up Pipx and install Poetry:
1. Refresh the APT Repository
$ sudo apt update2. Install Pipx
$ sudo apt install pipx -y3. Add Pipx to Your System PATH
$ pipx ensurepath4. Enable Auto-Completion for Pipx Commands
$ echo 'eval "$(register-python-argcomplete pipx)"' >> ~/.bashrc5. Apply the Configuration Changes
$ source ~/.bashrc6. Use Pipx to Install Poetry
$ pipx install poetryAfter installation, your terminal should display something like the following:
installed package poetry 2.0.0, installed using Python 3.12.3 These apps are now globally available - poetry done!
7. Check the Installed Poetry Version
$ poetry --versionThe expected output will be similar to:
Poetry (version 2.0.0)
Starting a New Poetry Project for Flask Development
You can either initialize Poetry in an existing Python project or let it create a new one from scratch. Using Poetry to set up a fresh project ensures the proper structure and configuration are created automatically. Below are the steps to begin a new Poetry-managed Flask project.
1. Create a New Project Directory
$ poetry new flask-appThe command above generates a folder named flask-app and includes the following structure:
- flask_app: Contains an
__init__.pyfile for your Flask application logic, modules, and support code. - pyproject.toml: Defines project metadata, Poetry settings, and dependencies.
- README.md: A basic documentation template for your project.
- tests: Organizes and stores the project's test files.
Created package flask_app in flask-app
2. Move into the Project Directory
$ cd flask-appSetting Up a Virtual Environment and Installing Flask
1. Choose the Python Interpreter
$ poetry env use python3This command tells Poetry to use the system’s default Python 3 interpreter. If you want a specific version, you can run something like poetry env use python3.11, assuming that version is installed.
Creating virtualenv flask-app-vnQ3DaWl-py3.12 in /home/linuxuser/.cache/pypoetry/virtualenvs
Using virtualenv: /home/linuxuser/.cache/pypoetry/virtualenvs/flask-app-vnQ3DaWl-py3.12
2. Get the Activation Command
$ poetry env activatesource /home/linuxuser/.cache/pypoetry/virtualenvs/flask-app-vnQ3DaWl-py3.12/bin/activate
3. Activate the Virtual Environment
$ source /home/linuxuser/.cache/pypoetry/virtualenvs/flask-app-vnQ3DaWl-py3.12/bin/activateOnce activated, your terminal prompt will look like this:
(flask-app-py3.12) linuxuser@:~/flask-app$
4. Install Flask in the Project
$ poetry add flaskThis command performs several actions:
- Installs Flask and all related packages into the virtual environment.
- Records the version in your
pyproject.tomlfile. - Creates a
poetry.lockfile to lock versions for reproducibility.
Using version ^3.1.0 for flask
Updating dependencies
Resolving dependencies... (0.2s)
Package operations: 7 installs, 0 updates, 0 removals
- Installing markupsafe (3.0.2)
- Installing blinker (1.9.0)
- Installing click (8.1.8)
- Installing itsdangerous (2.2.0)
- Installing jinja2 (3.1.5)
- Installing werkzeug (3.1.3)
- Installing flask (3.1.0)
Writing lock file
5. Exit the Virtual Environment
$ deactivateConfiguring Firewall Rules for Flask on Ubuntu 24.04
On most Ubuntu 24.04 systems, the Uncomplicated Firewall (UFW) is enabled by default. To ensure access to your Flask app, you need to open the port it uses—typically port 5000. Use the steps below to allow traffic through port 5000 and reload the firewall settings.
1. Permit Traffic on Port 5000
$ sudo ufw allow 5000/tcp2. Apply the Updated Firewall Configuration
$ sudo ufw reload3. Confirm UFW Rule Activation
$ sudo ufw statusThe output will typically include:
Status: active
To Action From
-- ------ ----
22/tcp ALLOW Anywhere
5000/tcp ALLOW Anywhere
22/tcp (v6) ALLOW Anywhere (v6)
5000/tcp (v6) ALLOW Anywhere (v6)
Running a Flask Application with Poetry
Poetry does more than just manage dependencies; it can also handle running Python projects within its managed virtual environment. Follow the instructions below to activate the virtual environment and run your Flask app.
1. Retrieve the Virtual Environment Activation Command
$ poetry env activateThe result will look like:
source /home/linuxuser/.cache/pypoetry/virtualenvs/flask-app-vnQ3DaWl-py3.12/bin/activate
2. Enable the Virtual Environment
$ source /home/linuxuser/.cache/pypoetry/virtualenvs/flask-app-vnQ3DaWl-py3.12/bin/activate3. Change to the Flask Project Directory
$ cd flask_app4. Create the app.py File
$ nano app.py5. Add This Code to the File
from flask import Flask
app = Flask(__name__)
@app.route('/')
def home():
return "<h1>Greetings</h1>"
if __name__ == '__main__':
app.run(host='0.0.0.0', port='5000')To save the file, press Ctrl+X, then hit Y and Enter.
This code launches a simple webpage that displays “Greetings” at the root URL.
6. Launch the Flask App with Poetry
$ poetry run python app.pyYour terminal should show an output like the following:
* Serving Flask app 'app'
* Debug mode: off
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Running on all addresses (0.0.0.0)
* Running on http://127.0.0.1:5000
* Running on http://<SERVER-IP>:5000
Press CTRL+C to quit
To view your Flask web application, open a browser and visit:
http://<SERVER-IP>:5000
To shut down the server, press Ctrl+C in your terminal.
Managing Development and Production Dependencies with Poetry
Poetry supports grouping dependencies, which helps separate development tools from production packages. Here’s how to create a development group and add pytest for testing purposes.
1. Install Pytest in a Dev Dependency Group
$ poetry add pytest --group devThis command adds a section named [tool.poetry.group.dev.dependencies] in the pyproject.toml file. It includes pytest = "^8.3.4" as part of the dev group.
Dependencies meant for production should not belong to any group. Instead, they should go into the main section [tool.poetry.dependencies]. This ensures they are available during packaging and deployment, without being left out.
2. Create a Unit Test for the Flask App
Navigate to the testing folder within your Flask project:
$ cd ~/flask-app/testsCreate a new folder named unit:
$ mkdir unitMove into the newly created directory:
$ cd unitCreate an __init__.py file to indicate the folder is a Python package:
$ touch __init__.pyThe __init__.py file allows Python to treat the directory as a package, enabling module imports. See the official Python documentation for more details.
Create a test file named test_app.py:
$ nano test_app.pyInsert the following test code:
import pytest
from flask_app.app import app
@pytest.fixture
def client():
with app.test_client() as client:
yield client
def test_the_home_route(client):
response = client.get('/')
assert response.status_code == 200
assert b"<h1>Greetings</h1>" in response.dataSave and close the file by pressing Ctrl+X, then Y, and finally Enter.
This unit test checks whether the Flask app’s root endpoint returns the expected HTML content.
3. Run the Unit Test
$ pytestThe output will resemble:
platform linux -- Python 3.12.3, pytest-8.3.4, pluggy-1.5.0
rootdir: /home/linuxuser/flask-app
configfile: pyproject.toml
collected 1 item
test_app.py . [100%]
============================= 1 passed in 0.11s ==============================
Setting Up Gunicorn for Flask in Production
Gunicorn is a production-ready WSGI server for Python web apps. It efficiently handles multiple client requests, making it ideal for running Flask in a live environment. Below are steps to install and use Gunicorn with your Flask project.
1. Move to the Flask Application Directory
$ cd ~/flask-app/flask_app2. Add Gunicorn as a Root Dependency
$ poetry add gunicorn3. Create the wsgi.py File
$ nano wsgi.pyPaste the following Python code:
from app import app
if __name__ == '__main__':
app.run()Save and exit using Ctrl+X, then press Y and Enter.
4. Launch Flask App Using Gunicorn
$ gunicorn --bind 0.0.0.0:5000 wsgi:appCheck your web browser at:
http://<SERVER-IP>:5000
To stop the running server, use Ctrl+C in the terminal.
Managing and Recreating Poetry Virtual Environments
Poetry creates virtual environments that use up storage space, but they can be deleted and recreated as needed. Below are the steps to remove the current virtual environment and regenerate it.
1. Exit the Current Virtual Environment
$ deactivate2. List All Virtual Environments for the Project
$ poetry env listThe currently active environment will be marked with (Activated).
flask-app-vnQ3DaWl-py3.12 (Activated)
3. Remove the Virtual Environment
$ poetry env remove flask-app-vnQ3DaWl-py3.12Deleted virtualenv: /home/linuxuser/.cache/pypoetry/virtualenvs/flask-app-vnQ3DaWl-py3.12
4. Recreate the Virtual Environment
$ poetry env use python35. Retrieve the Activation Command
$ poetry env activatesource /home/linuxuser/.cache/pypoetry/virtualenvs/flask-app-vnQ3DaWl-py3.12/bin/activate
6. Activate the Virtual Environment
$ source /home/linuxuser/.cache/pypoetry/virtualenvs/flask-app-vnQ3DaWl-py3.12/bin/activate7. Install Dependencies from pyproject.toml
$ poetry installAs long as the pyproject.toml file is intact, Poetry can restore the environment and its dependencies at any time.
Changing the Location of the Poetry Virtual Environment
By default, Poetry saves virtual environments in ~/.cache/pypoetry/virtualenvs. To better organize your project, you can place the environment directly inside the project folder.
1. Exit the Current Environment
$ deactivate2. List Current Virtual Environments
$ poetry env listflask-app-vnQ3DaWl-py3.12 (Activated)
3. Delete the Virtual Environment
$ poetry env remove flask-app-vnQ3DaWl-py3.124. Change the Environment Location Setting
$ poetry config virtualenvs.in-project trueThis command overrides the default Poetry setting, placing the virtual environment inside your project’s root folder.
5. Confirm the Configuration
$ poetry config virtualenvs.in-projecttrue
6. Generate a New Virtual Environment
$ poetry env use python3Creating virtualenv flask-app in /home/linuxuser/flask-app/.venv
Using virtualenv: /home/linuxuser/flask-app/.venv
7. Retrieve the Activation Command
$ poetry env activatesource /home/linuxuser/flask-app/.venv/bin/activate
8. Activate the Environment
$ source /home/linuxuser/flask-app/.venv/bin/activate9. Display Environment Information
$ poetry env info
Virtualenv
Python: 3.12.3
Implementation: CPython
Path: /home/linuxuser/flask-app/.venv
Executable: /home/linuxuser/flask-app/.venv/bin/python
Valid: True
Base Platform: linux
OS: posix
Python: 3.12.3
Path: /usr
Executable: /usr/bin/python3.12
10. Reinstall All Project Dependencies
$ poetry install11. Start Flask Using Gunicorn in the New Environment
$ gunicorn --bind 0.0.0.0:5000 wsgi:appCheck the application by navigating to:
http://<SERVER-IP>:5000
Conclusion
In this guide, you learned how to install and use Poetry on Ubuntu 24.04 for managing dependencies in a Flask project. You created a Poetry project, set up virtual environments, ran tests, and configured a production-ready server using Gunicorn. Additionally, you explored how to control the location and management of your virtual environments, ensuring an efficient development workflow.
For more detailed information, visit the official Poetry documentation.
Testen Sie Ihr Setup auf ccloud³
Registrieren Sie sich in der ccloud³ und erhalten Sie 200 € Startguthaben für Ihr Projekt – z. B. für eine PostgreSQL-VM mit automatischen Backups.