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:[email protected]:port/db_name"
    • [production]:

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

      • DEBUG = "False"
      • SQLALCHEMY_DATABASE_URI = "mysql+pymysql://root:[email protected]_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(".")
    
Owner
Facundo Padilla
Técnico informático profesional y personal
Facundo Padilla
Appier is an object-oriented Python web framework built for super fast app development.

Joyful Python Web App development Appier is an object-oriented Python web framework built for super fast app development. It's as lightweight as possi

Hive Solutions 122 Dec 22, 2022
Daniel Vaz Gaspar 4k Jan 08, 2023
A proof-of-concept CherryPy inspired Python micro framework

Varmkorv Varmkorv is a CherryPy inspired micro framework using Werkzeug. This is just a proof of concept. You are free to use it if you like, or find

Magnus Karlsson 1 Nov 22, 2021
A minimal, extensible, fast and productive API framework for Python 3.

molten A minimal, extensible, fast and productive API framework for Python 3. Changelog: https://moltenframework.com/changelog.html Community: https:/

Bogdan Popa 980 Nov 28, 2022
Cses2humio - CrowdStrike Falcon Event Stream to Humio

CrowdStrike Falcon Event Stream to Humio This project intend to provide a simple

Trifork.Security 6 Aug 02, 2022
Pretty tornado wrapper for making lightweight REST API services

CleanAPI Pretty tornado wrapper for making lightweight REST API services Installation: pip install cleanapi Example: Project folders structure: . ├──

Vladimir Kirievskiy 26 Sep 11, 2022
Async Python 3.6+ web server/framework | Build fast. Run fast.

Sanic | Build fast. Run fast. Build Docs Package Support Stats Sanic is a Python 3.6+ web server and web framework that's written to go fast. It allow

Sanic Community Organization 16.7k Dec 28, 2022
Phoenix LiveView but for Django

Reactor, a LiveView library for Django Reactor enables you to do something similar to Phoenix framework LiveView using Django Channels. What's in the

Eddy Ernesto del Valle Pino 526 Jan 02, 2023
aiohttp-ratelimiter is a rate limiter for the aiohttp.web framework.

aiohttp-ratelimiter aiohttp-ratelimiter is a rate limiter for the aiohttp.web fr

JGL Technologies 4 Dec 11, 2022
Library for building WebSocket servers and clients in Python

What is websockets? websockets is a library for building WebSocket servers and clients in Python with a focus on correctness and simplicity. Built on

Aymeric Augustin 4.3k Dec 31, 2022
The little ASGI framework that shines. ?

✨ The little ASGI framework that shines. ✨ Documentation: https://www.starlette.io/ Community: https://discuss.encode.io/c/starlette Starlette Starlet

Encode 7.7k Jan 01, 2023
Serverless Python

Zappa - Serverless Python About Installation and Configuration Running the Initial Setup / Settings Basic Usage Initial Deployments Updates Rollback S

Rich Jones 11.9k Jan 01, 2023
A tool for quickly creating REST/HATEOAS/Hypermedia APIs in python

ripozo Ripozo is a tool for building RESTful/HATEOAS/Hypermedia apis. It provides strong, simple, and fully qualified linking between resources, the a

Vertical Knowledge 198 Jan 07, 2023
Embrace the APIs of the future. Hug aims to make developing APIs as simple as possible, but no simpler.

Read Latest Documentation - Browse GitHub Code Repository hug aims to make developing Python driven APIs as simple as possible, but no simpler. As a r

Hug API Framework 6.7k Dec 27, 2022
web.py is a web framework for python that is as simple as it is powerful.

web.py is a web framework for Python that is as simple as it is powerful. Visit http://webpy.org/ for more information. The latest stable release 0.62

5.8k Dec 30, 2022
Sanic integration with Webargs

webargs-sanic Sanic integration with Webargs. Parsing and validating request arguments: headers, arguments, cookies, files, json, etc. IMPORTANT: From

Endurant Devs 13 Aug 31, 2022
Tornado is a Python web framework and asynchronous networking library, originally developed at FriendFeed.

Tornado Web Server Tornado is a Python web framework and asynchronous networking library, originally developed at FriendFeed. By using non-blocking ne

20.9k Jan 01, 2023
Distribution Analyser is a Web App that allows you to interactively explore continuous distributions from SciPy and fit distribution(s) to your data.

Distribution Analyser Distribution Analyser is a Web App that allows you to interactively explore continuous distributions from SciPy and fit distribu

Robert Dzudzar 46 Nov 08, 2022
Dazzler is a Python async UI/Web framework built with aiohttp and react.

Dazzler is a Python async UI/Web framework built with aiohttp and react. Create dazzling fast pages with a layout of Python components and bindings to update from the backend.

Philippe Duval 17 Oct 18, 2022
FPS, fast pluggable server, is a framework designed to compose and run a web-server based on plugins.

FPS, fast pluggable server, is a framework designed to compose and run a web-server based on plugins. It is based on top of fastAPI, uvicorn, typer, and pluggy.

Adrien Delsalle 1 Nov 16, 2021