def planets(id=None): if request.method == 'GET': if id is not None: planet = Planet.query.get(id) if not planet: return jsonify({"fail": "Planet not found"}), 404 return jsonify({ "success": "Planet found", "planet": planet.serialize() }), 200 else: planets = Planet.query.all() planets = list(map(lambda planet: planet.serialize(), planets)) return jsonify({ "total": len(planets), "results": planets }), 200 if request.method == 'POST': name = request.json.get('name') population = request.json.get('population') terrain = request.json.get('terrain') climate = request.json.get('climate') rotation_period = request.json.get('rotation_period') orbital_period = request.json.get('orbital_period') gravity = request.json.get('gravity') planet = Planet() planet.name = name planet.population = population planet.terrain = terrain planet.climate = climate planet.rotation_period = rotation_period planet.orbital_period = orbital_period planet.gravity = gravity planet.save() return jsonify({ "success": "planet created!", "planet": planet.serialize() }), 201 if request.method == 'PUT': pass if request.method == 'DELETE': planet = Planet.query.get(id) if not planet: return jsonify({"fail": "planet not found"}), 404 planet.delete() return jsonify({"success": "planet deleted"}), 200
def createPlanet(): planet = Planet() planet.name = request.json.get('name') planet.rotation_period = request.json.get('rotation_period') planet.orbital_period = request.json.get('orbital_period') planet.diameter = request.json.get('diameter') planet.climate = request.json.get('climate') planet.gravity = request.json.get('gravity') planet.terrain = request.json.get('terrain') planet.surface_water = request.json.get('surface_water') planet.population = request.json.get('population') planet.save() return jsonify(planet.to_dict()), 201
def post(self): try: result = PlanetSchema().load(request.json) newplanet = Planet(**result) if Planet.objects(name__iexact=newplanet.name): return ApiResponseBuilder.error( 'this planet is already in the database', 404) newplanet.get_appearances() newplanet.save() except ma_exc.ValidationError as err: return ApiResponseBuilder.error(err.messages, 400) return ApiResponseBuilder.success( f'planet named {newplanet.name} was added successfully', newplanet.serialized, 201)
def seed(): if os.getenv('env') == "docker": db = connect('planets', host="mongo") else: db = connect('planets') db.drop_database('planets') # CLEARS DATABASE FOR TESTING # POPULATING DATA WITH EXAMPLES tatooine = Planet(name='dagobah', terrain='swamp', climate='murky', appearances=3) tatooine.save() hoth = Planet(name='hoth', terrain='tundra', climate='cold', appearances=1) hoth.save() print('examples added to the database')