2017-11-18 67 views
0

我做了一個Django的網站,這form.py來填充HTML模板用下拉列表與所有我目前的Spotify播放列表:我運行Django的形式spotipy不更新上的Apache2

from django import forms 
import spotipy 
import spotipy.util as util 


def getplaylists(): 

    #credentials 
    CLIENT_ID='xxxxx' 
    CLIENT_SECRET='xxxxx' 
    USER='xxxxxx' 

    # token krijgen 
    token = util.oauth2.SpotifyClientCredentials(client_id=CLIENT_ID, client_secret=CLIENT_SECRET) 
    cache_token = token.get_access_token() 
    sp = spotipy.Spotify(cache_token) 

    # playlists opvragen 
    results = sp.user_playlists(USER,limit=50) 

    namenlijst = [] 
    idlijst = [] 

    for i, item in enumerate(results['items']): 
     namenlijst.append(item['name']) 
     idlijst.append(item['id']) 

    #samenvoegen 
    dropdowndata = zip(idlijst, namenlijst) 
    #dropdowndata = zip(namenlijst, idlijst) 

    return dropdowndata 


class SpotiForm(forms.Form): 

    LIJSTEN = getplaylists() 
    lijstje = forms.ChoiceField(choices=LIJSTEN, required=True) 

在我的VPS上有兩個版本的Django網站(代碼完全相同):
A)Apache2上的一個版本(帶mod_wsgi)
B)測試版本('python ./manage.py runserver xxxx:xxx')

當我在Spotify中添加或刪除播放列表時,版本A中的下拉列表會得到您pdated,但版本B的下拉列表沒有。有人可以向我解釋爲什麼會發生這種情況嗎?

回答

2

因爲在Apache上 - 或任何適當的宿主環境 - 一個進程持續多個請求,但在類或模塊級別完成的任何操作僅在每個進程中執行一次。

像這樣的動態事情應該在方法內完成。在這種情況下,把它放在表格的__init__

class SpotiForm(forms.Form): 
    lijstje = forms.ChoiceField(choices=(), required=True) 

    def __init__(self, *args, **kwargs): 
     super(SpotiForm, self).__init__(*args, **kwargs) 
     self.fields['lijstje'].choices = getplaylists() 
+0

謝謝,這個工程!我不知道什麼方法,但我會找出...我有很多東西要學習Python,我很喜歡它:)。再次感謝您的解決方案! – Joost