From f036d6d8ac29a493d9f9d96c1664ab50d19b14bf Mon Sep 17 00:00:00 2001 From: joyce Date: Fri, 4 Dec 2020 20:41:39 +0800 Subject: [PATCH] initial commit --- Procfile | 1 + README.md | 43 +++++++++- __pycache__/config.cpython-36.pyc | Bin 0 -> 887 bytes __pycache__/fastflask.cpython-36.pyc | Bin 0 -> 144 bytes app/__init__.py | 17 ++++ app/__pycache__/__init__.cpython-36.pyc | Bin 0 -> 560 bytes app/__pycache__/forms.cpython-36.pyc | Bin 0 -> 533 bytes app/__pycache__/models.cpython-36.pyc | Bin 0 -> 840 bytes app/__pycache__/routes.cpython-36.pyc | Bin 0 -> 1165 bytes app/forms.py | 7 ++ app/models.py | 19 +++++ app/routes.py | 31 +++++++ app/templates/index.html | 10 +++ app/templates/input.html | 6 ++ config.py | 21 +++++ fastflask.py | 1 + manage.py | 12 +++ migrations/README | 1 + migrations/__pycache__/env.cpython-36.pyc | Bin 0 -> 2260 bytes migrations/alembic.ini | 45 ++++++++++ migrations/env.py | 96 ++++++++++++++++++++++ migrations/script.py.mako | 24 ++++++ requirements.txt | 20 +++++ schema.psql | 4 + 24 files changed, 357 insertions(+), 1 deletion(-) create mode 100644 Procfile create mode 100644 __pycache__/config.cpython-36.pyc create mode 100644 __pycache__/fastflask.cpython-36.pyc create mode 100644 app/__init__.py create mode 100644 app/__pycache__/__init__.cpython-36.pyc create mode 100644 app/__pycache__/forms.cpython-36.pyc create mode 100644 app/__pycache__/models.cpython-36.pyc create mode 100644 app/__pycache__/routes.cpython-36.pyc create mode 100644 app/forms.py create mode 100644 app/models.py create mode 100644 app/routes.py create mode 100644 app/templates/index.html create mode 100644 app/templates/input.html create mode 100644 config.py create mode 100644 fastflask.py create mode 100644 manage.py create mode 100644 migrations/README create mode 100644 migrations/__pycache__/env.cpython-36.pyc create mode 100644 migrations/alembic.ini create mode 100644 migrations/env.py create mode 100644 migrations/script.py.mako create mode 100644 requirements.txt create mode 100644 schema.psql 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 0000000000000000000000000000000000000000..6c87a64bc0f2a993da090a71714b932c67315f99 GIT binary patch literal 887 zcma))&2HL25XX0I0|pF9`jOnK9E(b0sl7#2#g~(!5J)jq6<=0_U1*5G&KeRC#ED+} zAbpPB`UrdNsjtveXADiK)I)9UPygBRtam}@@jLsb5%PmL&u74(6Uuqr&%isyH5@2bZx}=c&315?D5BcXwf+)d?`T#*Z%8925eP|35oGxj& z%QY{#w)G|TQfqC1HrF}5Z@W`!xzA|*21{9<^Pu)G{kdwHILdt}v4P231S z2uET(sRrZz_fYuau1g4v{m-rJo~s| z)GBwyFo-4tDWYrtMHtO`K{$AIXxsB?B;?|79^NiW^QrU~_MBfV3WhS!p|tQ;>9DOd zesR<+Y$=nmad#vbQyIoa0iXJ)Eyk{=U4QM-f=H#r_~uduW2FzoL}GKKfk+^*!ZHO= z$$lV5-HDg1RpNB^-1m)gqx#M{J!iFYr(7w!4mj%S*@mOjE>}<3X{%O0s#nXMdaLPv zCGsgAiuko}e+ovz9tN|Xu>0L;^0M!Dqbs`?m-Qf=Nf;i2cZwbXOuDUEG=4RM=BYtr z|6enK0VND50{&+vxZ#;RffJ^znh5=1wrXlziid7`)<%{MsBl_Z@CTVgPZ0M>uhcH??Ex?#!ZJg0kXpP~&{v0HF7d{{qLuk()z!BYkHDUpT0Zw10uju+ literal 0 HcmV?d00001 diff --git a/__pycache__/fastflask.cpython-36.pyc b/__pycache__/fastflask.cpython-36.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cc32c76efb305655b93db0eaa6b23147cff6e728 GIT binary patch literal 144 zcmXr!<>flWbShqifq~&M5W@izkmUfx#R5Pgg&~D8has0Cih+?Kg(;Xplldi3ltGj6 z7IR`jfuAO05lHz;h9YJl1txwe>u2QWrs`+qS0<~Gf#P#VHf5!-YqrF1_U&FHuOo>V?k-`jPkBKBIU_pZe*-;@2 z8{CnR>awn)jDjDQ(FbBZ(c2*wi%`Tn%=*yXm9a`#0u^+M(%uj7qZHTSoy_eMfZnav z&N`D<;Kb91`x{v-gxaK}J{pTxA$6t1+Ku#jzI?2cv8bfpv|i!4{DEnZpI`*f9)oen z;T?WMj%?8mrr4rYuB zs!wG4;QgLt3#~-9(wjnL^W3_#xgRKll8p1^dg(YnuQqjD7?C@{As#`WrC<=In39B; z0bt;bjDB&#PSQagHY|-YcGzG(``=F^kPX|YeU^Eb z0u$E>FH63<&vVYTkH+IsGI^s8M(7>=I}Z3KaO)WujyTSd!~|pGTe&4|VoQg>7{qq& zN{@ILT_Emo_Ze|l;H^yt+?%6t@Bs)Y#O*N2S$&t3N`_XuGuJ9BmPsaZ4ncDxGu;Ky z7@RT9uEn~^l;8_9{d0a*9Y97Pf;l3VusIga7A-NiUM%7YkK0=e><+NI?eMaw8f|Ew zCg+6~YO2Mfp00!vQ4|5)=$_>nXS!518Jw0ynkjh|`mIlC!K9$H9Z@Pv-sHv)C|x%! z?<>j%9m)mMItEo4fvs0}>%1a0Hf3Wz_v2M5MSNRs79vhrtq)W48ZoP?I0bEWRBe<8 zod&EnFh1VHT?Vv}Vb@I`bgC?4^lgW1~`dg<{)?xf9>AhV8;?Mf6j^XoB KZO8-Q46HBD1A>+S literal 0 HcmV?d00001 diff --git a/app/__pycache__/models.cpython-36.pyc b/app/__pycache__/models.cpython-36.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6b20dfdda9a12f0ffdfb8dfa499f99608a98a28e GIT binary patch literal 840 zcmaJ;y>8nu5GJV~%d+KW>fWM@hQ>qJq6iS6MTdAvCM|^Gqf@q z&{yaqaP5>==+fR%ao}|50r%aVj=JxD-ep<(+)QyxxfqwS<+)vn<8xamPwo$3HS`_r7d#Euchu3 z77DG>3m5tDo|zH;@cYg5%c@q>x>3C+-2r?1}|hueN!;(yv6NR`sUI_$lr7z* z4-GZu;^UR>>c$N|H?6u*rWp8BRN&&%)>O@fN${DWSi_@% literal 0 HcmV?d00001 diff --git a/app/__pycache__/routes.cpython-36.pyc b/app/__pycache__/routes.cpython-36.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5856c82da8824f6c87d94e66cfb20179b3a0977c GIT binary patch literal 1165 zcmZ8fOKuZE5bf^yk3R_p#AgFSY-T|Qi7i41#BUQKlGSWRwyW*TWZGkT+99@_m07Uy z2{-{~;07F_x2(8AR#bNq%gRX8s;d6fd#~P$PAC5P=uiIJA>=RF`do}(Wpce0{c+g3t| zARaSltr@hTV|O}srwh@T+WHRc+Ikmm9g?K?57Cgs)jN_;fXiHQF|GQF>riqiBp)gr z%w(01YN-Rszs`805~iL0bgCH)5~`z5lj%&oucg4mJ>qBTf~G_B?Dc1;zs0|4XLlfvTMk?~b&4@cHlvdj*24;~JU`Vv0vS z{4L_=7$~wL=VVDrx+3z4V#)!EnOl0m)@(%&iSoe#cS*ooJIKo4*TGcQL*6t-5`~f& zn%LUX)Sgu=VX}pq*|s2BJ{X!3}9Nl(+49-0oXtP@ub} zypczC%mHMNtzrzV;Dq@!q<5%G8I||2x(L%NbQ{j5#fI|%CJNaCeSo|bE1lACV{2M^ zs03Y7ASa=Gqu3Iycg~bw24%QJB`7L^akL^B#Wysu=o6a7MvokM&iMB57hS8$<1c*3 zi&G9)@?73(NrO(ieK~GqWI_*}DCasF6_rBU4shtBLN-bUW;bY1`=XwpPXV+)tc4NM zcp-7LXM1N|epWQ9n2d8iQF5NOC;VFugUjrOrm}}ujrxrV2#Z+{H4SN-#?0z!%KOO< zf-rWpownv?z)NFCi!O`Mt$Swb&E?QzlZzU7bxqD%*_zf)%(mZxWCw0%9lpeSvx>hm RuC?R7Pj?YkoAum>(SKD_4wV1^ literal 0 HcmV?d00001 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 0000000000000000000000000000000000000000..39e08b848c54a4907a671630f618ae7d6b17bc79 GIT binary patch literal 2260 zcmaJ?PjB2r6rZuZw%5DaP0~M*6cr0K3X9NkK&nJlRnU}5m8z(;MWDS{6VL3%u01w0 z%ja=Xz~x}D5AJPC7xhx=1$>E92nigExn0nWnR%K{fTeq9he7`z|Q?5EW48~ zMy#7hlZbgN%6kjY!<@WNg9VN`BmDZ z{e`n|;LK|8y~+D@jSgO-$rc^bbr`qdoofpuerH%sF( z9VSu{#Y)E2K8T`eRwjCLwlZZ8uJPyJpS6E z^C?`Zn%Ut>5`#vPrmR-vpkVgaArmYnGJejAVjRbJk7M~PtLu!s5>HAVP05zvPX&n?61zuAF~%MZ4~=>6x-)n znJN3)EHfIV688DZ$n1+U6{d*zLbmFM)38I}}T?L6veMs51Cs(^5K&5qH8`)sw4{bgQumq~stIMVk~+*}!pd45Yrm*wGbXf`@o6>kTE2yX z9c9wcDx#S%-XAfk{g(8WQEhk0JaMfSRm!AH&MqaZJNFC{mQ8qoLmc5gp5J<#cs6L` z+eMX#g4)wyo0WhIKdipRr(65_R{RDPL zALuAarj3Fkog~5mkq%6lp@vNc%gMMkQW);)Xa#Evkaay+{;OJtEuGevFqvOp!b!<= z7f^g?DI|<(x-*3^JZnK2N>lV!#Z0?UNX4!>=FkJ}x4%qVsB|D$U67RN@T^L<=$hJN zz0yPA?6OED=BIQ4Gz*_4V|W|3nu6Ui*&pLOtJAKnU--~eM_o1#i_&Oeh;g#@4 Hh(qTe9hrFz literal 0 HcmV?d00001 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 +);