Beispiel #1
0
 def create(self, model, data, **kwargs):
     """
     Create a new instance of a model
     :param model: The model name to create an instance of
     :type model: str
     :param data: The data to provide to that instance, formatted as a Collection+JSON data array
     :type data: list
     :return: Collection representation of the created resource.
     """
     try:
         data = Template(data)
     except (TypeError, ValueError, IndexError):
         abort(400)
     # letting this raise a KeyError on purpose, flask returns HTTP 500 on python errors
     instance = self.models[model](data)
     session = sessionmaker(bind=self.database)
     session.add(instance)
     session.commit()
     return Collection(href=self.app.config.get('API_ROOT'),
                       items=[instance.get_collection_item()])
Beispiel #2
0
    def update(self, model, data, pk=None, **kwargs):
        """
        Update a model instance in the database.
        :param model: The model name to look for an instance of.
        :param data: The data to provide to the instance, formatted as a Collection+JSON data array
        :param pk: The primary key of the model instance to modify.
        :param kwargs:
        :return: A Collection+JSON representation of the updated model instance.
        """
        try:
            data = Template(data)
        except (TypeError, ValueError, IndexError):
            abort(400)

        # letting self.models[model] raise a KeyError on purpose, see above
        instance = self.models[model].query.get_or_404(pk)
        instance.update(data)
        self.database.session.commit()
        return Collection(
            href=self.app.config.get('API_ROOT'),
            template=self.models[model].get_collection_template(),
            items=[instance.get_collection_item()])