Skip to content

This repository provides a robust template for building Flask applications with MySQL integration. It includes Docker support for database containerization, automated testing with GitHub Actions, and a modular structure for scalability and maintainability.

License

Notifications You must be signed in to change notification settings

MarinCervinschi/flask-mysql-template

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

7 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

GitHub license GitHub stars GitHub forks GitHub issues GitHub visitors

Flask MySQL Template 🐍🐬

Overview

This repository provides a Flask application template integrated with MySQL. It leverages modular design principles, Docker for database containerization, and a robust testing suite to ensure ease of use and extensibility. Additionally, it uses GitHub Actions for automated testing to maintain code quality.

‼️ Use as a template:

To use it as a template for your project, you can click on the "Use this template" button on the repository page. This will create a new repository with the same structure and files as this one.

Technologies

Python Flask MySQL Docker Pytest GitHub Actions

  • Flask-MySQLdb: A Flask extension that provides MySQL database connectivity.
  • Coverage: A tool for measuring code coverage of Python programs.

Features

Continuous Integration with GitHub Actions

This repository is configured to automatically run tests on every commit and pull request using GitHub Actions. The CI pipeline ensures that new changes do not introduce errors or break existing features.

GitHub Actions Workflow

β€’ Location: .github/workflows/python-app.yml

β€’ Workflow Description:

  1. Installs the application requirements.

  2. Sets up the testing environment using Python and MySQL.

  3. Runs the test suite to validate the application.

Key Features:

  1. Automated Tests:

β€’ Ensures all unit tests in the tests/ directory are executed on every commit.

β€’ Reports errors if any test fails, preventing the merge of faulty code.

  1. Dependency Installation:

β€’ Installs dependencies specified in requirements.txt to replicate the application environment.

  1. Fast Feedback:

β€’ Developers are notified of issues immediately after pushing code, enabling faster debugging and resolution.

Repository Structure

β”œβ”€β”€ README.md                  # Documentation for the repository
β”œβ”€β”€ LICENSE                    # License information
β”œβ”€β”€ app/                       # Core application logic
β”‚   β”œβ”€β”€ __init__.py            # App initialization
β”‚   β”œβ”€β”€ config.py              # Configuration settings
β”‚   β”œβ”€β”€ db.py                  # Database connection logic
β”‚   β”œβ”€β”€ factory.py             # Application factory pattern implementation
β”‚   └── routes/                # Application routes
β”‚       β”œβ”€β”€ __init__.py        # Routes initialization
β”‚       β”œβ”€β”€ db_route.py        # Database-related routes (CRUD operations)
β”‚       └── main.py            # Main application routes
β”œβ”€β”€ docker-compose.yml         # Docker configuration for MySQL
β”œβ”€β”€ requirements.txt           # Python dependencies
β”œβ”€β”€ run.py                     # Entry point to run the Flask application
β”œβ”€β”€ schema.sql                 # MySQL database schema
└── tests/                     # Testing suite
    β”œβ”€β”€ conftest.py            # Pytest fixtures and configurations
    β”œβ”€β”€ data.sql               # Sample data for tests
    β”œβ”€β”€ test_db.py             # Unit tests for `db.py`
    β”œβ”€β”€ test_db_route.py       # Unit tests for `db_route.py`
    β”œβ”€β”€ test_factory.py        # Unit tests for `factory.py`
    └── test_main.py           # Unit tests for `main.py`

Getting Started

Prerequisites

β€’ Docker and Docker Compose

β€’ Python 3.9+ installed locally

β€’ MySQL client installed locally (optional for local database interactions)

Running the Application

With Docker and Flask

  1. Set up the .env File:

Create a .env file in the root directory with the following content to configure the MySQL database for both Docker and Flask:

MYSQL_ROOT_PASSWORD=password # Change this to a secure password

#MYSQL_USER=root # You don't need for docker-compose

MYSQL_PASSWORD=password # Change this to a secure password (same as MYSQL_ROOT_PASSWORD)

MYSQL_HOST=127.0.0.1 # flask dosn't like localhost

MYSQL_PORT=3306 # default port

MYSQL_DATABASE=mysql_db # Change this to the desired database name
  1. Start the MySQL Container:
docker-compose up --build -d
  1. Run Flask Locally:

Create a virtual environment and install the dependencies:

python3 -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt
python run.py

The application will be available at: http://127.0.0.1:5000

Database Setup

Schema Initialization

With the MySQL container build, you also initialize the database schema.sql file. If you change it, to apply the changes you can run the following command:

docker exec -i <mysql-container-name> mysql -u root -p <your-db-name> < schema.sql

Then you need to enter the password

Enter password: ...

To access the MySQL CLI, run the following command:

docker exec -it <mysql-container-name> mysql -u root -p <your-db-name>

CRUD Operations in db_route.py

The db_route.py implements CRUD (Create, Read, Update, Delete) operations using Flask and MySQL. It uses the db.py module that i created to interact with the database. It includes personal methods to handle the database connection, execute queries, and fetch results.

In particular:

  • get_db() is a helper function that creates a database connection.
  • json_data() is a helper function that converts the MySQL query results into JSON format.
  • query_db() is a helper function that executes a query and returns the results.
    • It accepts the query and a tuple of parameters.
    • It has also two optional parameters: one and commit that are set to False by default.
      • one is used to fetch a single result.
        • By default, it is set to False and returns all results.
      • commit is used to commit the transaction.
        • It is set to True when the query is an INSERT, UPDATE, or DELETE operation.
    • It returns the query results as a list of dictionaries.
  • init_db() is a helper function that initializes the database schema.
    • It reads the schema.sql file and executes the queries to create the tables.

    • It's a command line that you can run to initialize the database schema.

      flask init-db

These routes demonstrate how to use db.py functions to interact with the database effectively. Refer to db_route.py for implementation details.

Running Tests and Coverage

  1. Run Tests:
python -m pytest tests/
  1. Run Specific Test:
python -m pytest tests/<test_file_name>.py
  1. Generate a coverage report:
coverage run -m pytest
coverage report
  1. To generate an HTML coverage report:
coverage html

Open htmlcov/index.html in your web browser to view the report.


Contributing

Check out the contributing guidelines to get involved in the project.

Issues

Happy Coding! 😊

About

This repository provides a robust template for building Flask applications with MySQL integration. It includes Docker support for database containerization, automated testing with GitHub Actions, and a modular structure for scalability and maintainability.

Topics

Resources

License

Contributing

Security policy

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages