簡體   English   中英

如何在Django / Tastypie中處理動作?

[英]How to handle actions in Django/Tastypie?

我正在編寫一個Web應用程序,目的是充當應用程序和Amazon API之間的中間層。 我認為可以使用REST風格的API,並選擇了Deliciouspie來簡化實現。

我創建了一個名為Instance的模型,並創建了一個Deliciouspie資源。 為了簡單起見,假設對該資源的PUT將啟動EC2實例,而DELETE將停止它。 在需要與Amazon API通信的地方,應該在哪里處理這些操作? 它應該放在資源代碼,模型代碼還是其他地方?

另外,將錯誤消息返回給客戶端的最合適方法是什么?

我會這樣做:

  • PUT創建一個新實例並將其存儲在數據庫中
  • 實例模型上的Django Post Save Signal執行一個特殊的事情:

在models.py中:

@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()

在task.py中:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM