Skip to content

Forms #92

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
127 changes: 127 additions & 0 deletions Unit-01/07-sql-alchemy-2/users-messages-forms/app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
from flask import Flask, request, redirect, render_template, url_for
from flask_sqlalchemy import SQLAlchemy
from flask_modus import Modus
from forms import UserForm, MessageForm, DeleteForm
import os

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = "postgres://localhost/users-messages"
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SECRET KEY'] = os.environ.get('SECRET_KEY')
modus = Modus(app)
db = SQLAlchemy(app)

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")

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():
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'])
db.session.add(new_user)
db.session.commit()
return redirect(url_for('index'))
else:
return render_template('users/new.html', form=form)
return render_template('users/index.html', users=User.query.all(), delete_form=delete_form)

@app.route('/users/new')
def new():
user_form = UserForm()
return render_template('users/new.html', form=user_form)

@app.route('/users/<int:id>/edit')
def edit(id):
found_user = User.query.get(id)
user_form = UserForm(obj=found_user)
return render_template('users/edit.html', user=found_user, form=user_form)

@app.route('/users/<int:id>', 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()
return redirect(url_for('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()
return redirect(url_for('index'))
return render_template('users/show.html', user=found_user)

@app.route('/users/<int:user_id>/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/<int:user_id>/messages/new', methods=["GET", "POST"])
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This one doesn't need to have a methods=["GET", "POST"] - that was a mistake in the screencast :) - we just need "GET" here

def messages_new(user_id):
return render_template('messages/new.html', user=User.query.get(user_id))

@app.route('/users/<int:user_id>/messages/<int:id>/edit', methods=["GET", "POST"])
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same comment as above.

def messages_edit(user_id, id):
found_message = Message.query.get(id)
return render_template('messages/edit.html', message=found_message)


@app.route('/users/<int:user_id>/messages/<int:id>', 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))
if 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)



if __name__ == '__main__':
app.run(debug=True, port=3000)



12 changes: 12 additions & 0 deletions Unit-01/07-sql-alchemy-2/users-messages-forms/forms.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
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
12 changes: 12 additions & 0 deletions Unit-01/07-sql-alchemy-2/users-messages-forms/manage.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
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)

if __name__ == '__main__':
manager.run()
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Generic single-database configuration.
Original file line number Diff line number Diff line change
@@ -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
87 changes: 87 additions & 0 deletions Unit-01/07-sql-alchemy-2/users-messages-forms/migrations/env.py
Original file line number Diff line number Diff line change
@@ -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()
Original file line number Diff line number Diff line change
@@ -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"}
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
"""adding users table

Revision ID: 10ea5e18414a
Revises:
Create Date: 2017-11-30 14:09:26.373494

"""
from alembic import op
import sqlalchemy as sa


# revision identifiers, used by Alembic.
revision = '10ea5e18414a'
down_revision = None
branch_labels = None
depends_on = None


def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('users',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('first_name', sa.Text(), nullable=True),
sa.Column('last_name', sa.Text(), nullable=True),
sa.PrimaryKeyConstraint('id')
)
# ### end Alembic commands ###


def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table('users')
# ### end Alembic commands ###
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
"""adding messages table

Revision ID: bcb5d2e5decd
Revises: 10ea5e18414a
Create Date: 2017-11-30 18:07:25.906299

"""
from alembic import op
import sqlalchemy as sa


# revision identifiers, used by Alembic.
revision = 'bcb5d2e5decd'
down_revision = '10ea5e18414a'
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 ###
11 changes: 11 additions & 0 deletions Unit-01/07-sql-alchemy-2/users-messages-forms/templates/base.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
{% block content %}
{% endblock %}
</body>
</html>
Loading