2017-11-18 66 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