2016-02-11 52 views
0

我試圖從基於類的視圖調用外部api。 目前我有下面哪個調用API的視圖。然而目前我只是用api(username, password)調用API,它返回數據但不保存。django從視圖調用外部api

我該如何將視圖中modelform中使用的模型傳遞給api函數,以便它可以將返回的數據保存到相關用戶。 (即我需要在CBV中重寫什麼方法)。

另外什麼是在Django中調用外部API的最佳方法(從表單完成啓動)。目前,API往返時間需要5-10秒,目前它的設置方式會延遲下一頁加載量。

class SupplierOnlineAccountView(CreateView): 
    form_class = SupplierOnlineAccountForm 
    template_name = 'standard_form.html' 
    success_url = '../contacting' 

    def form_valid(self, form): 
     username = form.cleaned_data.get('username') 
     password = form.cleaned_data.get('password') 
     api(username, password) 
     return super().form_valid(form) 

型號:

class EUser(models.Model): 
    username = models.CharField(max_length=255, null=True) 
    password = models.CharField(max_length=255, null=True) 
    address = models.ForeignKey(Address, null=True) 
    temp_user = models.CharField(max_length=255, null=True) 
    user = models.OneToOneField(settings.AUTH_USER_MODEL, null=True, default=None) 
    title = models.CharField(max_length=10) 
    first_name = models.CharField(max_length=255) 
    last_name = models.CharField(max_length=255) 
+0

你能詳細說明你到底想做什麼:你得到的數據,你想要保存的數據 –

+0

當然,謝謝,我試圖將返回的API數據保存在Euser模型中。 SupplierOnlineAccountForm也保存到Euser模型。 Api返回first_name,last_name等...和其他數據以保存在EUser模型中。 – Yunti

+0

好的,更新了一個答案。 –

回答

1
def form_valid(self, form): 
    username = form.cleaned_data.get('username') 
    password = form.cleaned_data.get('password') 
    self.object = form.save() 
    api(username, password,self.object) 
    return super().form_valid(form) 

你將不得不更改標題,名字,姓氏字段爲空=真這樣你就可以在API調用之前保存,然後通過保存的模型。

API的等待時間問題,這是一個像芹菜隊列的典型異步任務。您保存表單,然後將任務卸載到在另一個線程(或進程或計算機)上運行的隊列中。然後django不必等到api返回,然後發送響應。

+0

謝謝,我現在在ModelFormMixin中看到。有沒有一種方法不是先保存,而是仍然傳遞要保存的對象,比如'instance = form.save(commit = False)'在基於函數的視圖中?我寧願避免在api將保存的所有字段中填入blank = True,因爲最終可能會有很多。 – Yunti

+0

你可以,但最好先保存到db,尤其是在它進入外部API之前。 –

+0

只是爲了理解爲什麼在去api之前先保存更好? – Yunti