Flask + Docker + Nginx + Gunicorn + MySQL + Factory Method Pattern

Overview

Author: Facundo Padilla

Social networks:

Version:

  • 1.0:
    • 01/02/2021 (DD-MM-YYYY)
    • 02/01/2021 (MM-DD-YYYY)
    • 2021/02/01 (YYYY-MM-DDDD)

What is this?:

  • This Flask project is reusable and also an example of how to merge Flask, Docker, Nginx, Gunicorn, MySQL, new: Flask-RESTX, Factory Method design pattern, and other optional dependencies such as Dynaconf, Marshmallow, SQLAlchemy, Faker, PyMySQL, Pytest, etc... which are installed inside the virtual environment "env_flask".

How to use it?

  • Easy, if you have Docker Compose installed, just run the following command inside the project directory: docker-compose up

  • You can also use the commands created inside the "Makefile" file, simply by executing the "make" command; make [OPTION] - Example: make full-start

  • Once you execute any of these commands, it starts to create the containers to work, they are already linked so you should have no problems to get it to work

  • Once you have finished running and creating the containers, simply go to http://localhost:80/

Initialize application:

  • After you have executed the commands like docker-compose up, make full-start or whatever you have created in the Makefile or used, it automatically creates the tables and works without problems, the tables are created in the predefined database with the name "flask_api", if you want to change the name of this database just go to the file "docker-compose.yaml" and change the environment variable "MYSQL_DATABASE".

  • And that's it, once the tables are created, you only have to go to http://localhost:80 (Nginx)

"Hot-Reloading":

  • You could use Watchman to do hot-reaload, but it gives some problems/bugs, so you can directly work with the virtual environment "env_flask" and start working there to simulate a hot-reload, also, it is not recommended that a container contains integrated hot-realoading if it is going to be used for hot-reloading.

  • How to activate env_flask:

    • Linux / PowerShell:

      1. Run: pip3 install virtualenv && python3 -m virtualenv env_flask
      2. Enter directory ../env_flask/bin/activate and execute: source activate (in the terminal)
      3. Return to the path where run_debug.py is found, and run: pip install -r requirements.txt
      4. Run the following commands:
        • export FLASK_APP=run_debug.py
        • flask run -h 0.0.0.0 -p 5001(the host and port can be changed to the one you want) or
        • python run_debug.py
    • Windows:

      1. Run: pip3 install virtualenv && python3 -m virtualenv env_flask
      2. Enter directory ../env_flask/bin/activate and execute: activate in CMD
      3. Return to the path where run_debug.py is found, and run: pip install -r requirements.txt
      4. Run the following commands:
        • set FLASK_APP=run_debug.py
        • flask run -h 0.0.0.0 -p 5001 (the host and port can be changed to the one you want) or
        • python run_debug.py

ATTENTION: in the Dynaconf configuration file (settings.toml), when running the run_debug.py , the MySQL connection points to localhost and port 3307, if it is going to be uploaded to production, remove the "expose" option from the docker-file.yaml file.

  • Deactivate the virtual environment:

    • Execute deactivate in the terminal or CMD

Settings:

  • docker-compose.yaml:

    • MySQL (db):

      • MYSQL_USER: the user name you want to customize (the root user is default and cannot be deleted)

      • MYSQL_PASSWORD= the password of the user (not the root)

      • MYSQL_DATABASE= name of the database you want

      • MYSQL_ROOT_PASSWORD= root user password

      • More documentation: https://hub.docker.com/_/mysql

    • Flask (flask_app):

      • PYTHONBUFFERED= by default leave it set to 1, it is used to display Python logs.

      • ENVVAR_PREFIX_FOR_DYNACONF= the name of our module

      • ENVVAR_FOR_DYNACONF= file name with extension ".toml", Dynaconf supports several others: https://dynaconf.readthedocs.io/en/docs_223/guides/examples.html

      • FLASK_APP= the name of the Python file to be executed by the server

      • FLASK_RUN_HOST= the host address of the application, defaulting to 0.0.0.0

      • FLASK_DEBUG= WARNING!, 1 enables debug, 0 for production.

      • command: Gunicorn command to execute

      • More documentation: https://hub.docker.com/_/python

    • Nginx (nginx lol):

  • settings.toml (Dynaconf file):

    • [default]

      • SQLALCHEMY_TRACK_MODIFICATIONS = "False" (is a setting that is no longer used, leave it at false)
    • [development]:

      When you switch to debug mode, the db name becomes localhost and port 3307.

      • DEBUG = "True"
      • SQLALCHEMY_DATABASE_URI = "mysql+pymysql://root:password@localhost:port/db_name"
    • [production]:

      When in production, mostly in the docker, it keeps running this configuration

      • DEBUG = "False"
      • SQLALCHEMY_DATABASE_URI = "mysql+pymysql://root:password@db_container_name/db_name"

python run.py vs flask run:

  • The difference between using Python to execute "run.py" and using "flask run", is that when you have the file "__module__.py" in the project, Python automatically adds it to the "syspath", in the case of "flask run", this does not happen, even if there is the "__init__.py" and the "__module__.py" , so to avoid problems when working with flask run, in each __init__.py file the following code fragment is added:

      import sys
      sys.path.append(".")
    
You might also like...
Fully featured framework for fast, easy and documented API development with Flask

Flask RestPlus IMPORTANT NOTICE: This project has been forked to Flask-RESTX and will be maintained by by the python-restx organization. Flask-RESTPlu

A Flask API REST to access words' definition
A Flask API REST to access words' definition

A Flask API to access words' definitions

A boilerplate Flask API for a Fullstack Project with some additional packages and configuration prebuilt. ⚙

Flask Boilerplate to quickly get started with production grade flask application with some additional packages and configuration prebuilt.

APIFlask is a lightweight Python web API framework based on Flask and marshmallow-code projects
APIFlask is a lightweight Python web API framework based on Flask and marshmallow-code projects

APIFlask APIFlask is a lightweight Python web API framework based on Flask and marshmallow-code projects. It's easy to use, highly customizable, ORM/O

A public API written in Python using the Flask web framework to determine the direction of a road sign using AI
A public API written in Python using the Flask web framework to determine the direction of a road sign using AI

python-public-API This repository is a public API for solving the problem of the final of the AIIJC competition. The task is to create an AI for the c

Otter is framework for creating microservices in Flask like fassion using RPC communication via message queue.

Otter Framework for microservices. Overview Otter is framework for creating microservices in Flask like fassion using RPC communication via message qu

Quiz Web App with Flask and MongoDB as the Databases
Quiz Web App with Flask and MongoDB as the Databases

quiz-app Quiz Web Application made with flask and mongodb as the Databases Before you run this application, change the inside MONGODB_URI ( in config.

A simple todo app using flask and sqlachemy
A simple todo app using flask and sqlachemy

TODO app This is a simple TODO app made using Flask. Packages used: DoodleCSS Special thanks to Chris McCormick (@mccrmx) :) Flask Flask-SQLAlchemy Fl

Basic Docker Compose template application with Flask, Celery, Redis, MySQL, SocketIO, Nginx and Gunicorn.

Nginx / Gunicorn / Flask 🐍 / Celery / SocketIO / MySQL / Redis / Docker 🐳 sample application Basic Docker Compose template application for orchestat

A minimal implementation of face-detection models using flask, gunicorn, nginx, docker, and docker-compose

Face-Detection-flask-gunicorn-nginx-docker This is a simple implementation of dockerized face-detection restful-API implemented with flask, Nginx, and

Dockerizing Django with Postgres, Gunicorn, Nginx and Certbot. A fully Django starter project.

Dockerizing Django with Postgres, Gunicorn, Nginx and Certbot 🚀 Features A Django stater project with fully basic requirements for a production-ready

基于Pytorch的脚手架项目,Celery+FastAPI+Gunicorn+Nginx+Supervisor实现服务部署,支持Docker发布

cookiecutter-pytorch-fastapi 基于Pytorch的 脚手架项目 按规范添加推理函数即可实现Celery+FastAPI+Gunicorn+Nginx+Supervisor+Docker的快速部署 Requirements Python = 3.6 with pip in

Deploying a production-ready Django project using Nginx and Gunicorn
Deploying a production-ready Django project using Nginx and Gunicorn

django-nginx-gunicorn This project is for deploying a production-ready Django project using Nginx and Gunicorn. Running a local server of Django is no

Nginx UI allows you to access and modify the nginx configurations files without cli.
Nginx UI allows you to access and modify the nginx configurations files without cli.

nginx ui Table of Contents nginx ui Introduction Setup Example Docker UI Authentication Configure the auth file Configure nginx Introduction We use ng

🐍 Simple FastAPI template with factory pattern architecture
🐍 Simple FastAPI template with factory pattern architecture

Description This is a minimalistic and extensible FastAPI template that incorporates factory pattern architecture with divisional folder structure. It

docker-compose uWSGI nginx flask

docker-compose uWSGI nginx flask Note that this was tested on CentOS 7 Usage sudo yum install docker

Docker image with Uvicorn managed by Gunicorn for high-performance FastAPI web applications in Python 3.6 and above with performance auto-tuning. Optionally with Alpine Linux.
Docker image with Uvicorn managed by Gunicorn for high-performance FastAPI web applications in Python 3.6 and above with performance auto-tuning. Optionally with Alpine Linux.

Supported tags and respective Dockerfile links python3.8, latest (Dockerfile) python3.7, (Dockerfile) python3.6 (Dockerfile) python3.8-slim (Dockerfil

 Learn REST API with Flask, Mysql and Docker
Learn REST API with Flask, Mysql and Docker

Learn REST API with Flask, Mysql and Docker A project for you to learn to work a flask REST api with docker and the mysql database manager! Table of C

Owner
Facundo Padilla
Técnico informático profesional y personal
Facundo Padilla
Flask-Potion is a RESTful API framework for Flask and SQLAlchemy, Peewee or MongoEngine

Flask-Potion Description Flask-Potion is a powerful Flask extension for building RESTful JSON APIs. Potion features include validation, model resource

DTU Biosustain 491 Dec 8, 2022
Flask-Potion is a RESTful API framework for Flask and SQLAlchemy, Peewee or MongoEngine

Flask-Potion Description Flask-Potion is a powerful Flask extension for building RESTful JSON APIs. Potion features include validation, model resource

DTU Biosustain 484 Feb 3, 2021
Flask Sugar is a web framework for building APIs with Flask, Pydantic and Python 3.6+ type hints.

Flask Sugar is a web framework for building APIs with Flask, Pydantic and Python 3.6+ type hints. check parameters and generate API documents automatically. Flask Sugar是一个基于flask,pyddantic,类型注解的API框架, 可以检查参数并自动生成API文档

null 162 Dec 26, 2022
Pyrin is an application framework built on top of Flask micro-framework to make life easier for developers who want to develop an enterprise application using Flask

Pyrin A rich, fast, performant and easy to use application framework to build apps using Flask on top of it. Pyrin is an application framework built o

Mohamad Nobakht 10 Jan 25, 2022
Daniel Vaz Gaspar 4k Jan 8, 2023
Swagger/OpenAPI First framework for Python on top of Flask with automatic endpoint validation & OAuth2 support

Connexion Connexion is a framework that automagically handles HTTP requests based on OpenAPI Specification (formerly known as Swagger Spec) of your AP

Zalando SE 4.2k Jan 7, 2023
NO LONGER MAINTAINED - A Flask extension for creating simple ReSTful JSON APIs from SQLAlchemy models.

NO LONGER MAINTAINED This repository is no longer maintained due to lack of time. You might check out the fork https://github.com/mrevutskyi/flask-res

null 1k Jan 4, 2023
Fully featured framework for fast, easy and documented API development with Flask

Flask RestPlus IMPORTANT NOTICE: This project has been forked to Flask-RESTX and will be maintained by by the python-restx organization. Flask-RESTPlu

Axel H. 2.7k Jan 4, 2023
Swagger/OpenAPI First framework for Python on top of Flask with automatic endpoint validation & OAuth2 support

Connexion Connexion is a framework that automagically handles HTTP requests based on OpenAPI Specification (formerly known as Swagger Spec) of your AP

Zalando SE 3.5k Feb 17, 2021
NO LONGER MAINTAINED - A Flask extension for creating simple ReSTful JSON APIs from SQLAlchemy models.

NO LONGER MAINTAINED This repository is no longer maintained due to lack of time. You might check out the fork https://github.com/mrevutskyi/flask-res

null 1k Jan 15, 2021