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 shopping list and kitchen inventory management app.

Flask React Project This is the backend for the Flask React project. Getting started Clone this repository (only this branch) git clone https://github

11 Jun 03, 2022
A Flask API REST to access words' definition

A Flask API to access words' definitions

Pablo Emídio S.S 9 Jul 22, 2022
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
News search API developed for the purposes of the ColdCase Project.

Saxion - Cold Case - News Search API Setup Local – Linux/MacOS Make sure you have python 3.9 and pip 21 installed. This project uses a MySQL database,

Dimitar Rangelov 3 Jul 01, 2021
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
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
A microservice written in Python detecting nudity in images/videos

py-nudec py-nudec (python nude detector) is a microservice, which scans all the images and videos from the multipart/form-data request payload and sen

Michael Grigoryan 8 Jul 09, 2022
Goblet is an easy-to-use framework that enables developers to quickly spin up fully featured REST APIs with python on GCP

GOBLET Goblet is a framework for writing serverless rest apis in python in google cloud. It allows you to quickly create and deploy python apis backed

Austen 78 Dec 27, 2022
Web3.py plugin for using Flashbots' bundle APIs

This library works by injecting a new module in the Web3.py instance, which allows submitting "bundles" of transactions directly to miners. This is do

Flashbots 293 Dec 31, 2022
Fast⚡, simple and light💡weight ASGI micro🔬 web🌏-framework for Python🐍.

NanoASGI Asynchronous Python Web Framework NanoASGI is a fast ⚡ , simple and light 💡 weight ASGI micro 🔬 web 🌏 -framework for Python 🐍 . It is dis

Kavindu Santhusa 8 Jun 16, 2022
JustPy is an object-oriented, component based, high-level Python Web Framework

JustPy Docs and Tutorials Introduction JustPy is an object-oriented, component based, high-level Python Web Framework that requires no front-en

927 Jan 08, 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 07, 2023
An abstract and extensible framework in python for building client SDKs and CLI tools for a RESTful API.

django-rest-client An abstract and extensible framework in python for building client SDKs and CLI tools for a RESTful API. Suitable for APIs made wit

Certego 4 Aug 25, 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
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
Web framework based on type hint。

Hint API 中文 | English 基于 Type hint 的 Web 框架 hintapi 文档 hintapi 实现了 WSGI 接口,并使用 Radix Tree 进行路由查找。是最快的 Python web 框架之一。一切特性都服务于快速开发高性能的 Web 服务。 大量正确的类型

Aber 19 Dec 02, 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
Python Wrapper for interacting with the Flutterwave API

Python Flutterwave Description Python Wrapper for interacting with the Flutterwa

William Otieno 32 Dec 14, 2022
PipeLayer is a lightweight Python pipeline framework

PipeLayer is a lightweight Python pipeline framework. Define a series of steps, and chain them together to create modular applications

greaterthan 64 Jul 21, 2022
The Modern And Developer Centric Python Web Framework. Be sure to read the documentation and join the Slack channel questions: http://slack.masoniteproject.com

NOTE: Masonite 2.3 is no longer compatible with the masonite-cli tool. Please uninstall that by running pip uninstall masonite-cli. If you do not unin

Masonite 1.9k Jan 04, 2023