Conversation
… folder and created a planets_routes.py
… get medthod and created function to create a list of all the planets.
…refactored create_app.
| migrate.init_app(app, db) | ||
|
|
||
| app.register_blueprint(planets_bp) | ||
|
|
| class Planet(db.Model): | ||
| id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True) | ||
| name: Mapped[str] | ||
| description: Mapped[str] | ||
| num_moons: Mapped[int] |
There was a problem hiding this comment.
We could have some methods on this class that could make our business logic in our routes more clean and in line with SRP
| # def to_dict(self): | ||
| # return dict( | ||
| # id = self.id, | ||
| # name = self.name, | ||
| # description = self.description, | ||
| # num_moons = self.num_moons, | ||
| # ) |
There was a problem hiding this comment.
Like this here could be added to our Planet class.
| response = { | ||
| "id": new_planet.id, | ||
| "name": new_planet.name, | ||
| "description": new_planet.description, | ||
| "num_moons": new_planet.num_moons | ||
| } |
There was a problem hiding this comment.
This is a place where you could call that method, like so new_planet.to_dict().
| "num_moons": planet.num_moons | ||
| } | ||
| ) | ||
| return planets_response |
| return { | ||
| "id": planet.id, | ||
| "name": planet.name, | ||
| "description": planet.description, | ||
| "num_moons": planet.num_moons, | ||
| } |
There was a problem hiding this comment.
Another place where you could call to_dict.
| planet.name = request_body["name"] | ||
| planet.description = request_body["description"] | ||
| planet.num_moons = request_body["num_moons"] | ||
| db.session.commit() |
There was a problem hiding this comment.
Could this be its own helper function perhaps?
| def validate_planet(planet_id): | ||
| try: | ||
| planet_id =int(planet_id) | ||
| except: | ||
| response = {"message": f"Planet {planet_id} invalid."} | ||
| abort(make_response(response, 400)) | ||
|
|
||
| query = db.select(Planet).where(Planet.id==planet_id) | ||
| planet = db.session.scalar(query) | ||
|
|
||
| if not planet: | ||
| response = {"message": f"Planet {planet_id} not found."} | ||
| abort(make_response(response, 404)) | ||
|
|
||
| return planet |
There was a problem hiding this comment.
Now that we've learned a little more about refactoring, where could this function live?
| @pytest.fixture | ||
| def two_saved_planets(app): | ||
| # Arrange | ||
| planet_1 = Planet(name="Mercury", description="first planet", num_moons=0) | ||
| planet_2 = Planet(name="Venus", description="second planet", num_moons=0) | ||
|
|
||
| db.session.add_all([planet_1, planet_2]) | ||
| db.session.commit() |
| "name": "Earth", | ||
| "description": "Blue planet", | ||
| "num_moons": 1 | ||
| } |
There was a problem hiding this comment.
Nice work on these tests! How could we modify them to make sure that our changes (additions and deletions) are being persisted to our database?
No description provided.