diff --git a/Unit-02/01-blueprints/app.py b/Unit-02/01-blueprints/app.py new file mode 100644 index 0000000..3d6fb59 --- /dev/null +++ b/Unit-02/01-blueprints/app.py @@ -0,0 +1,6 @@ +from project import app + + + +if __name__ == '__main__': + app.run(debug=True, port=9000) diff --git a/Unit-02/01-blueprints/manage.py b/Unit-02/01-blueprints/manage.py new file mode 100644 index 0000000..2f154d1 --- /dev/null +++ b/Unit-02/01-blueprints/manage.py @@ -0,0 +1,11 @@ +from project 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-02/01-blueprints/migrations/README b/Unit-02/01-blueprints/migrations/README new file mode 100755 index 0000000..98e4f9c --- /dev/null +++ b/Unit-02/01-blueprints/migrations/README @@ -0,0 +1 @@ +Generic single-database configuration. \ No newline at end of file diff --git a/Unit-02/01-blueprints/migrations/alembic.ini b/Unit-02/01-blueprints/migrations/alembic.ini new file mode 100644 index 0000000..f8ed480 --- /dev/null +++ b/Unit-02/01-blueprints/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-02/01-blueprints/migrations/env.py b/Unit-02/01-blueprints/migrations/env.py new file mode 100755 index 0000000..23663ff --- /dev/null +++ b/Unit-02/01-blueprints/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-02/01-blueprints/migrations/script.py.mako b/Unit-02/01-blueprints/migrations/script.py.mako new file mode 100755 index 0000000..2c01563 --- /dev/null +++ b/Unit-02/01-blueprints/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-02/01-blueprints/migrations/versions/d133f7ee8b3c_.py b/Unit-02/01-blueprints/migrations/versions/d133f7ee8b3c_.py new file mode 100644 index 0000000..3a1e8b8 --- /dev/null +++ b/Unit-02/01-blueprints/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-02/01-blueprints/project/__init__.py b/Unit-02/01-blueprints/project/__init__.py new file mode 100644 index 0000000..33097bb --- /dev/null +++ b/Unit-02/01-blueprints/project/__init__.py @@ -0,0 +1,27 @@ +from flask import Flask, redirect, url_for +from flask_sqlalchemy import SQLAlchemy #step 1: pip install flask_sqlalchemy psycopg2 +from flask_modus import Modus +import os + + + + +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 +app.config['SECRET_KEY'] = os.environ.get('SECRET_KEY') +modus = Modus(app) +db = SQLAlchemy(app) + +from project.users.views import users_blueprint +from project.messages.views import messages_blueprint + +app.register_blueprint(users_blueprint, url_prefix='/users') +app.register_blueprint(messages_blueprint, url_prefix='/users//messages') + + + +@app.route('/') +def root(): + return redirect(url_for('users.index')) diff --git a/Unit-02/01-blueprints/project/messages/forms.py b/Unit-02/01-blueprints/project/messages/forms.py new file mode 100644 index 0000000..b2c553d --- /dev/null +++ b/Unit-02/01-blueprints/project/messages/forms.py @@ -0,0 +1,14 @@ +from flask_wtf import FlaskForm +from wtforms import StringField, validators + +class UserForm(FlaskForm): + first_name = StringField('First Name', [validators.DataRequired()]) + last_name = StringField('Last Name', [validators.DataRequired()]) + + +class MessageForm(FlaskForm): + content = StringField('Content', [validators.DataRequired()]) + + +class DeleteForm(FlaskForm): + pass diff --git a/Unit-02/01-blueprints/project/messages/templates/messages/edit.html b/Unit-02/01-blueprints/project/messages/templates/messages/edit.html new file mode 100644 index 0000000..af91e0d --- /dev/null +++ b/Unit-02/01-blueprints/project/messages/templates/messages/edit.html @@ -0,0 +1,27 @@ +{% extends "base.html" %} +{% block content %} +

Edit Your Message

+ +
+ {{ form.hidden_tag() }} + {% for field in form if field.widget.input_type != 'hidden' %} + +

+ {{ field.label }} + {{ field }} + + {% if field.errors %} + {% for error in field.errors %} + {{ error }} + {% endfor %} + + {% endif %} + + +

+ {% endfor %} + + +
+ +{% endblock %} diff --git a/Unit-02/01-blueprints/project/messages/templates/messages/index.html b/Unit-02/01-blueprints/project/messages/templates/messages/index.html new file mode 100644 index 0000000..34af76e --- /dev/null +++ b/Unit-02/01-blueprints/project/messages/templates/messages/index.html @@ -0,0 +1,33 @@ +{% extends "base.html" %} +{% block content %} + +

Messages for {{user.first_name}}

+ + Add A New Message + + +

+ {% for message in user.messages %} +

+ + +
+
+ {{message.content}} + +

+ + + + +
{{ delete_form.hidden_tag()}} + + +
+ +

+ + {% endfor %} + + +{% endblock %} diff --git a/Unit-02/01-blueprints/project/messages/templates/messages/new.html b/Unit-02/01-blueprints/project/messages/templates/messages/new.html new file mode 100644 index 0000000..a1e064a --- /dev/null +++ b/Unit-02/01-blueprints/project/messages/templates/messages/new.html @@ -0,0 +1,28 @@ +{% extends 'base.html' %} +{% block content %} + +

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

+ +
+ {{ form.hidden_tag() }} + {% for field in form if field.widget.input_type != 'hidden' %} +

+ {{ field.label }} + {{ field }} + + {% if field.errors %} + {% for error in field.errors %} + {{ error }} + {% endfor %} + + {% endif %} + + + +

+ {% endfor %} + + +
+ + {% endblock %} diff --git a/Unit-02/01-blueprints/project/messages/templates/messages/show.html b/Unit-02/01-blueprints/project/messages/templates/messages/show.html new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/Unit-02/01-blueprints/project/messages/templates/messages/show.html @@ -0,0 +1 @@ + diff --git a/Unit-02/01-blueprints/project/messages/views.py b/Unit-02/01-blueprints/project/messages/views.py new file mode 100644 index 0000000..f35c357 --- /dev/null +++ b/Unit-02/01-blueprints/project/messages/views.py @@ -0,0 +1,59 @@ +from flask import redirect, render_template, request, url_for, flash, Blueprint +from project.models import Message, User +from project.messages.forms import MessageForm, DeleteForm +from project import db + +messages_blueprint = Blueprint( + 'messages', + __name__, + template_folder='templates' +) + +@messages_blueprint.route('/', methods=["GET", "POST"]) +def index(user_id): + delete_form = DeleteForm() + if request.method == "POST": + message_form = MessageForm(request.form) + if message_form.validate(): + new_message = Message(request.form['content'], user_id) + db.session.add(new_message) + db.session.commit() + flash('Message Created!') + return redirect(url_for('messages.index', user_id=user_id, form=message_form)) + else: + return render_template('messages/new.html', user=User.query.get(user_id), form=message_form) + return render_template('messages/index.html', user=User.query.get(user_id), delete_form=delete_form) + +@messages_blueprint.route('/new') +def new(user_id): + message_form = MessageForm(request.form) + return render_template('messages/new.html', user=User.query.get(user_id), form=message_form) + +@messages_blueprint.route('/', methods=['GET', 'PATCH', 'DELETE']) +def show(user_id, id): + found_message = Message.query.get(id) + + if request.method == b'PATCH': + message_form = MessageForm(request.form) + if message_form.validate(): + found_message.content = request.form['content'] + db.session.add(found_message) + db.session.commit() + flash('Message Updated!') + return redirect(url_for('users.index', user_id=user_id)) + return render_template('messages/edit.html', message=found_message, form=message_form) + + elif request.method == b'DELETE': + delete_form = DeleteForm(request.form) + if delete_form.validate(): + db.session.delete(found_message) + db.session.commit() + flash('Message Deleted!') + return redirect(url_for('messages.index', user_id=user_id)) + return render_template('messages/show.html', message=found_message, form=message_form) + +@messages_blueprint.route('//edit') +def edit(user_id, id): + found_message = Message.query.get(id) + message_form = MessageForm(obj=found_message) + return render_template('messages/edit.html', message=found_message, form=message_form) diff --git a/Unit-02/01-blueprints/project/models.py b/Unit-02/01-blueprints/project/models.py new file mode 100644 index 0000000..27a0d0b --- /dev/null +++ b/Unit-02/01-blueprints/project/models.py @@ -0,0 +1,27 @@ +from project import db + +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 diff --git a/Unit-02/01-blueprints/project/templates/base.html b/Unit-02/01-blueprints/project/templates/base.html new file mode 100644 index 0000000..dcd38e8 --- /dev/null +++ b/Unit-02/01-blueprints/project/templates/base.html @@ -0,0 +1,29 @@ + + + + + + + Users CRUD App + + + +
+ + + Home + {% with messages = get_flashed_messages()%} + {% if messages %} + {% for message in messages %} + +

{{ message }}

+ + {% endfor %} + {% endif %} + {% endwith %} + + {% block content %} + {% endblock %} +
+ + diff --git a/Unit-02/01-blueprints/project/users/forms.py b/Unit-02/01-blueprints/project/users/forms.py new file mode 100644 index 0000000..b2c553d --- /dev/null +++ b/Unit-02/01-blueprints/project/users/forms.py @@ -0,0 +1,14 @@ +from flask_wtf import FlaskForm +from wtforms import StringField, validators + +class UserForm(FlaskForm): + first_name = StringField('First Name', [validators.DataRequired()]) + last_name = StringField('Last Name', [validators.DataRequired()]) + + +class MessageForm(FlaskForm): + content = StringField('Content', [validators.DataRequired()]) + + +class DeleteForm(FlaskForm): + pass diff --git a/Unit-02/01-blueprints/project/users/templates/users/edit.html b/Unit-02/01-blueprints/project/users/templates/users/edit.html new file mode 100644 index 0000000..b4df761 --- /dev/null +++ b/Unit-02/01-blueprints/project/users/templates/users/edit.html @@ -0,0 +1,24 @@ +{% extends "base.html" %} +{% block content %} + +
+ {{ form.hidden_tag() }} + + {% for field in form if field.widget.input_type != 'hidden' %} +

+ {{ field.label }} + {{ field }} + + {% if field.errors %} + {% for error in field.errors %} + {{error}} + {% endfor %} + {% endif %} + +

+{% endfor %} + + +
+ +{% endblock %} diff --git a/Unit-02/01-blueprints/project/users/templates/users/index.html b/Unit-02/01-blueprints/project/users/templates/users/index.html new file mode 100644 index 0000000..7029401 --- /dev/null +++ b/Unit-02/01-blueprints/project/users/templates/users/index.html @@ -0,0 +1,28 @@ +{% extends "base.html" %} +{% block content %} + + + +

See All The Users!

+
+ Add A New User + + +{% endblock %} diff --git a/Unit-02/01-blueprints/project/users/templates/users/new.html b/Unit-02/01-blueprints/project/users/templates/users/new.html new file mode 100644 index 0000000..949eacd --- /dev/null +++ b/Unit-02/01-blueprints/project/users/templates/users/new.html @@ -0,0 +1,26 @@ +{% extends 'base.html' %} +{% block content %} + +

Add User

+ +
+ {{ form.hidden_tag() }} + + {% for field in form if field.widget.input_type != 'hidden' %} +

+ {{ field.label }} + {{ field }} + + {% if field.errors %} + {% for error in field.errors %} + {{error}} + {% endfor %} + {% endif %} + +

+ {% endfor %} + + +
+ + {% endblock %} diff --git a/Unit-02/01-blueprints/project/users/templates/users/show.html b/Unit-02/01-blueprints/project/users/templates/users/show.html new file mode 100644 index 0000000..8a60d07 --- /dev/null +++ b/Unit-02/01-blueprints/project/users/templates/users/show.html @@ -0,0 +1,21 @@ +{% 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 +
+

Delete User

+
+ +
+ + +{% endblock %} diff --git a/Unit-02/01-blueprints/project/users/views.py b/Unit-02/01-blueprints/project/users/views.py new file mode 100644 index 0000000..2c023ab --- /dev/null +++ b/Unit-02/01-blueprints/project/users/views.py @@ -0,0 +1,66 @@ +from flask import redirect, render_template, request, url_for, flash, Blueprint +from project.models import User +from project.users.forms import UserForm, DeleteForm +from project import db + +users_blueprint = Blueprint( + 'users', + __name__, + template_folder='templates' +) + +@users_blueprint.route('/', methods=["GET", "POST"]) +def index(): + delete_form = DeleteForm() + if request.method == "POST": + form = UserForm(request.form) + if form.validate(): + 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() + flash('User Created!') + return redirect(url_for('users.index')) + else: + return render_template('users/new.html', form=form) + return render_template('users/index.html', users=User.query.all(), delete_form=delete_form) + + + +@users_blueprint.route('/new') +def new(): + user_form = UserForm() + return render_template('users/new.html', form=user_form) + + + +@users_blueprint.route('/', methods=["GET", "PATCH", "DELETE"]) +def show(id): + found_user = User.query.get(id) + + if request.method == b"PATCH": + form = UserForm(request.form) + if form.validate(): + found_user.first_name = form.first_name.data + found_user.last_name = form.last_name.data + db.session.add(found_user) + db.session.commit() + flash('User Updated!') + return redirect(url_for('users.index')) + return render_template('users/edit.html', user=found_user, form=form) + + if request.method == b"DELETE": + delete_form = DeleteForm(request.form) + if delete_form.validate(): + db.session.delete(found_user) + db.session.commit() + flash('User Deleted!') + return redirect(url_for('users.index')) + return render_template('users/show.html', user=found_user) + + +@users_blueprint.route('//edit') +def edit(id): + #refactored using a list comprehension + found_user = User.query.get(id) + user_form = UserForm(obj=found_user) #do not use request.form, use obj= to prepopulate the form + return render_template('users/edit.html', user=found_user, form=user_form) diff --git a/Unit-02/01-blueprints/readme.md b/Unit-02/01-blueprints/readme.md index afe8a3c..aeebe73 100644 --- a/Unit-02/01-blueprints/readme.md +++ b/Unit-02/01-blueprints/readme.md @@ -1,11 +1,22 @@ -# Blueprints +# Blueprints ### Part I - Questions 1. Describe the MVC pattern. +#ANSWER: MVC stands for model, view, and controller. Models are responsible for data storage. +#Views is what our user sees and a minimal amout of logic for our controller is at. +#Controller is where all of our logic is at. The controller is responsible for updating the view by communicating to the model. + 2. In the MVC pattern, does the model communicate directly with the view? +#ANSWER: no, it goes through the controller and the controller is where the actions are processed to update the View from retrieving data from the model + 2. What is the purpose of blueprints? +#ANSWER: the purpose of blueprints is to organize our configuration settings, database logic and routing logic in a more structured folder system rather than storing it all in a single file (app.py) + + 3. How does using blueprints help us organize bigger applications? +#ANSWER: it reduces the amount of code in the app.py file by making the folder structure larger and a little more specific. + ### Part II - Exercise