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
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
Free & open source Rest API for YTDislike

RestAPI Free & open source Rest API for YTDislike, read docs.ytdislike.com for implementing. Todo Add websockets Installation Git clone git clone http

1 Nov 25, 2021
Pyramid - A Python web framework

Pyramid Pyramid is a small, fast, down-to-earth, open source Python web framework. It makes real-world web application development and deployment more

Pylons Project 3.7k Dec 30, 2022
A library that makes consuming a RESTful API easier and more convenient

Slumber is a Python library that provides a convenient yet powerful object-oriented interface to ReSTful APIs. It acts as a wrapper around the excellent requests library and abstracts away the handli

Sam Giles 597 Dec 13, 2022
A high-level framework for building GitHub applications in Python.

A high-level framework for building GitHub applications in Python. Core Features Async Proper ratelimit handling Handles interactions for you (

Vish M 3 Apr 12, 2022
Persistent remote applications for X11; screen sharing for X11, MacOS and MSWindows.

Table of Contents About Installation Usage Help About Xpra is known as "screen for X" : its seamless mode allows you to run X11 programs, usually on a

xpra.org 785 Dec 30, 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
Bromelia-hss implements an HSS by using the Python micro framework Bromélia.

Bromélia HSS bromelia-hss is the second official implementation of a Diameter-based protocol application by using the Python micro framework Bromélia.

henriquemr 7 Nov 02, 2022
Low code web framework for real world applications, in Python and Javascript

Full-stack web application framework that uses Python and MariaDB on the server side and a tightly integrated client side library.

Frappe 4.3k Dec 30, 2022
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

Lev 1 Nov 08, 2021
An easy-to-use high-performance asynchronous web framework.

中文 | English 一个易用的高性能异步 web 框架。 Index.py 文档 Index.py 实现了 ASGI3 接口,并使用 Radix Tree 进行路由查找。是最快的 Python web 框架之一。一切特性都服务于快速开发高性能的 Web 服务。 大量正确的类型注释 灵活且高效的

Index.py 264 Dec 31, 2022
An easy-to-use high-performance asynchronous web framework.

An easy-to-use high-performance asynchronous web framework.

Aber 264 Dec 31, 2022
Lemon is an async and lightweight API framework for python

Lemon is an async and lightweight API framework for python . Inspired by Koa and Sanic .

Joway 29 Nov 20, 2022
Asita is a web application framework for python.

What is Asita ? Asita is a web application framework for python. It is designed to be easy to use and be more easy for javascript users to use python

Mattéo 4 Nov 16, 2021
Pulumi-checkly - Checkly Pulumi Provider With Python

🚨 This project is still in very early stages and is not stable, use at your own

Checkly 16 Dec 15, 2022
Klein - A micro-framework for developing production-ready web services with Python

Klein, a Web Micro-Framework Klein is a micro-framework for developing production-ready web services with Python. It is 'micro' in that it has an incr

Twisted Matrix Labs 814 Jan 08, 2023
Try to create a python mircoservice framework.

Micro current_status: prototype. ... Python microservice framework. More in Document. You should clone this project and run inv docs. Install Not now.

修昊 1 Dec 07, 2021
FastAPI framework, high performance, easy to learn, fast to code, ready for production

FastAPI framework, high performance, easy to learn, fast to code, ready for production Documentation: https://fastapi.tiangolo.com Source Code: https:

Sebastián Ramírez 53k Jan 02, 2023
Dockerized web application on Starlite, SQLAlchemy1.4, PostgreSQL

Production-ready dockerized async REST API on Starlite with SQLAlchemy and PostgreSQL

Artur Shiriev 10 Jan 03, 2023
🔥 Fire up your API with this flamethrower

🔥 Fire up your API. Documentation: https://flama.perdy.io Flama Flama aims to bring a layer on top of Starlette to provide an easy to learn and fast

José Antonio Perdiguero 216 Dec 26, 2022