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

Ihovanna + Maria Fernanda #41

Open
wants to merge 28 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
28 commits
Select commit Hold shift + click to select a range
8af0f79
progress on get all planets
Mfpr603 Oct 24, 2022
0bbe40c
reverting to no routes folder state
Ihovanna Oct 24, 2022
912fc68
starting dictionary in planets.py
Ihovanna Oct 24, 2022
d040581
wave 1 shows a dict of all planets in sever
Ihovanna Oct 24, 2022
25ac4ab
incomplete Wave 2
Mfpr603 Oct 25, 2022
886a2d1
Wave 2 completed, changed from Planet_name to planet_id per learn che…
Mfpr603 Oct 25, 2022
4e374b7
Planets class, HTTP request returns all planets.
Ihovanna Nov 4, 2022
7dc2a1c
Merge branch 'main' of https://github.com/Mfpr603/solar-system-api
Ihovanna Nov 4, 2022
0a19d23
Changed Blueprints to routes.py
Ihovanna Nov 4, 2022
252d9a1
Endpoint /planet_id shows one planet
Ihovanna Nov 4, 2022
0d4a0b4
Wave 2: returns one planet with /<planet_id> endpoint, returns error …
Ihovanna Nov 4, 2022
dc978e0
Created Planet model and initiated in app>__init__.py
Ihovanna Nov 6, 2022
53cca8a
Migrated and upgraded model (my local database updated; you need to u…
Ihovanna Nov 6, 2022
e541508
Wave 3: HTTP POST requests updates local database with new data entri…
Ihovanna Nov 7, 2022
9ee2e9e
GET request returns one planet based on id.
Ihovanna Nov 7, 2022
395f104
refactores handle_planet based on API lesson 4
Ihovanna Nov 7, 2022
e8568ac
Route to update one planet
Ihovanna Nov 7, 2022
b64177f
Delete HTTP request successful
Ihovanna Nov 7, 2022
13511c4
Helper function complete
Mfpr603 Nov 7, 2022
cb05168
resolved conflicts to push helper
Mfpr603 Nov 7, 2022
4bbe9e1
unsure
Ihovanna Nov 7, 2022
c04f19d
Merge branch 'main' of https://github.com/Mfpr603/solar-system-api
Ihovanna Nov 7, 2022
a7a1396
Deleted comments
Ihovanna Nov 7, 2022
95b8385
Added validate_planet() function to every route with a panet_id
Ihovanna Nov 7, 2022
fb3836f
set up test database
Ihovanna Nov 9, 2022
cca6ced
Created tests foder, conftest.py and test_routes.py. Single test for …
Ihovanna Nov 9, 2022
f6d343b
all tests for GET requests pass. Missing POST tests.
Ihovanna Nov 10, 2022
3b1548c
Created 100% test coverage for routes.
Ihovanna Nov 10, 2022
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
The diff you're trying to view is too large. We only load the first 3000 changed files.
Binary file added .coverage
Binary file not shown.
140 changes: 0 additions & 140 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,141 +1 @@
.vscode
.DS_Store

# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

# C extensions
*.so

# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST

# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/

# Translations
*.mo
*.pot

# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal

# Flask stuff:
instance/
.webassets-cache

# Scrapy stuff:
.scrapy

# Sphinx documentation
docs/_build/

# PyBuilder
.pybuilder/
target/

# Jupyter Notebook
.ipynb_checkpoints

# IPython
profile_default/
ipython_config.py

# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version

# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock

# PEP 582; used by e.g. github.com/David-OConnor/pyflow
__pypackages__/

# Celery stuff
celerybeat-schedule
celerybeat.pid

# SageMath parsed files
*.sage.py

# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/

# Spyder project settings
.spyderproject
.spyproject

# Rope project settings
.ropeproject

# mkdocs documentation
/site

# mypy
.mypy_cache/
.dmypy.json
dmypy.json

# Pyre type checker
.pyre/

# pytype static type analyzer
.pytype/

# Cython debug symbols
cython_debug/
7 changes: 7 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"python.testing.pytestArgs": [
"tests"
],
"python.testing.unittestEnabled": false,
"python.testing.pytestEnabled": true
}
26 changes: 25 additions & 1 deletion app/__init__.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,31 @@
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__)

return app
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)

from app.models.planet_model import Planet

from .routes import planets_bp
app.register_blueprint(planets_bp)

return app
Binary file added app/__pycache__/__init__.cpython-310.pyc
Binary file not shown.
Binary file added app/__pycache__/__init__.cpython-39.pyc
Binary file not shown.
Binary file added app/__pycache__/planets.cpython-310.pyc
Binary file not shown.
Binary file added app/__pycache__/planets.cpython-39.pyc
Binary file not shown.
Binary file added app/__pycache__/routes.cpython-310.pyc
Binary file not shown.
Binary file added app/__pycache__/routes.cpython-39.pyc
Binary file not shown.
Empty file added app/models/__init__.py
Empty file.
Binary file added app/models/__pycache__/__init__.cpython-310.pyc
Binary file not shown.
Binary file added app/models/__pycache__/__init__.cpython-39.pyc
Binary file not shown.
Binary file added app/models/__pycache__/planet_model.cpython-310.pyc
Binary file not shown.
Binary file added app/models/__pycache__/planet_model.cpython-39.pyc
Binary file not shown.
45 changes: 45 additions & 0 deletions app/models/planet_model.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
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)

Choose a reason for hiding this comment

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

some helper methods like

    def to_dict(self):

        return {
            "name": self.name,
            "color": self.color,
            "description": self.description,
            "id": self.id
        }
    @classmethod   
    def from_json(cls, input_dict):
        return cls(
            name= input_dict["name"],
            color= input_dict["color"],
            description= input_dict["description"]
        )

Might be helpful


'''
Planet descriptions for Postman POST HTML requests bodies:
{
"name": "Mercury",
"description": "The smallest planet in our solar system and closest to the Sun. It is only slightly larger than Earth's Moon."
}
{
"name": "Venus",
"description": "Spins slowly in the opposite direction from most planets. A thick atmosphere traps heat in a runaway greenhouse effect."
}

{
"name": "Earth",
"description": "The only place that's inhabited by living things. Also, the only planet in our solar system with liquid water on the surface."
}

{
"name": "Mars",
"description": "A dusty, cold desert world with a very thin atmosphere."
}
{
"name": "Jupiter",
"description": "More than twice as massive than other planets in our solar system combined."
}
{
"name": "Saturn",
"description": "Adorned with a dazzling, complex system of icy rings."
}
{
"name": "Uranus",
"description": "Rotates at a nearly 90-degree angle from the plane of its orbit."
}
{
"name": "Neptune",
"description": "Is dark, cold and whipped by supersonic winds. First planet located through mathematical calculations."
}
'''
82 changes: 81 additions & 1 deletion app/routes.py
Original file line number Diff line number Diff line change
@@ -1,2 +1,82 @@
from flask import Blueprint
from app import db
from flask import Blueprint, jsonify, make_response, abort, request
from app.models.planet_model import Planet

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

@planets_bp.route("", methods=["POST"])
def create_planet():

Choose a reason for hiding this comment

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

Some input validation on the request body would be appropriate here.

request_body = request.get_json()
new_planet = Planet(
name=request_body["name"],
description=request_body["description"]
)

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

return make_response(f"Planet {new_planet.name} has been added to the Planets database.", 201)


@planets_bp.route("", methods=["GET"])
def all_planets():
planets_response = []
planets = Planet.query.all()

for planet in planets:
planets_response.append({
"id": planet.id,
"name": planet.name,
"description": planet.description
})
Comment on lines +27 to +31

Choose a reason for hiding this comment

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

This would be a great place to use that helper method I listed in the Planet Class.


return jsonify(planets_response)


@planets_bp.route("/<planet_id>", methods=["GET"])
def handle_planet(planet_id):

Choose a reason for hiding this comment

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

Why name this handle_planet instead of get_planet?

planet = validate_planet(planet_id)

return {
"id": planet.id,
"name": planet.name,
"description": planet.description
}


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

planet.name = request_body["name"]
planet.description = request_body["description"]

db.session.commit()

return make_response(f"Planet {planet.name} has been updated in the Planets database.", 201)




@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(f"Planet {planet.name} has been deleted from the Planets database.", 200)


def validate_planet(planet_id):
try:
planet_id = int(planet_id)
except:
abort(make_response({"message":f"Planet {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
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.
Binary file added migrations/__pycache__/env.cpython-310.pyc
Binary file not shown.
Binary file added migrations/__pycache__/env.cpython-39.pyc
Binary file not shown.
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