How to handle actions in Django/Tastypie?
I'm writing a web app which purpose is to act as an intermediate layer between an application and Amazon's API. I figured a REST style API would fit and chose Tastypie to ease the implementation.
I've created a model called Instance and a Tastypie resource to go with it. To simplify a bit, let's say a PUT to that resource would launch an EC2 instance and a DELETE would stop it. Where is the proper place to handle the these actions where I need to communicate with the Amazon's API? Should it go in the resource code, the model code or elsewhere?
Also, what is the most appropriate way to return error messages to the client?
I would do it like this:
- PUT creates a new Instance and stores it in the database
- A Django Post Save Signal on the Instance model executes a special thingy:
@receiver(post_save, sender=Instance, dispatch_uid="create_instance") def create_instance(sender, **kwargs): instance = kwargs['instance'] created = kwargs['created'] raw = kwargs['raw'] if instance and created and not raw: from my_project.my_app.tasks import create_ec2_instance result = create_ec2_instance(instance) if result: instance.started = True instance.save()
def create_ec2_instance(instace): # do the calls to ec2 to create the instance and get a result form it return the_result_from_ec2