Skip to content
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

Tien&Anya - Sharks Solar_system #27

Open
wants to merge 19 commits into
base: main
Choose a base branch
from
Open
1 change: 1 addition & 0 deletions Procfile
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
web: gunicorn 'app:create_app()'
35 changes: 35 additions & 0 deletions app/__init__.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,42 @@
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'
Comment on lines +14 to +15

Choose a reason for hiding this comment

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

since we now have this string stored in our environmental variables for safe keeping we want to get rid of it from public view

Suggested change
# app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
# app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql+psycopg2://postgres:postgres@localhost:5432/solar_system_development'

Copy link
Author

Choose a reason for hiding this comment

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

Agree, should be deleted from init.py


if not test_config:
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get(
"SQLALCHEMY_DATABASE_URI")
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)

# Import models here
from app.models.planet import Planet

# Register Blueprints here
from .routes import planets_bp
app.register_blueprint(planets_bp)

from app.models.planet import Planet

return app



15 changes: 15 additions & 0 deletions app/helper.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
from flask import abort, make_response

Choose a reason for hiding this comment

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

👍 Great job moving this helper function into a separate file, so that our routes are more clean and easy to read!

from app.models.planet import Planet

def validate_planet(planet_id):
try:
planet_id = int(planet_id)
except:
abort(make_response({"message":f"planet_id {planet_id} invalid"}, 400))

planet = Planet.query.get(planet_id)

if not planet:
abort(make_response({"message":f"planet {planet_id} not found"}, 404))

return planet
Empty file added app/models/__init__.py
Empty file.
47 changes: 47 additions & 0 deletions app/models/planet.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@

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)
moons = db.Column(db.Integer)

def to_json(self):
return {
"id": self.id,
"name" : self.name,
"description": self.description,
"moons": self.moons
}

def update(self, req_body):

Choose a reason for hiding this comment

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

👍 helper method woo

self.name = req_body["name"]
self.description = req_body["description"]
self.moons = req_body["moons"]

@classmethod
def create(cls,req_body):
new_planet = cls(
name=req_body["name"],
description=req_body["description"],
moons=req_body["moons"]
)
return new_planet



# class Planet():
# def __init__(self, id, name, description, moons = None):
# self.id = id
# self.name = name
# self.description = description
# self.moons = moons

# def to_json(self):
# return {
# "id": self.id,
# "name" : self.name,
# "decription": self.description,
# "moons": self.moons
# }
Comment on lines +34 to +47

Choose a reason for hiding this comment

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

Suggested change
# class Planet():
# def __init__(self, id, name, description, moons = None):
# self.id = id
# self.name = name
# self.description = description
# self.moons = moons
# def to_json(self):
# return {
# "id": self.id,
# "name" : self.name,
# "decription": self.description,
# "moons": self.moons
# }

Copy link
Author

Choose a reason for hiding this comment

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

Forgot delete those lines

63 changes: 62 additions & 1 deletion app/routes.py
Original file line number Diff line number Diff line change
@@ -1,2 +1,63 @@
from flask import Blueprint
from requests import request
from app import db
from app.models.planet import Planet
from flask import Blueprint, jsonify, abort, make_response, request
from .helper import validate_planet

planets_bp = Blueprint("planets_bp", __name__, url_prefix="/planets")

# CREATE PLANET
@planets_bp.route("", methods=["POST"])
def create_planet():
request_body = request.get_json()

new_planet = Planet.create(request_body)

db.session.add(new_planet)
db.session.commit()

# return make_response(jsonify(f"Planet {new_planet.name} successfully created!", 201))

Choose a reason for hiding this comment

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

This looks the same as the one below, so let's get rid of this

Suggested change
# return make_response(jsonify(f"Planet {new_planet.name} successfully created!", 201))

return make_response(jsonify(f"Planet {new_planet.name} successfully created"), 201)

# GET ALL
@planets_bp.route("", methods=["GET"])
def read_all_planets():
name_query = request.args.get("name")
if name_query:
planets = Planet.query.filter_by(name=name_query)
else:
planets = Planet.query.all()

planets_response = []
for planet in planets:
planets_response.append(planet.to_json())

return jsonify(planets_response), 200

# GET one planet
@planets_bp.route("/<planet_id>", methods=["GET"])
def read_one_planet(planet_id):
planet = validate_planet(planet_id)
# return jsonify(planet.to_json()), 200
return jsonify(planet.to_json())
Comment on lines +41 to +42

Choose a reason for hiding this comment

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

any reason you removed the status code on line 42?

Copy link
Author

Choose a reason for hiding this comment

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

I think no. I am not sure why we removed it.


# UPDATE one planet
@planets_bp.route("/<planet_id>", methods=["PUT"])
def update_planet(planet_id):
planet = validate_planet(planet_id)
request_body = request.get_json()

planet.update(request_body)

db.session.commit()
return make_response(jsonify(f"Planet #{planet.id} successfully updated")), 200

# DELETE one planet
@planets_bp.route("/<planet_id>", methods=["DELETE"])
def delete_planet(planet_id):
planet = validate_planet(planet_id)

db.session.delete(planet)
db.session.commit()

return make_response(jsonify(f"Planet #{planet.id} successfully deleted")), 200
Empty file added app/tests/__init__.py
Empty file.
42 changes: 42 additions & 0 deletions app/tests/conftest.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import pytest

Choose a reason for hiding this comment

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

👍 looks good

from app import create_app
from app import db
from flask.signals import request_finished
from app.models.planet import Planet


@pytest.fixture
def app():
app = create_app({"TESTING": True})

@request_finished.connect_via(app)
def expire_session(sender, response, **extra):
db.session.remove()

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
jupiter = Planet(name="Jupiter",
description="has big spot",
moons=66)
venus = Planet(name="Venus",
description="beauty",
moons=0)

db.session.add_all([jupiter, venus])
# Alternatively, we could do
# db.session.add(jupiter)
# db.session.add(venus)
db.session.commit()
46 changes: 46 additions & 0 deletions app/tests/test_routes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
def test_get_all_planets_with_no_records(client):

Choose a reason for hiding this comment

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

👍 looks good

# 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 == {
"id": 1,
"name": "Jupiter",
"description": "has big spot",
"moons": 66
}

def test_get_one_planet_empty(client):
# Act
response = client.get("/planets/1")
# response_body = response.get_json()

# Assert
assert response.status_code == 404
# assert response_body == make_response({"message":f"planet {planet_id} not found"}, 404)



def test_create_one_planet(client):
# Act
response = client.post("/planets", json={
"name": "Saturn",
"description": "has rings",
"moons": 82
})
response_body = response.get_json()

# Assert
assert response.status_code == 201
assert response_body == "Planet Saturn successfully created"
20 changes: 20 additions & 0 deletions merge.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
result = []
def merge_lists(list1, list2):

if not list1:
return list2
if not list2:
return list1
if not list1 and not list2:
return []

if list1[0] < list2[0]:
result.append(list1[0])
merge_lists(list1[1:], list2)
else:
result.append(list2[0])
merge_lists(list1, list2[1:])

return result

print(merge_lists([1, 2, 4, 5], [1, 2, 4, 5, 6]))
1 change: 1 addition & 0 deletions migrations/README
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Generic single-database configuration.
45 changes: 45 additions & 0 deletions migrations/alembic.ini
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
Loading