diff --git a/Procfile b/Procfile new file mode 100644 index 0000000..216c639 --- /dev/null +++ b/Procfile @@ -0,0 +1 @@ +web: flask db upgrade; flask translate compile; gunicorn microblog:app diff --git a/README.md b/README.md index 7a6c76b..5622b03 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,43 @@ # fast-flask -template flask app (with postgres + heroku deploy) + +A flask starter template with postgreSQL database and deployed to Heroku. + +## Getting Started (Development) + +Clone the repository. + +`git clone https://github.com/pikulet/fast-flask-example` +`cd fast-flask-example` + +Install virtualenv. + +`pip3 install virtualenv` + +Activate the virtual environment. + +`source venv\bin\activate` + +## Deployment to Heroku + +Login to Heroku. + +`heroku login` + +Create Heroku app. + +`heroku apps:create ` + +Create a PostgreSQL database on Heroku. We use the free plan. + +`heroku addson:add heroku-postgresql:hobby-dev` + +Configure environment variables for Heroku. + +`heroku config:set FLASK_APP=fastflask.py` + +Push to Heroku remote. + +`git push heroku master` + + + diff --git a/__pycache__/config.cpython-36.pyc b/__pycache__/config.cpython-36.pyc new file mode 100644 index 0000000..6c87a64 Binary files /dev/null and b/__pycache__/config.cpython-36.pyc differ diff --git a/__pycache__/fastflask.cpython-36.pyc b/__pycache__/fastflask.cpython-36.pyc new file mode 100644 index 0000000..cc32c76 Binary files /dev/null and b/__pycache__/fastflask.cpython-36.pyc differ diff --git a/app/__init__.py b/app/__init__.py new file mode 100644 index 0000000..2cc8104 --- /dev/null +++ b/app/__init__.py @@ -0,0 +1,17 @@ +from flask import Flask +from flask_bootstrap import Bootstrap +from flask_sqlalchemy import SQLAlchemy +from config import DevelopmentConfig, DeployConfig + +def create_app(): + app = Flask(__name__) + Bootstrap(app) + + app.config.from_object(DevelopmentConfig) + #app.config.from_object(DeployConfig) + return app + +app = create_app() +db = SQLAlchemy(app) + +from app import routes diff --git a/app/__pycache__/__init__.cpython-36.pyc b/app/__pycache__/__init__.cpython-36.pyc new file mode 100644 index 0000000..ff8c632 Binary files /dev/null and b/app/__pycache__/__init__.cpython-36.pyc differ diff --git a/app/__pycache__/forms.cpython-36.pyc b/app/__pycache__/forms.cpython-36.pyc new file mode 100644 index 0000000..8c4d374 Binary files /dev/null and b/app/__pycache__/forms.cpython-36.pyc differ diff --git a/app/__pycache__/models.cpython-36.pyc b/app/__pycache__/models.cpython-36.pyc new file mode 100644 index 0000000..6b20dfd Binary files /dev/null and b/app/__pycache__/models.cpython-36.pyc differ diff --git a/app/__pycache__/routes.cpython-36.pyc b/app/__pycache__/routes.cpython-36.pyc new file mode 100644 index 0000000..5856c82 Binary files /dev/null and b/app/__pycache__/routes.cpython-36.pyc differ diff --git a/app/forms.py b/app/forms.py new file mode 100644 index 0000000..d56e84a --- /dev/null +++ b/app/forms.py @@ -0,0 +1,7 @@ +from flask_wtf import FlaskForm +from wtforms import StringField, SubmitField +from wtforms.validators import DataRequired + +class InputForm(FlaskForm): + text = StringField('Enter text here...', validators=[DataRequired()]) + submit = SubmitField('Confirm') diff --git a/app/models.py b/app/models.py new file mode 100644 index 0000000..060aee7 --- /dev/null +++ b/app/models.py @@ -0,0 +1,19 @@ +from app import db + +class Text(db.Model): + + __tablename__ = 'fastflask' + + text_id = db.Column(db.Integer, primary_key=True) + text_value = db.Column(db.String(255), unique=True, nullable=False) + + def __init__(self, value): + self.text_value = value + + def __repr__(self): + return self.value + + def serialise(self): + return { + 'value' : self.value + } diff --git a/app/routes.py b/app/routes.py new file mode 100644 index 0000000..8de2a96 --- /dev/null +++ b/app/routes.py @@ -0,0 +1,31 @@ +from flask import render_template, redirect, url_for, request +from app import app, db +from app.forms import InputForm +from app.models import Text + +@app.route('/') +def index(): + return render_template('index.html', title='Home') + +@app.route('/input', methods=['GET', 'POST']) +def input(): + form = InputForm() + if form.validate_on_submit(): + return redirect(url_for('process', text=form.text.data)) + return render_template('input.html', + title='Input', + form=form) + +@app.route('/process', methods=['GET']) +def process(): + value = request.args['text'] + + existing_entry = Text.query.filter_by(text_value=value).first() + if existing_entry is None: + new_db_entry = Text(value) + db.session.add(new_db_entry) + db.session.commit() + + return render_template('index.html', + title='Input Received', + text=value) diff --git a/app/templates/index.html b/app/templates/index.html new file mode 100644 index 0000000..bf845d6 --- /dev/null +++ b/app/templates/index.html @@ -0,0 +1,10 @@ +{% extends "bootstrap/base.html" %} +{% block title %} {{ title }} {% endblock %} + +{% block content %} + {% if text %} +

{{ text }}

+ {% else %} +

Welcome!

+ {% endif %} +{% endblock %} diff --git a/app/templates/input.html b/app/templates/input.html new file mode 100644 index 0000000..41cb119 --- /dev/null +++ b/app/templates/input.html @@ -0,0 +1,6 @@ +{% import "bootstrap/wtf.html" as wtf %} +{% extends "index.html" %} + +{% block content %} + {{ wtf.quick_form(form) }} +{% endblock %} diff --git a/config.py b/config.py new file mode 100644 index 0000000..167d608 --- /dev/null +++ b/config.py @@ -0,0 +1,21 @@ +import os + +class DevelopmentConfig: + SECRET_KEY = os.environ.get('SECRET_KEY') or 'csrf key' + + POSTGRES_URL = os.environ.get("POSTGRES_URL") + POSTGRES_USER = os.environ.get("POSTGRES_USER") + POSTGRES_PW = os.environ.get("POSTGRES_PW") + POSTGRES_DB = os.environ.get("POSTGRES_DB") + + DB_URL = 'postgresql+psycopg2://{user}:{pw}@{url}/{db}'.format( + user=POSTGRES_USER,pw=POSTGRES_PW,url=POSTGRES_URL,db=POSTGRES_DB) + SQLALCHEMY_DATABASE_URI = DB_URL + SQLALCHEMY_TRACK_MODIFICATIONS = False + +class DeployConfig: + SECRET_KEY = os.environ.get('SECRET_KEY') or 'csrf key' + SQLALCHEMY_DATABASE_URI = os.environ.get("DATABASE_URL") + SQLALCHEMY_TRACK_MODIFICATIONS = False + + diff --git a/fastflask.py b/fastflask.py new file mode 100644 index 0000000..d099b92 --- /dev/null +++ b/fastflask.py @@ -0,0 +1 @@ +from app import app diff --git a/manage.py b/manage.py new file mode 100644 index 0000000..97c29c5 --- /dev/null +++ b/manage.py @@ -0,0 +1,12 @@ +from flask_script import Manager +from flask_migrate import Migrate, MigrateCommand + +from app import app, db + +migrate = Migrate(app, db) +manager = Manager(app) + +manager.add_command('db', MigrateCommand) + +if __name__ == '__main__': + manager.run() diff --git a/migrations/README b/migrations/README new file mode 100644 index 0000000..98e4f9c --- /dev/null +++ b/migrations/README @@ -0,0 +1 @@ +Generic single-database configuration. \ No newline at end of file diff --git a/migrations/__pycache__/env.cpython-36.pyc b/migrations/__pycache__/env.cpython-36.pyc new file mode 100644 index 0000000..39e08b8 Binary files /dev/null and b/migrations/__pycache__/env.cpython-36.pyc differ diff --git a/migrations/alembic.ini b/migrations/alembic.ini new file mode 100644 index 0000000..f8ed480 --- /dev/null +++ b/migrations/alembic.ini @@ -0,0 +1,45 @@ +# A generic, single database configuration. + +[alembic] +# template used to generate migration files +# file_template = %%(rev)s_%%(slug)s + +# set to 'true' to run the environment during +# the 'revision' command, regardless of autogenerate +# revision_environment = false + + +# Logging configuration +[loggers] +keys = root,sqlalchemy,alembic + +[handlers] +keys = console + +[formatters] +keys = generic + +[logger_root] +level = WARN +handlers = console +qualname = + +[logger_sqlalchemy] +level = WARN +handlers = +qualname = sqlalchemy.engine + +[logger_alembic] +level = INFO +handlers = +qualname = alembic + +[handler_console] +class = StreamHandler +args = (sys.stderr,) +level = NOTSET +formatter = generic + +[formatter_generic] +format = %(levelname)-5.5s [%(name)s] %(message)s +datefmt = %H:%M:%S diff --git a/migrations/env.py b/migrations/env.py new file mode 100644 index 0000000..9452179 --- /dev/null +++ b/migrations/env.py @@ -0,0 +1,96 @@ +from __future__ import with_statement + +import logging +from logging.config import fileConfig + +from sqlalchemy import engine_from_config +from sqlalchemy import pool + +from alembic import context + +# this is the Alembic Config object, which provides +# access to the values within the .ini file in use. +config = context.config + +# Interpret the config file for Python logging. +# This line sets up loggers basically. +fileConfig(config.config_file_name) +logger = logging.getLogger('alembic.env') + +# add your model's MetaData object here +# for 'autogenerate' support +# from myapp import mymodel +# target_metadata = mymodel.Base.metadata +from flask import current_app +config.set_main_option( + 'sqlalchemy.url', + str(current_app.extensions['migrate'].db.engine.url).replace('%', '%%')) +target_metadata = current_app.extensions['migrate'].db.metadata + +# other values from the config, defined by the needs of env.py, +# can be acquired: +# my_important_option = config.get_main_option("my_important_option") +# ... etc. + + +def run_migrations_offline(): + """Run migrations in 'offline' mode. + + This configures the context with just a URL + and not an Engine, though an Engine is acceptable + here as well. By skipping the Engine creation + we don't even need a DBAPI to be available. + + Calls to context.execute() here emit the given string to the + script output. + + """ + url = config.get_main_option("sqlalchemy.url") + context.configure( + url=url, target_metadata=target_metadata, literal_binds=True + ) + + with context.begin_transaction(): + context.run_migrations() + + +def run_migrations_online(): + """Run migrations in 'online' mode. + + In this scenario we need to create an Engine + and associate a connection with the context. + + """ + + # this callback is used to prevent an auto-migration from being generated + # when there are no changes to the schema + # reference: http://alembic.zzzcomputing.com/en/latest/cookbook.html + def process_revision_directives(context, revision, directives): + if getattr(config.cmd_opts, 'autogenerate', False): + script = directives[0] + if script.upgrade_ops.is_empty(): + directives[:] = [] + logger.info('No changes in schema detected.') + + connectable = engine_from_config( + config.get_section(config.config_ini_section), + prefix='sqlalchemy.', + poolclass=pool.NullPool, + ) + + with connectable.connect() as connection: + context.configure( + connection=connection, + target_metadata=target_metadata, + process_revision_directives=process_revision_directives, + **current_app.extensions['migrate'].configure_args + ) + + with context.begin_transaction(): + context.run_migrations() + + +if context.is_offline_mode(): + run_migrations_offline() +else: + run_migrations_online() diff --git a/migrations/script.py.mako b/migrations/script.py.mako new file mode 100644 index 0000000..2c01563 --- /dev/null +++ b/migrations/script.py.mako @@ -0,0 +1,24 @@ +"""${message} + +Revision ID: ${up_revision} +Revises: ${down_revision | comma,n} +Create Date: ${create_date} + +""" +from alembic import op +import sqlalchemy as sa +${imports if imports else ""} + +# revision identifiers, used by Alembic. +revision = ${repr(up_revision)} +down_revision = ${repr(down_revision)} +branch_labels = ${repr(branch_labels)} +depends_on = ${repr(depends_on)} + + +def upgrade(): + ${upgrades if upgrades else "pass"} + + +def downgrade(): + ${downgrades if downgrades else "pass"} diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..de13989 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,20 @@ +alembic==1.4.3 +click==7.1.2 +dominate==2.6.0 +Flask==1.1.2 +Flask-Bootstrap==3.3.7.1 +Flask-Migrate==2.5.3 +Flask-SQLAlchemy==2.4.4 +Flask-WTF==0.14.3 +itsdangerous==1.1.0 +Jinja2==2.11.2 +Mako==1.1.3 +MarkupSafe==1.1.1 +python-dateutil==2.8.1 +python-dotenv==0.15.0 +python-editor==1.0.4 +six==1.15.0 +SQLAlchemy==1.3.20 +visitor==0.1.3 +Werkzeug==1.0.1 +WTForms==2.3.3 diff --git a/schema.psql b/schema.psql new file mode 100644 index 0000000..09bae89 --- /dev/null +++ b/schema.psql @@ -0,0 +1,4 @@ +CREATE TABLE fastflask ( + text_id serial PRIMARY KEY, + text_value VARCHAR(255) UNIQUE NOT NULL +);