Beispiel #1
0
    def put(self, pet_id):
        pet = Pet.objects.filter(external_id=pet_id, live=True).first()
        if not pet:
            return jsonify({}), 404
        pet_json = request.json
        error = best_match(Draft4Validator(schema).iter_errors(pet_json))
        if error:
            return jsonify({"error": error.message}), 400

        store = Store.objects.filter(external_id=pet_json.get('store')).first()
        if not store:
            error = {"code": "STORE_NOT_FOUND"}
            return jsonify({'error': error}), 400

        try:
            received_date = datetime.datetime.strptime(
                pet_json.get('received_date'), "%Y-%m-%dT%H:%M:%SZ")
        except:
            return jsonify({"error": "INVALID_DATE"}), 400

        pet.name = pet_json.get('name')
        pet.species = pet_json.get('species')
        pet.breed = pet_json.get('breed')
        pet.age = pet_json.get('age')
        pet.store = store
        pet.price = pet_json.get('price')
        pet.received_date = received_date
        pet.save()
        response = {"result": "ok", "pet": pet_obj(pet)}
        return jsonify(response), 200
Beispiel #2
0
    def get(self, pet_id):
        if pet_id:
            pet = Pet.objects.filter(external_id=pet_id, live=True).first()
            if pet:
                response = {"result": "ok", "pet": pet_obj(pet)}
                return jsonify(response), 200
            else:
                return jsonify({}), 404
        else:
            # pet URL template
            pet_href = "/pets/?page=%s"

            pets = Pet.objects.filter(live=True)
            if "species" in request.args:
                pets = pets.filter(species=request.args.get('species'))
                pet_href += "&species=" + request.args.get('species')
            if "breed" in request.args:
                pets = pets.filter(breed=request.args.get('breed'))
                pet_href += "&breed=" + request.args.get('breed')

            page = int(request.args.get('page', 1))
            pets = pets.paginate(page=page, per_page=self.PETS_PER_PAGE)

            response = {
                "result": "ok",
                "total": pets.total,
                "links": [{
                    "href": pet_href % page,
                    "rel": "self"
                }],
                "pets": pets_obj(pets)
            }
            if pets.has_prev:
                response["links"].append({
                    "href": pet_href % (pets.prev_num),
                    "rel": "previous"
                })
            if pets.has_next:
                response["links"].append({
                    "href": pet_href % (pets.next_num),
                    "rel": "next"
                })
            return jsonify(response), 200