From 1ac0022ec58cfe6ced69f9ec302d7e2ac332f2e0 Mon Sep 17 00:00:00 2001 From: ayaka Date: Fri, 15 Oct 2021 11:15:09 -0700 Subject: [PATCH 01/11] create class Planet and list of instances --- app/routes.py | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/app/routes.py b/app/routes.py index 8e9dfe684..62960d328 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,2 +1,20 @@ from flask import Blueprint + +class Planet: + def __init__(self, id, name, description, has_moons=True): + self.id = id + self.name = name + self.description = description + self.has_moons = has_moons + +planets = [ + Planet(1, "Earth", "Has Humans"), + Planet(2, "Mars", "No Humans"), + Planet(3, "Neptune", "No Humans"), + Planet(4, "Saturn", "No Humans"), + Planet(5, "Venus", "No Humans"), + Planet(6, "Uranus", "No Humans"), + Planet(7, "Mercury", "No Humans"), + Planet(8, "Jupiter", "No Humans"), +] \ No newline at end of file From 119792e33382969d57214114ff8436566e643291 Mon Sep 17 00:00:00 2001 From: ayaka Date: Mon, 18 Oct 2021 13:28:38 -0700 Subject: [PATCH 02/11] create routes --- app/__init__.py | 2 ++ app/routes.py | 35 +++++++++++++++++++++++++++++++++-- 2 files changed, 35 insertions(+), 2 deletions(-) diff --git a/app/__init__.py b/app/__init__.py index 70b4cabfe..3675c9309 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -4,4 +4,6 @@ def create_app(test_config=None): app = Flask(__name__) + from .routes import planets_bp + app.register_blueprint(planets_bp) return app diff --git a/app/routes.py b/app/routes.py index 62960d328..2e26b5dde 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,4 +1,4 @@ -from flask import Blueprint +from flask import Blueprint, jsonify class Planet: @@ -17,4 +17,35 @@ def __init__(self, id, name, description, has_moons=True): Planet(6, "Uranus", "No Humans"), Planet(7, "Mercury", "No Humans"), Planet(8, "Jupiter", "No Humans"), -] \ No newline at end of file +] + +planets_bp = Blueprint("planets", __name__, url_prefix="/planets") + +@planets_bp.route("", methods=["GET"]) +def handle_planets(): + #describe response for displaying all planets + planets_response = [] + for planet in planets: + planets_response.append( + { + "id": planet.id, + "name": planet.name, + "description": planet.description, + "has_moons": planet.has_moons + } + ) + return jsonify(planets_response) + +@planets_bp.route("/", methods=["GET"]) +def handle_planet(planet_id): + planet_id = int(planet_id) + planet_response = jsonify("id not valid") + for planet in planets: + if planet.id == planet_id: + planet_response = { + "id": planet.id, + "name": planet.name, + "description": planet.description, + "has_moons": planet.has_moons + } + return planet_response \ No newline at end of file From 945b2686126fe75d746231d793d0566e99ed71a6 Mon Sep 17 00:00:00 2001 From: ayaka Date: Fri, 22 Oct 2021 10:54:01 -0700 Subject: [PATCH 03/11] add Planet model --- app/__init__.py | 16 ++++++++ app/models/__init__.py | 0 app/models/planet.py | 10 +++++ app/routes.py | 89 +++++++++++++++++++++--------------------- 4 files changed, 71 insertions(+), 44 deletions(-) create mode 100644 app/models/__init__.py create mode 100644 app/models/planet.py diff --git a/app/__init__.py b/app/__init__.py index 3675c9309..7b0afa696 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -1,9 +1,25 @@ from flask import Flask +from flask_sqlalchemy import SQLAlchemy +from flask_migrate import Migrate +db = SQLAlchemy() +migrate = Migrate() def create_app(test_config=None): app = Flask(__name__) + app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False + app.config['SQLALCHEMY_DATABASE_URI'] = "postgresql+psycopg2://postgres:postgres@localhost:5432/solar_system_development" + + + db.init_app(app) + migrate.init_app(app, db) + from app.models.planet import Planet + + db.init_app(app) + migrate.init_app(app, db) + from .routes import planets_bp app.register_blueprint(planets_bp) + return app diff --git a/app/models/__init__.py b/app/models/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/app/models/planet.py b/app/models/planet.py new file mode 100644 index 000000000..9ecf2099c --- /dev/null +++ b/app/models/planet.py @@ -0,0 +1,10 @@ +from app import db + +class Planet(db.Model): + id = db.Column(db.Integer, primary_key=True, autoincrement=True) + name= db.Column(db.String) + description = db.Column(db.String) + has_moons = db.Column(db.Boolean) + + def to_string(self): + return f"{self.id}: {self.name} Description: {self.description}" \ No newline at end of file diff --git a/app/routes.py b/app/routes.py index 2e26b5dde..3fca81268 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,51 +1,52 @@ -from flask import Blueprint, jsonify +from app.models.book import Book +from flask import Blueprint, jsonify, make_response, request -class Planet: - def __init__(self, id, name, description, has_moons=True): - self.id = id - self.name = name - self.description = description - self.has_moons = has_moons +# class Planet: +# def __init__(self, id, name, description, has_moons=True): +# self.id = id +# self.name = name +# self.description = description +# self.has_moons = has_moons -planets = [ - Planet(1, "Earth", "Has Humans"), - Planet(2, "Mars", "No Humans"), - Planet(3, "Neptune", "No Humans"), - Planet(4, "Saturn", "No Humans"), - Planet(5, "Venus", "No Humans"), - Planet(6, "Uranus", "No Humans"), - Planet(7, "Mercury", "No Humans"), - Planet(8, "Jupiter", "No Humans"), -] +# planets = [ +# Planet(1, "Earth", "Has Humans"), +# Planet(2, "Mars", "No Humans"), +# Planet(3, "Neptune", "No Humans"), +# Planet(4, "Saturn", "No Humans"), +# Planet(5, "Venus", "No Humans"), +# Planet(6, "Uranus", "No Humans"), +# Planet(7, "Mercury", "No Humans"), +# Planet(8, "Jupiter", "No Humans"), +# ] planets_bp = Blueprint("planets", __name__, url_prefix="/planets") -@planets_bp.route("", methods=["GET"]) -def handle_planets(): - #describe response for displaying all planets - planets_response = [] - for planet in planets: - planets_response.append( - { - "id": planet.id, - "name": planet.name, - "description": planet.description, - "has_moons": planet.has_moons - } - ) - return jsonify(planets_response) +# @planets_bp.route("", methods=["GET"]) +# def handle_planets(): +# #describe response for displaying all planets +# planets_response = [] +# for planet in planets: +# planets_response.append( +# { +# "id": planet.id, +# "name": planet.name, +# "description": planet.description, +# "has_moons": planet.has_moons +# } +# ) +# return jsonify(planets_response) -@planets_bp.route("/", methods=["GET"]) -def handle_planet(planet_id): - planet_id = int(planet_id) - planet_response = jsonify("id not valid") - for planet in planets: - if planet.id == planet_id: - planet_response = { - "id": planet.id, - "name": planet.name, - "description": planet.description, - "has_moons": planet.has_moons - } - return planet_response \ No newline at end of file +# @planets_bp.route("/", methods=["GET"]) +# def handle_planet(planet_id): +# planet_id = int(planet_id) +# planet_response = jsonify("id not valid") +# for planet in planets: +# if planet.id == planet_id: +# planet_response = { +# "id": planet.id, +# "name": planet.name, +# "description": planet.description, +# "has_moons": planet.has_moons +# } +# return planet_response \ No newline at end of file From ebb68cc677a42ddf2fa65d12faaa54765fae5f5e Mon Sep 17 00:00:00 2001 From: ayaka Date: Fri, 22 Oct 2021 10:55:55 -0700 Subject: [PATCH 04/11] fix import --- app/routes.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/routes.py b/app/routes.py index 3fca81268..394fcf2db 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,4 +1,4 @@ -from app.models.book import Book +from app.models.planet import Planet from flask import Blueprint, jsonify, make_response, request From 27ad08f07dd1169058aeb7cf9765a92c3a0546e6 Mon Sep 17 00:00:00 2001 From: ayaka Date: Mon, 25 Oct 2021 14:48:44 -0700 Subject: [PATCH 05/11] add methods to /planets and /planets/ --- app/models/planet.py | 9 +- app/routes.py | 95 +++++++++--------- migrations/README | 1 + migrations/alembic.ini | 45 +++++++++ migrations/env.py | 96 +++++++++++++++++++ migrations/script.py.mako | 24 +++++ .../versions/8d90ba2cc7d3_add_planet_model.py | 34 +++++++ 7 files changed, 256 insertions(+), 48 deletions(-) create mode 100644 migrations/README create mode 100644 migrations/alembic.ini create mode 100644 migrations/env.py create mode 100644 migrations/script.py.mako create mode 100644 migrations/versions/8d90ba2cc7d3_add_planet_model.py diff --git a/app/models/planet.py b/app/models/planet.py index 9ecf2099c..56b01ae18 100644 --- a/app/models/planet.py +++ b/app/models/planet.py @@ -6,5 +6,10 @@ class Planet(db.Model): description = db.Column(db.String) has_moons = db.Column(db.Boolean) - def to_string(self): - return f"{self.id}: {self.name} Description: {self.description}" \ No newline at end of file + def to_json(self): + return { + "id": self.id, + "name": self.name, + "description": self.description, + "has_moons": self.has_moons + } \ No newline at end of file diff --git a/app/routes.py b/app/routes.py index 394fcf2db..bb10a8ce7 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,52 +1,55 @@ from app.models.planet import Planet from flask import Blueprint, jsonify, make_response, request +from app import db -# class Planet: -# def __init__(self, id, name, description, has_moons=True): -# self.id = id -# self.name = name -# self.description = description -# self.has_moons = has_moons - -# planets = [ -# Planet(1, "Earth", "Has Humans"), -# Planet(2, "Mars", "No Humans"), -# Planet(3, "Neptune", "No Humans"), -# Planet(4, "Saturn", "No Humans"), -# Planet(5, "Venus", "No Humans"), -# Planet(6, "Uranus", "No Humans"), -# Planet(7, "Mercury", "No Humans"), -# Planet(8, "Jupiter", "No Humans"), -# ] - planets_bp = Blueprint("planets", __name__, url_prefix="/planets") -# @planets_bp.route("", methods=["GET"]) -# def handle_planets(): -# #describe response for displaying all planets -# planets_response = [] -# for planet in planets: -# planets_response.append( -# { -# "id": planet.id, -# "name": planet.name, -# "description": planet.description, -# "has_moons": planet.has_moons -# } -# ) -# return jsonify(planets_response) - -# @planets_bp.route("/", methods=["GET"]) -# def handle_planet(planet_id): -# planet_id = int(planet_id) -# planet_response = jsonify("id not valid") -# for planet in planets: -# if planet.id == planet_id: -# planet_response = { -# "id": planet.id, -# "name": planet.name, -# "description": planet.description, -# "has_moons": planet.has_moons -# } -# return planet_response \ No newline at end of file +@planets_bp.route("", methods=["GET", "POST"]) +def handle_planets(): + + if request.method == "GET": + planets = Planet.query.all() + planets_response = [planet.to_json() for planet in planets] + + return jsonify(planets_response), 200 + + elif request.method == "POST": + request_body = request.get_json() + if "name" not in request_body or "description" not in request_body: + return jsonify("Invalid Request"), 400 + + new_planet = Planet( + name = request_body["name"], + description = request_body["description"], + has_moons = request_body["has_moons"] + ) + + db.session.add(new_planet) + db.session.commit() + + return jsonify(f"created {new_planet.name}"), 201 + +@planets_bp.route("/", methods=["GET", "PUT", "DELETE"]) +def handle_planet(planet_id): + planet = Planet.query.get(planet_id) + if planet is None: + return make_response("", 404) + if request.method == "DELETE": + db.session.delete(planet) + db.session.commit() + return make_response(f"Planet #{planet.id} successfully deleted.", 200) + elif request.method == "GET": + return planet.to_json(), 200 + + elif request.method == "PUT": + form_data = request.get_json() + + planet.name = form_data["name"] + planet.description = form_data["description"] + planet.has_moons = form_data["has_moons"] + + db.session.commit() + + return make_response(f"planet #{planet.id} successfully updated.", 200) + \ No newline at end of file diff --git a/migrations/README b/migrations/README new file mode 100644 index 000000000..98e4f9c44 --- /dev/null +++ b/migrations/README @@ -0,0 +1 @@ +Generic single-database configuration. \ No newline at end of file diff --git a/migrations/alembic.ini b/migrations/alembic.ini new file mode 100644 index 000000000..f8ed4801f --- /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 000000000..8b3fb3353 --- /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 flask import current_app + +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 +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 000000000..2c0156303 --- /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/migrations/versions/8d90ba2cc7d3_add_planet_model.py b/migrations/versions/8d90ba2cc7d3_add_planet_model.py new file mode 100644 index 000000000..84589116a --- /dev/null +++ b/migrations/versions/8d90ba2cc7d3_add_planet_model.py @@ -0,0 +1,34 @@ +"""add Planet model + +Revision ID: 8d90ba2cc7d3 +Revises: +Create Date: 2021-10-22 11:43:16.374084 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = '8d90ba2cc7d3' +down_revision = None +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.create_table('planet', + sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), + sa.Column('name', sa.String(), nullable=True), + sa.Column('description', sa.String(), nullable=True), + sa.Column('has_moons', sa.Boolean(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.drop_table('planet') + # ### end Alembic commands ### From c0ff7efb8bd8e8bf3ce5741199eda57ab74dda0e Mon Sep 17 00:00:00 2001 From: Rhyannon Date: Tue, 26 Oct 2021 11:38:59 -0600 Subject: [PATCH 06/11] confusing merge --- app/routes.py | 3 +- migrations/README | 1 + migrations/alembic.ini | 45 +++++++++ migrations/env.py | 96 +++++++++++++++++++ migrations/script.py.mako | 24 +++++ .../d4244cbb0171_adds_planet_model.py | 34 +++++++ 6 files changed, 201 insertions(+), 2 deletions(-) create mode 100644 migrations/README create mode 100644 migrations/alembic.ini create mode 100644 migrations/env.py create mode 100644 migrations/script.py.mako create mode 100644 migrations/versions/d4244cbb0171_adds_planet_model.py diff --git a/app/routes.py b/app/routes.py index 394fcf2db..592fdbea9 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,6 +1,7 @@ from app.models.planet import Planet from flask import Blueprint, jsonify, make_response, request +planets_bp = Blueprint("planets", __name__, url_prefix="/planets") # class Planet: # def __init__(self, id, name, description, has_moons=True): @@ -20,8 +21,6 @@ # Planet(8, "Jupiter", "No Humans"), # ] -planets_bp = Blueprint("planets", __name__, url_prefix="/planets") - # @planets_bp.route("", methods=["GET"]) # def handle_planets(): # #describe response for displaying all planets diff --git a/migrations/README b/migrations/README new file mode 100644 index 000000000..98e4f9c44 --- /dev/null +++ b/migrations/README @@ -0,0 +1 @@ +Generic single-database configuration. \ No newline at end of file diff --git a/migrations/alembic.ini b/migrations/alembic.ini new file mode 100644 index 000000000..f8ed4801f --- /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 000000000..8b3fb3353 --- /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 flask import current_app + +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 +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 000000000..2c0156303 --- /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/migrations/versions/d4244cbb0171_adds_planet_model.py b/migrations/versions/d4244cbb0171_adds_planet_model.py new file mode 100644 index 000000000..6ca918e89 --- /dev/null +++ b/migrations/versions/d4244cbb0171_adds_planet_model.py @@ -0,0 +1,34 @@ +"""adds Planet model + +Revision ID: d4244cbb0171 +Revises: +Create Date: 2021-10-22 12:43:57.773211 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = 'd4244cbb0171' +down_revision = None +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.create_table('planet', + sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), + sa.Column('name', sa.String(), nullable=True), + sa.Column('description', sa.String(), nullable=True), + sa.Column('has_moons', sa.Boolean(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.drop_table('planet') + # ### end Alembic commands ### From 131fbd388de8133cbacab2e04315c49109f9dee3 Mon Sep 17 00:00:00 2001 From: ayaka Date: Tue, 26 Oct 2021 11:03:45 -0700 Subject: [PATCH 07/11] experiement query like still in progress --- app/routes.py | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/app/routes.py b/app/routes.py index bb10a8ce7..5974dd35c 100644 --- a/app/routes.py +++ b/app/routes.py @@ -9,7 +9,13 @@ def handle_planets(): if request.method == "GET": - planets = Planet.query.all() + name_query = request.args.get("name") + if name_query: + # planets = Planet.query.filter_by(name=name_query) + planets = Planet.query.filter(name_query.like(name_query)) + else: + planets = Planet.query.all() + planets_response = [planet.to_json() for planet in planets] return jsonify(planets_response), 200 @@ -35,10 +41,12 @@ def handle_planet(planet_id): planet = Planet.query.get(planet_id) if planet is None: return make_response("", 404) + if request.method == "DELETE": db.session.delete(planet) db.session.commit() return make_response(f"Planet #{planet.id} successfully deleted.", 200) + elif request.method == "GET": return planet.to_json(), 200 From 054e2bb7f396044c236dd5a1e7c0a2bfdda9f883 Mon Sep 17 00:00:00 2001 From: ayaka Date: Wed, 27 Oct 2021 11:12:47 -0700 Subject: [PATCH 08/11] add tests --- app/__init__.py | 17 +++++++++++------ app/routes.py | 3 +-- tests/__init__.py | 0 tests/conftest.py | 37 +++++++++++++++++++++++++++++++++++++ tests/test_routes.py | 39 +++++++++++++++++++++++++++++++++++++++ 5 files changed, 88 insertions(+), 8 deletions(-) create mode 100644 tests/__init__.py create mode 100644 tests/conftest.py create mode 100644 tests/test_routes.py diff --git a/app/__init__.py b/app/__init__.py index 7b0afa696..bcfee766f 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -1,24 +1,29 @@ from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate +from dotenv import load_dotenv +import os db = SQLAlchemy() migrate = Migrate() +load_dotenv() def create_app(test_config=None): app = Flask(__name__) - app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False - app.config['SQLALCHEMY_DATABASE_URI'] = "postgresql+psycopg2://postgres:postgres@localhost:5432/solar_system_development" - + if not test_config: + app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False + app.config['SQLALCHEMY_DATABASE_URI'] = "postgresql+psycopg2://postgres:postgres@localhost:5432/solar_system_development" + else: + app.config["TESTING"] = True + app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False + app.config["SQLALCHEMY_DATABASE_URI"] = os.environ.get( + "SQLALCHEMY_TEST_DATABASE_URI") db.init_app(app) migrate.init_app(app, db) from app.models.planet import Planet - db.init_app(app) - migrate.init_app(app, db) - from .routes import planets_bp app.register_blueprint(planets_bp) diff --git a/app/routes.py b/app/routes.py index 5dfd66267..5f28fc5d0 100644 --- a/app/routes.py +++ b/app/routes.py @@ -12,8 +12,7 @@ def handle_planets(): if request.method == "GET": name_query = request.args.get("name") if name_query: - # planets = Planet.query.filter_by(name=name_query) - planets = Planet.query.filter(name_query.like(name_query)) + planets = Planet.query.filter(Planet.name.ilike(name_query)) else: planets = Planet.query.all() diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 000000000..44cfd13ff --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,37 @@ +import pytest +from app import create_app +from app import db +from app.models.planet import Planet + +@pytest.fixture +def app(): + app = create_app({"TESTING": True}) + + with app.app_context(): + db.create_all() + yield app + + with app.app_context(): + db.drop_all() + +@pytest.fixture +def client(app): + return app.test_client() + + +@pytest.fixture +def two_saved_planets(app): + # Arrange + arrakis_planet = Planet( + name="Arrakis", + description="Got the spice", + has_moons=True + ) + pluto_planet = Planet( + name="Pluto", + description="sad", + has_moon=True + ) + + db.session.add_all([arrakis_planet, pluto_planet]) + db.session.commit() \ No newline at end of file diff --git a/tests/test_routes.py b/tests/test_routes.py new file mode 100644 index 000000000..2be3db371 --- /dev/null +++ b/tests/test_routes.py @@ -0,0 +1,39 @@ +def test_get_all__lanetswith_no_records(client): + # Act + response = client.get("/planets") + response_body = response.get_json() + + # Assert + assert response.status_code == 200 + assert response_body == [] + + +def test_get_one_planet(client, two_saved_planets): + # Act + response = client.get("/planets/1") + response_body = response.get_json() + + # Assert + assert response.status_code == 200 + assert response_body == { + "name": "Arrakis", + "description": "Got the spice", + "has_moons": True + } + + +# def test_create_a_book(client): +# # act +# response = client.post("/books", json = { +# "title" : "The Never Ending Story", +# "description" : "The horse dies" +# }) +# response_body = response.get_json() + +# # assert +# assert response.status_code == 201 +# assert response_body == { +# "id" : 1, +# "title" : "The Never Ending Story", +# "description": "The horse dies" +# } \ No newline at end of file From a3738f699e053cbd8eb480fe1808abd9f154535a Mon Sep 17 00:00:00 2001 From: ayaka Date: Wed, 27 Oct 2021 11:16:58 -0700 Subject: [PATCH 09/11] fix tests --- tests/conftest.py | 2 +- tests/test_routes.py | 19 ++----------------- 2 files changed, 3 insertions(+), 18 deletions(-) diff --git a/tests/conftest.py b/tests/conftest.py index 44cfd13ff..947fae2b8 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -30,7 +30,7 @@ def two_saved_planets(app): pluto_planet = Planet( name="Pluto", description="sad", - has_moon=True + has_moons=True ) db.session.add_all([arrakis_planet, pluto_planet]) diff --git a/tests/test_routes.py b/tests/test_routes.py index 2be3db371..8e160c003 100644 --- a/tests/test_routes.py +++ b/tests/test_routes.py @@ -1,4 +1,4 @@ -def test_get_all__lanetswith_no_records(client): +def test_get_all_planets_with_no_records(client): # Act response = client.get("/planets") response_body = response.get_json() @@ -16,24 +16,9 @@ def test_get_one_planet(client, two_saved_planets): # Assert assert response.status_code == 200 assert response_body == { + "id": 1, "name": "Arrakis", "description": "Got the spice", "has_moons": True } - -# def test_create_a_book(client): -# # act -# response = client.post("/books", json = { -# "title" : "The Never Ending Story", -# "description" : "The horse dies" -# }) -# response_body = response.get_json() - -# # assert -# assert response.status_code == 201 -# assert response_body == { -# "id" : 1, -# "title" : "The Never Ending Story", -# "description": "The horse dies" -# } \ No newline at end of file From 85f62c552f97e35beeeec37a7378ce00db1baef3 Mon Sep 17 00:00:00 2001 From: Rhyannon Date: Tue, 2 Nov 2021 11:59:04 -0600 Subject: [PATCH 10/11] Created Procfile, Installed gunicorn --- Procfile | 1 + app/routes.py | 10 ++++------ requirements.txt | 8 ++++++++ tests/test_routes.py | 3 +-- 4 files changed, 14 insertions(+), 8 deletions(-) create mode 100644 Procfile diff --git a/Procfile b/Procfile new file mode 100644 index 000000000..62e430aca --- /dev/null +++ b/Procfile @@ -0,0 +1 @@ +web: gunicorn 'app:create_app()' \ No newline at end of file diff --git a/app/routes.py b/app/routes.py index 5f28fc5d0..0bea24f62 100644 --- a/app/routes.py +++ b/app/routes.py @@ -4,8 +4,6 @@ planets_bp = Blueprint("planets", __name__, url_prefix="/planets") -planets_bp = Blueprint("planets", __name__, url_prefix="/planets") - @planets_bp.route("", methods=["GET", "POST"]) def handle_planets(): @@ -26,14 +24,14 @@ def handle_planets(): return jsonify("Invalid Request"), 400 new_planet = Planet( - name = request_body["name"], - description = request_body["description"], - has_moons = request_body["has_moons"] + name=request_body["name"], + description=request_body["description"], + has_moons=request_body["has_moons"] ) db.session.add(new_planet) db.session.commit() - + return jsonify(f"created {new_planet.name}"), 201 @planets_bp.route("/", methods=["GET", "PUT", "DELETE"]) diff --git a/requirements.txt b/requirements.txt index fd90fffa8..09438102a 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,4 +1,5 @@ alembic==1.5.4 +attrs==21.2.0 autopep8==1.5.5 certifi==2020.12.5 chardet==4.0.0 @@ -6,13 +7,20 @@ click==7.1.2 Flask==1.1.2 Flask-Migrate==2.6.0 Flask-SQLAlchemy==2.4.4 +gunicorn==20.1.0 idna==2.10 +iniconfig==1.1.1 itsdangerous==1.1.0 Jinja2==2.11.3 Mako==1.1.4 MarkupSafe==1.1.1 +packaging==21.0 +pluggy==1.0.0 psycopg2-binary==2.8.6 +py==1.10.0 pycodestyle==2.6.0 +pyparsing==3.0.2 +pytest==6.2.5 python-dateutil==2.8.1 python-dotenv==0.15.0 python-editor==1.0.4 diff --git a/tests/test_routes.py b/tests/test_routes.py index 8e160c003..26590861a 100644 --- a/tests/test_routes.py +++ b/tests/test_routes.py @@ -20,5 +20,4 @@ def test_get_one_planet(client, two_saved_planets): "name": "Arrakis", "description": "Got the spice", "has_moons": True - } - + } \ No newline at end of file From fe21d6128a83a80b19a22a8b9737fe5bde3bbfb1 Mon Sep 17 00:00:00 2001 From: Rhyannon Date: Tue, 2 Nov 2021 13:11:55 -0600 Subject: [PATCH 11/11] Changed location of db, app/__init__.py --- app/__init__.py | 2 +- .../d4244cbb0171_adds_planet_model.py | 34 ------------------- ...3_add_planet_model.py => e746b4fff154_.py} | 8 ++--- 3 files changed, 5 insertions(+), 39 deletions(-) delete mode 100644 migrations/versions/d4244cbb0171_adds_planet_model.py rename migrations/versions/{8d90ba2cc7d3_add_planet_model.py => e746b4fff154_.py} (86%) diff --git a/app/__init__.py b/app/__init__.py index bcfee766f..dd40eb58c 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -13,7 +13,7 @@ def create_app(test_config=None): if not test_config: app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False - app.config['SQLALCHEMY_DATABASE_URI'] = "postgresql+psycopg2://postgres:postgres@localhost:5432/solar_system_development" + app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('SQLALCHEMY_DATABASE_URI') else: app.config["TESTING"] = True app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False diff --git a/migrations/versions/d4244cbb0171_adds_planet_model.py b/migrations/versions/d4244cbb0171_adds_planet_model.py deleted file mode 100644 index 6ca918e89..000000000 --- a/migrations/versions/d4244cbb0171_adds_planet_model.py +++ /dev/null @@ -1,34 +0,0 @@ -"""adds Planet model - -Revision ID: d4244cbb0171 -Revises: -Create Date: 2021-10-22 12:43:57.773211 - -""" -from alembic import op -import sqlalchemy as sa - - -# revision identifiers, used by Alembic. -revision = 'd4244cbb0171' -down_revision = None -branch_labels = None -depends_on = None - - -def upgrade(): - # ### commands auto generated by Alembic - please adjust! ### - op.create_table('planet', - sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), - sa.Column('name', sa.String(), nullable=True), - sa.Column('description', sa.String(), nullable=True), - sa.Column('has_moons', sa.Boolean(), nullable=True), - sa.PrimaryKeyConstraint('id') - ) - # ### end Alembic commands ### - - -def downgrade(): - # ### commands auto generated by Alembic - please adjust! ### - op.drop_table('planet') - # ### end Alembic commands ### diff --git a/migrations/versions/8d90ba2cc7d3_add_planet_model.py b/migrations/versions/e746b4fff154_.py similarity index 86% rename from migrations/versions/8d90ba2cc7d3_add_planet_model.py rename to migrations/versions/e746b4fff154_.py index 84589116a..569a3d8a4 100644 --- a/migrations/versions/8d90ba2cc7d3_add_planet_model.py +++ b/migrations/versions/e746b4fff154_.py @@ -1,8 +1,8 @@ -"""add Planet model +"""empty message -Revision ID: 8d90ba2cc7d3 +Revision ID: e746b4fff154 Revises: -Create Date: 2021-10-22 11:43:16.374084 +Create Date: 2021-11-02 13:00:21.172685 """ from alembic import op @@ -10,7 +10,7 @@ # revision identifiers, used by Alembic. -revision = '8d90ba2cc7d3' +revision = 'e746b4fff154' down_revision = None branch_labels = None depends_on = None