Repository: Radu-Raicea/Dockerized-Flask Branch: master Commit: cc7478c70985 Files: 25 Total size: 19.2 KB Directory structure: gitextract_x1ccivd5/ ├── .gitignore ├── .travis.yml ├── LICENSE ├── README.md ├── docker-compose.yml ├── flask/ │ ├── Dockerfile │ ├── config.py │ ├── manage.py │ ├── project/ │ │ ├── __init__.py │ │ ├── controllers/ │ │ │ ├── __init__.py │ │ │ └── routes.py │ │ ├── models/ │ │ │ ├── __init__.py │ │ │ └── names.py │ │ ├── static/ │ │ │ ├── css/ │ │ │ │ └── style.css │ │ │ └── js/ │ │ │ └── script.js │ │ └── templates/ │ │ └── index.html │ ├── requirements.txt │ └── tests/ │ ├── __init__.py │ ├── test_configs.py │ └── test_website.py ├── nginx/ │ ├── Dockerfile │ ├── app.conf │ └── nginx.conf └── postgres/ ├── Dockerfile └── create.sql ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ ./ ../ .git/ .idea/ *.pyc flask/htmlcov/ .coverage ================================================ FILE: .travis.yml ================================================ sudo: required services: - docker env: DOCKER_COMPOSE_VERSION: 1.13.0 before_install: - sudo rm /usr/local/bin/docker-compose - curl -L https://github.com/docker/compose/releases/download/${DOCKER_COMPOSE_VERSION}/docker-compose-`uname -s`-`uname -m` > docker-compose - chmod +x docker-compose - sudo mv docker-compose /usr/local/bin before_script: - docker-compose up --build -d - sleep 10 script: - docker-compose run flask python manage.py test after_script: - docker-compose down ================================================ FILE: LICENSE ================================================ BSD 3-Clause License Copyright (c) 2017, Radu Raicea All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ================================================ FILE: README.md ================================================

logo

Dockerized web app template using NGINX, Flask, and PostgreSQL.

Travis

. ├── LICENSE ├── README.md ├── docker-compose.yml ├── dockerized_logo.png ├── flask │   ├── Dockerfile │   ├── config.py │   ├── manage.py │   ├── project │   │   ├── __init__.py │   │   ├── controllers │   │   │   ├── __init__.py │   │   │   └── routes.py │   │   ├── models │   │   │   ├── __init__.py │   │   │   └── names.py │   │   ├── static │   │   │   ├── css │   │   │   ├── img │   │   │   └── js │   │   └── templates │   │   └── index.html │   ├── requirements.txt │   └── tests │   ├── __init__.py │   ├── test_configs.py │   └── test_website.py ├── nginx │   ├── Dockerfile │   ├── app.conf │   └── nginx.conf └── postgres ├── Dockerfile └── create.sql --- ## Installation * [Windows 10 (64-bit Pro)](https://github.com/Radu-Raicea/Dockerized-Flask/wiki/%5BInstallation%5D-Windows-10-Instructions-(64-bit-Pro)) * [Windows Toolbox](https://github.com/Radu-Raicea/Dockerized-Flask/wiki/%5BInstallation%5D-Windows-Instructions-(Toolbox)) * [macOS (Yosemite 10.10.3 and higher)](https://github.com/Radu-Raicea/Dockerized-Flask/wiki/%5BInstallation%5D-macOS-Instructions-(Yosemite-10.10.3-and-higher)) * [Linux (Ubuntu 16.04)](https://github.com/Radu-Raicea/Dockerized-Flask/wiki/%5BInstallation%5D-Linux-Instructions-(Ubuntu-16.04)) ## Flask * [Using Flask Script to run commands while application is running](https://github.com/Radu-Raicea/Dockerized-Flask/wiki/%5BFlask%5D-Using-Flask-Script-to-run-commands-while-the-application-is-running) * [Running unit tests with Flask Testing and coverage](https://github.com/Radu-Raicea/Dockerized-Flask/wiki/%5BFlask%5D-Running-unit-tests-with-Flask-Testing-and-coverage) ## Docker * [Remove all Docker volumes to delete the database](https://github.com/Radu-Raicea/Dockerized-Flask/wiki/%5BDocker%5D-Remove-all-Docker-volumes-to-delete-the-database) * [Access the PostgreSQL command line terminal through Docker](https://github.com/Radu-Raicea/Dockerized-Flask/wiki/%5BDocker%5D-Access-the-PostgreSQL-command-line-terminal-through-Docker) ## Other * [Access the PostgreSQL database using a 3rd party software](https://github.com/Radu-Raicea/Dockerized-Flask/wiki/%5BOther%5D-Access-the-PostgreSQL-database-using-a-3rd-party-software) ================================================ FILE: docker-compose.yml ================================================ # -------------------------------------------------------------------------- # When 'docker-compose up --build' is run, this file is executed. # # Its purpose is to run 3 containers (nginx, flask and postgres) and # attach them together in a common network with shared volumes. # -------------------------------------------------------------------------- version: '3' services: postgres: build: ./postgres container_name: postgres ports: - 2345:5432 networks: - net environment: - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres volumes: - postgres:/var/lib/postgresql/data flask: build: ./flask container_name: flask volumes: - ./flask:/usr/src/app networks: - net environment: - APP_SETTINGS=config.DevelopmentConfig - DATABASE_URL=postgresql://postgres:postgres@postgres:5432/db_dev - DATABASE_TEST_URL=postgresql://postgres:postgres@postgres:5432/db_test - SECRET_KEY=dockertutorial depends_on: - postgres links: - postgres command: gunicorn --worker-class eventlet -w 4 -b 0.0.0.0:8000 manage:app nginx: build: ./nginx container_name: nginx ports: - 80:80 restart: always networks: - net volumes: - ./flask/project/static:/usr/share/nginx/html/static depends_on: - flask volumes: postgres: networks: net: ================================================ FILE: flask/Dockerfile ================================================ # -------------------------------------------------------------------------- # When Docker builds the flask container, it builds it from this image. # # This file pulls a Python 3 image from Docker Hub (a sort of # GitHub for Docker images), and copies the requirements.txt file to the # container. It then installs all the Python dependencies from it. # -------------------------------------------------------------------------- FROM python:3.6.1 ENV PYTHONDONTWRITEBYTECODE=True RUN mkdir -p /usr/src/app WORKDIR /usr/src/app ADD ./requirements.txt /usr/src/app/requirements.txt RUN pip install -r requirements.txt ADD . /usr/src/app ================================================ FILE: flask/config.py ================================================ # -*- coding: utf-8 -*- """ This file stores all the possible configurations for the Flask app. Changing configurations like the secret key or the database url should be stored as environment variables and imported using the 'os' library in Python. """ import os class BaseConfig: SQLALCHEMY_TRACK_MODIFICATIONS = False SECRET_KEY = os.getenv('SECRET_KEY') DEBUG = False TESTING = False class TestingConfig(BaseConfig): SQLALCHEMY_DATABASE_URI = os.getenv('DATABASE_TEST_URL') DEBUG = True TESTING = True class DevelopmentConfig(BaseConfig): SQLALCHEMY_DATABASE_URI = os.getenv('DATABASE_URL') DEBUG = True class ProductionConfig(BaseConfig): SQLALCHEMY_DATABASE_URI = os.getenv('DATABASE_URL') DEBUG = False ================================================ FILE: flask/manage.py ================================================ # -*- coding: utf-8 -*- """ This is the entry point of the Flask application. """ import unittest import coverage from flask_script import Manager from project import create_app, logger, db # The logger should always be used instead of a print(). You need to import it from # the project package. If you want to understand how to use it properly and why you # should use it, check: http://bit.ly/2nqkupO logger.info('Server has started.') # Defines which parts of the code to include and omit when calculating code coverage. COV = coverage.coverage( branch=True, include='project/*', omit=[ 'tests/*', 'project/website/*' ] ) COV.start() # Creates the Flask application object that we use to initialize things in the app. app = create_app() # Creates all the models specified in project/models import project.models db.create_all(app=app) # Initializes the Manager object, which allows us to run terminal commands on the # Flask application while it's running (using Flask-Script). manager = Manager(app) @manager.command def cov(): """ Runs the unit tests and generates a coverage report on success. While the application is running, you can run the following command in a new terminal: 'docker-compose run --rm flask python manage.py cov' to run all the tests in the 'tests' directory. If all the tests pass, it will generate a coverage report. :return int: 0 if all tests pass, 1 if not """ tests = unittest.TestLoader().discover('tests') result = unittest.TextTestRunner(verbosity=2).run(tests) if result.wasSuccessful(): COV.stop() COV.save() print('Coverage Summary:') COV.report() COV.html_report() COV.erase() return 0 else: return 1 @manager.command def test(): """ Runs the unit tests without generating a coverage report. Enter 'docker-compose run --rm flask python manage.py test' to run all the tests in the 'tests' directory, with no coverage report. :return int: 0 if all tests pass, 1 if not """ tests = unittest.TestLoader().discover('tests', pattern='test*.py') result = unittest.TextTestRunner(verbosity=2).run(tests) if result.wasSuccessful(): return 0 else: return 1 @manager.command def test_one(test_file): """ Runs the unittest without generating a coverage report. Enter 'docker-compose run --rm flask python manage.py test_one ' to run only one test file in the 'tests' directory. It provides no coverage report. Example: 'docker-compose run --rm flask python manage.py test_one test_website' Note that you do not need to put the extension of the test file. :return int: 0 if all tests pass, 1 if not """ tests = unittest.TestLoader().discover('tests', pattern=test_file + '.py') result = unittest.TextTestRunner(verbosity=2).run(tests) if result.wasSuccessful(): return 0 else: return 1 # Starts the Flask app. if __name__ == '__main__': manager.run() ================================================ FILE: flask/project/__init__.py ================================================ # -*- coding: utf-8 -*- """ This is the root of the main package of our Flask app: project. Whenever you see 'from project import ', it takes it from here. """ import os import logging from flask import Flask from flask_sqlalchemy import SQLAlchemy # Defines the format of the logging to include the time and to use the INFO logging level or worse. logging.basicConfig(format='%(asctime)s %(levelname)s: %(message)s', datefmt='%Y-%m-%d %H:%M:%S', level=logging.INFO) logger = logging.getLogger(__name__) db = SQLAlchemy() def create_app(): """ Flask application factory that creates app instances. Every time this function is called, a new application instance is created. The reason why an application factory is needed is because we need to use different configurations for running our tests. :return Flask object: Returns a Flask application instance """ app = Flask(__name__) app_settings = os.getenv('APP_SETTINGS') app.config.from_object(app_settings) db.init_app(app) # Blueprints are used for scalability. If you want to read more about it, visit: # http://flask.pocoo.org/docs/0.12/blueprints/ from project.controllers.routes import website_blueprint app.register_blueprint(website_blueprint) return app ================================================ FILE: flask/project/controllers/__init__.py ================================================ # -*- coding: utf-8 -*- """ Whenever you want to create a package in Python, you must create a directory with an __init__.py inside, even if it's empty. """ ================================================ FILE: flask/project/controllers/routes.py ================================================ # -*- coding: utf-8 -*- """ This is where all the routes and controllers are defined. """ from flask import render_template, Blueprint website_blueprint = Blueprint('website_blueprint', __name__) @website_blueprint.route('/') def index(): # Controller logic should go here return render_template('index.html') ================================================ FILE: flask/project/models/__init__.py ================================================ # -*- coding: utf-8 -*- """ Whenever you want to create a package in Python, you must create a directory with an __init__.py inside, even if it's empty. """ ================================================ FILE: flask/project/models/names.py ================================================ # -*- coding: utf-8 -*- from flask_sqlalchemy import SQLAlchemy from project import db class Name(db.Model): id = db.Column(db.Integer, primary_key=True) first_name = db.Column(db.String(128)) last_name = db.Column(db.String(128)) def __init__(self, first_name, last_name): self.first_name = first_name self.last_name = last_name def __repr__(self): return '' % self.id ================================================ FILE: flask/project/static/css/style.css ================================================ body { margin: 10px; } ================================================ FILE: flask/project/static/js/script.js ================================================ // js ================================================ FILE: flask/project/templates/index.html ================================================ Template Flask App

It's Working!

NYA
================================================ FILE: flask/requirements.txt ================================================ flask==0.12.2 gunicorn==19.7.1 psycopg2==2.7.1 Flask-SQLAlchemy==2.2 eventlet==0.21.0 flask-script==2.0.5 coverage==4.4.1 flask_testing==0.6.2 ================================================ FILE: flask/tests/__init__.py ================================================ # -*- coding: utf-8 -*- """ Whenever you want to create a package in Python, you must create a directory with an __init__.py inside, even if it's empty. """ ================================================ FILE: flask/tests/test_configs.py ================================================ # -*- coding: utf-8 -*- """ This file tests the various configurations of the Flask app. It's pretty standard and shouldn't really be modified, unless you add new configurations. """ import os import unittest from flask import current_app from flask_testing import TestCase from project import create_app app = create_app() class TestDevelopmentConfig(TestCase): def create_app(self): app.config.from_object('config.DevelopmentConfig') return app def test_app_is_development(self): self.assertTrue(app.config['SECRET_KEY'] == os.getenv('SECRET_KEY')) self.assertTrue(app.config['DEBUG'] is True) self.assertFalse(current_app is None) self.assertTrue(app.config['SQLALCHEMY_DATABASE_URI'] == os.environ.get('DATABASE_URL')) class TestTestingConfig(TestCase): def create_app(self): app.config.from_object('config.TestingConfig') return app def test_app_is_testing(self): self.assertTrue(app.config['SECRET_KEY'] == os.getenv('SECRET_KEY')) self.assertTrue(app.config['DEBUG']) self.assertTrue(app.config['TESTING']) self.assertFalse(app.config['PRESERVE_CONTEXT_ON_EXCEPTION']) self.assertTrue(app.config['SQLALCHEMY_DATABASE_URI'] == os.environ.get('DATABASE_TEST_URL')) class TestProductionConfig(TestCase): def create_app(self): app.config.from_object('config.ProductionConfig') return app def test_app_is_production(self): self.assertTrue(app.config['SECRET_KEY'] == os.getenv('SECRET_KEY')) self.assertFalse(app.config['DEBUG']) self.assertFalse(app.config['TESTING']) if __name__ == '__main__': unittest.main() ================================================ FILE: flask/tests/test_website.py ================================================ # -*- coding: utf-8 -*- """ This file defines the group of tests for the simple website routes. You can run this test group file by running the application and running 'docker-compose run --rm flask python manage.py test_one test_website' in a separate terminal window. """ import logging import os import unittest from flask_testing import TestCase from project import create_app, logger # Creates a new instance of the Flask application. The reason for this # is that we can't interrupt the application instance that is currently # running and serving requests. app = create_app() class TestWebsite(TestCase): def create_app(self): """ Instructs Flask to run these commands when we request this group of tests to be run. """ # Sets the configuration of the application to 'TestingConfig' in order # that the tests use db_test, not db_dev or db_prod. app.config.from_object('config.TestingConfig') # Sets the logger to only show ERROR level logs and worse. We don't want # to print a million things when running tests. logger.setLevel(logging.ERROR) return app def setUp(self): """Defines what should be done before every single test in this test group.""" pass def tearDown(self): """Defines what should be done after every single test in this test group.""" pass def test_index_page_successful(self): """ Every single test in this test group should be defined as a method of this class. The methods should be named as follows: test_ """ with self.client: response = self.client.get('/') self.assertEqual(response.status_code, 200) # Runs the tests. if __name__ == '__main__': unittest.main() ================================================ FILE: nginx/Dockerfile ================================================ # -------------------------------------------------------------------------- # When Docker builds the nginx container, it builds it from this image. # # This file pulls a nginx image from Docker Hub (a sort of # GitHub for Docker images), and copies NGINX config files to the container. # -------------------------------------------------------------------------- FROM nginx:1.13.0 RUN rm /etc/nginx/nginx.conf COPY nginx.conf /etc/nginx/ RUN rm /etc/nginx/conf.d/default.conf COPY app.conf /etc/nginx/conf.d/ ================================================ FILE: nginx/app.conf ================================================ server { listen 80; charset utf-8; location /static/ { autoindex on; root /usr/share/nginx/html/; } location / { proxy_pass http://flask:8000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } } ================================================ FILE: nginx/nginx.conf ================================================ user nginx; worker_processes 1; error_log /var/log/nginx/error.log warn; pid /var/run/nginx.pid; events { worker_connections 1024; } http { include /etc/nginx/mime.types; default_type text/html; log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log /var/log/nginx/access.log main; sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; include /etc/nginx/conf.d/*.conf; } ================================================ FILE: postgres/Dockerfile ================================================ # ----------------------------------------------------------------------- # When Docker builds the postgres container, it builds it from this image. # # This file pulls the latest postgres image from Docker Hub (a sort of # GitHub for Docker images), and runs the create.sql file. # ----------------------------------------------------------------------- FROM postgres ADD create.sql /docker-entrypoint-initdb.d ================================================ FILE: postgres/create.sql ================================================ -- ----------------------------------------------------------------------- -- This file is run when the postgres container is first created. It -- creates 3 databases, one for each configuration. -- ----------------------------------------------------------------------- CREATE DATABASE db_dev; CREATE DATABASE db_prod; CREATE DATABASE db_test;