diff --git a/Unit-01/07-sql-alchemy-2/app.py b/Unit-01/07-sql-alchemy-2/app.py new file mode 100644 index 0000000..4ee21af --- /dev/null +++ b/Unit-01/07-sql-alchemy-2/app.py @@ -0,0 +1,133 @@ +from flask import Flask, render_template, redirect, url_for, request +from flask_sqlalchemy import SQLAlchemy #step 1: pip install flask_sqlalchemy psycopg2 +from flask_modus import Modus + + + + +app = Flask(__name__) +#step 2: app.config to cofig to correct database +app.config['SQLALCHEMY_DATABASE_URI'] = "postgres://localhost/flask-user-app" +app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False +modus = Modus(app) +db = SQLAlchemy(app) + + +#set up our table +class User(db.Model): + + __tablename__ = "users" + + id = db.Column(db.Integer, primary_key=True) + first_name = db.Column(db.Text) + last_name = db.Column(db.Text) + messages = db.relationship('Message', backref= 'user', lazy='dynamic', cascade='all,delete') + + def __init__(self, first_name, last_name): + self.first_name = first_name + self.last_name = last_name + +class Message(db.Model): + + __tablename__ = "messages" + + id = db.Column(db.Integer, primary_key=True) + content = db.Column(db.Text) + user_id = db.Column(db.Integer, db.ForeignKey('users.id')) + + def __init__(self, content, user_id): + self.content = content + self.user_id = user_id + + + +@app.route('/') +def root(): + return redirect(url_for('index')) + +@app.route('/users', methods=["GET", "POST"]) +def index(): + if request.method == "POST": + new_user = User(request.form['first_name'], request.form['last_name']) # name from type in new.html# + db.session.add(new_user) + db.session.commit() + return redirect(url_for('index')) + return render_template('users/index.html', users=User.query.all()) + + + +@app.route('/users/new') +def new(): + return render_template('users/new.html') + +@app.route('/users/', methods=["GET", "PATCH", "DELETE"]) +def show(id): + found_user = User.query.get(id) + + if request.method == b"PATCH": + found_user.first_name = request.form['first_name'] + found_user.last_name = request.form['last_name'] + db.session.add(found_user) + db.session.commit() + return redirect(url_for('index')) + + + if request.method == b"DELETE": + db.session.delete(found_user) + db.session.commit() + return redirect(url_for('index')) + return render_template('users/show.html', user=found_user) + + + +@app.route('/users//edit') +def edit(id): + #refactored using a list comprehension + found_user = User.query.get(id) + return render_template('users/edit.html', user=found_user) + + + +@app.route('/users//messages', methods=["GET", "POST"]) +def messages_index(user_id): + if request.method == "POST": + new_message = Message(request.form['content'], user_id) + db.session.add(new_message) + db.session.commit() + return redirect(url_for('messages_index', user_id=user_id)) + return render_template('messages/index.html', user=User.query.get(user_id)) + +@app.route('/users//messages/new') +def messages_new(user_id): + return render_template('messages/new.html', user=User.query.get(user_id)) + +@app.route('/users//messages/', methods=['GET', 'PATCH', 'DELETE']) +def messages_show(user_id, id): + found_message = Message.query.get(id) + + if request.method == b'PATCH': + found_message.content = request.form['content'] + db.session.add(found_message) + db.session.commit() + return redirect(url_for('messages_index', user_id=user_id)) + + elif request.method == b'DELETE': + db.session.delete(found_message) + db.session.commit() + return redirect(url_for('messages_index', user_id=user_id)) + return render_template('messages/show.html', message=found_message) + +@app.route('/users//messages//edit') +def messages_edit(user_id, id): + found_message = Message.query.get(id) + user=User.query.get(user_id) + return render_template('messages/edit.html', message=found_message, user=user) + + + + + + + +if __name__ == '__main__': + app.run(debug=True, port=3000) diff --git a/Unit-01/07-sql-alchemy-2/manage.py b/Unit-01/07-sql-alchemy-2/manage.py new file mode 100644 index 0000000..c51dfa7 --- /dev/null +++ b/Unit-01/07-sql-alchemy-2/manage.py @@ -0,0 +1,13 @@ +from app import app, db +from flask_script import Manager +from flask_migrate import Migrate, MigrateCommand + +migrate = Migrate(app, db) + +manager = Manager(app) + + +manager.add_command('db', MigrateCommand) # python manage.py db + +if __name__ == '__main__': + manager.run() diff --git a/Unit-01/07-sql-alchemy-2/migrations/README b/Unit-01/07-sql-alchemy-2/migrations/README new file mode 100755 index 0000000..98e4f9c --- /dev/null +++ b/Unit-01/07-sql-alchemy-2/migrations/README @@ -0,0 +1 @@ +Generic single-database configuration. \ No newline at end of file diff --git a/Unit-01/07-sql-alchemy-2/migrations/alembic.ini b/Unit-01/07-sql-alchemy-2/migrations/alembic.ini new file mode 100644 index 0000000..f8ed480 --- /dev/null +++ b/Unit-01/07-sql-alchemy-2/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/Unit-01/07-sql-alchemy-2/migrations/env.py b/Unit-01/07-sql-alchemy-2/migrations/env.py new file mode 100755 index 0000000..23663ff --- /dev/null +++ b/Unit-01/07-sql-alchemy-2/migrations/env.py @@ -0,0 +1,87 @@ +from __future__ import with_statement +from alembic import context +from sqlalchemy import engine_from_config, pool +from logging.config import fileConfig +import logging + +# 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', + current_app.config.get('SQLALCHEMY_DATABASE_URI')) +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) + + 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.') + + engine = engine_from_config(config.get_section(config.config_ini_section), + prefix='sqlalchemy.', + poolclass=pool.NullPool) + + connection = engine.connect() + context.configure(connection=connection, + target_metadata=target_metadata, + process_revision_directives=process_revision_directives, + **current_app.extensions['migrate'].configure_args) + + try: + with context.begin_transaction(): + context.run_migrations() + finally: + connection.close() + +if context.is_offline_mode(): + run_migrations_offline() +else: + run_migrations_online() diff --git a/Unit-01/07-sql-alchemy-2/migrations/script.py.mako b/Unit-01/07-sql-alchemy-2/migrations/script.py.mako new file mode 100755 index 0000000..2c01563 --- /dev/null +++ b/Unit-01/07-sql-alchemy-2/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/Unit-01/07-sql-alchemy-2/migrations/versions/d133f7ee8b3c_.py b/Unit-01/07-sql-alchemy-2/migrations/versions/d133f7ee8b3c_.py new file mode 100644 index 0000000..3a1e8b8 --- /dev/null +++ b/Unit-01/07-sql-alchemy-2/migrations/versions/d133f7ee8b3c_.py @@ -0,0 +1,34 @@ +"""empty message + +Revision ID: d133f7ee8b3c +Revises: +Create Date: 2017-12-09 19:11:57.347109 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = 'd133f7ee8b3c' +down_revision = None +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.create_table('messages', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('content', sa.Text(), nullable=True), + sa.Column('user_id', sa.Integer(), nullable=True), + sa.ForeignKeyConstraint(['user_id'], ['users.id'], ), + sa.PrimaryKeyConstraint('id') + ) + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.drop_table('messages') + # ### end Alembic commands ### diff --git a/Unit-01/07-sql-alchemy-2/templates/base.html b/Unit-01/07-sql-alchemy-2/templates/base.html new file mode 100644 index 0000000..d658833 --- /dev/null +++ b/Unit-01/07-sql-alchemy-2/templates/base.html @@ -0,0 +1,19 @@ + + + + + + + Users CRUD App + + + +
+ + + Home + {% block content %} + {% endblock %} +
+ + diff --git a/Unit-01/07-sql-alchemy-2/templates/messages/edit.html b/Unit-01/07-sql-alchemy-2/templates/messages/edit.html new file mode 100644 index 0000000..e886aad --- /dev/null +++ b/Unit-01/07-sql-alchemy-2/templates/messages/edit.html @@ -0,0 +1,16 @@ +{% extends "base.html" %} +{% block content %} +

Edit Your Message

+ +
+ + + +
+ +
+ + +
+ +{% endblock %} diff --git a/Unit-01/07-sql-alchemy-2/templates/messages/index.html b/Unit-01/07-sql-alchemy-2/templates/messages/index.html new file mode 100644 index 0000000..d592c30 --- /dev/null +++ b/Unit-01/07-sql-alchemy-2/templates/messages/index.html @@ -0,0 +1,26 @@ +{% extends "base.html" %} +{% block content %} + +

Messages for {{user.first_name}}

+ + Add A New Message + + +

+ {% for message in user.messages %} + + + + {{message.content}} + + Edit your message + +

+ +
+ + + {% endfor %} +

+ +{% endblock %} diff --git a/Unit-01/07-sql-alchemy-2/templates/messages/new.html b/Unit-01/07-sql-alchemy-2/templates/messages/new.html new file mode 100644 index 0000000..b796c86 --- /dev/null +++ b/Unit-01/07-sql-alchemy-2/templates/messages/new.html @@ -0,0 +1,14 @@ +{% extends 'base.html' %} +{% block content %} + +

Add A Message For {{user.first_name}} {{user.last_name}}

+ +
+ + + + + +
+ + {% endblock %} diff --git a/Unit-01/07-sql-alchemy-2/templates/messages/show.html b/Unit-01/07-sql-alchemy-2/templates/messages/show.html new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/Unit-01/07-sql-alchemy-2/templates/messages/show.html @@ -0,0 +1 @@ + diff --git a/Unit-01/07-sql-alchemy-2/templates/users/edit.html b/Unit-01/07-sql-alchemy-2/templates/users/edit.html new file mode 100644 index 0000000..19d63cc --- /dev/null +++ b/Unit-01/07-sql-alchemy-2/templates/users/edit.html @@ -0,0 +1,15 @@ +{% extends "base.html" %} +{% block content %} + +
+ + + +
+ +
+ + +
+ +{% endblock %} diff --git a/Unit-01/07-sql-alchemy-2/templates/users/index.html b/Unit-01/07-sql-alchemy-2/templates/users/index.html new file mode 100644 index 0000000..5c162c1 --- /dev/null +++ b/Unit-01/07-sql-alchemy-2/templates/users/index.html @@ -0,0 +1,16 @@ +{% extends "base.html" %} +{% block content %} + +

Users App

+ + Add A New User + + + +{% endblock %} diff --git a/Unit-01/07-sql-alchemy-2/templates/users/new.html b/Unit-01/07-sql-alchemy-2/templates/users/new.html new file mode 100644 index 0000000..f6edcd2 --- /dev/null +++ b/Unit-01/07-sql-alchemy-2/templates/users/new.html @@ -0,0 +1,15 @@ +{% extends 'base.html' %} +{% block content %} + +

Add User

+ +
+ + + + + + +
+ + {% endblock %} diff --git a/Unit-01/07-sql-alchemy-2/templates/users/show.html b/Unit-01/07-sql-alchemy-2/templates/users/show.html new file mode 100644 index 0000000..13b77ad --- /dev/null +++ b/Unit-01/07-sql-alchemy-2/templates/users/show.html @@ -0,0 +1,15 @@ +{% extends "base.html" %} +{% block content %} + +

More About This User

+

+ The name of the user is {{user.first_name}} {{user.last_name}} +

+ + See all the users +
+ Edit this user +
+ See user's messages + +{% endblock %}