2017-08-25 18 views
1

新手在這裏寫了超過6個月的Python腳本。燒瓶 - 使用數組填充SelectField選項

我想從一個從Slack API中獲取數據的函數返回的列表填充一個wtf SelectField。該列表包含頻道名稱,我想將其設置爲SelectField的選項。

這是我的函數的代碼:

def get_channels_list(slack_token): 
    sc = SlackClient(slack_token) 
    a = sc.api_call('channels.list', 
        exclude_archived=1, 
        exclude_members=1,) 

    a = json.dumps(a) 
    a = json.loads(a) 

    list1 = [] 
    for i in a['channels']: 
     str1 = ("('%s','#%s')," % (i['name'],i['name'])) 
     list1.append(str1) 
    return list1 

他們有這樣的格式:

[u"('whoisdoingwhat','#whoisdoingwhat'),", 
u"('windowsproblems','#windowsproblems'),", 
u"('wow','#wow'),", 
u"('wp-security','#wp-security'),",] 

,我想進入我的這種格式的功能:

('whoisdoingwhat','#whoisdoingwhat'), 
('windowsproblems','#windowsproblems'), 
('wow','#wow'), 
('wp-security','#wp-security'), 

這裏是有問題的代碼:

class SlackMessageForm(Form): 
    a = get_channels_list(app.config['SLACK_API_TOKEN']) 
    channel = SelectField('Channel', 
         choices=[a],) 

當然,ValueError: too many values to unpack被拋出。
我該如何做到這一點?我覺得我非常接近但錯過了一些東西。

解決方案: 問題出在我對數據如何返回並因此傳遞到其他地方的理解/無知。

修改我get_channels_list功能如下:

for i in a['channels']: 
    # str1 = ("('%s','#%s')," % (i['name'],i['name'])) 
    list1.append((i['name'],'#'+i['name'])) 

這會返回一個元組列表。
我們現在在把它作爲參數傳遞給SelectField對象,而方括號:

class SlackMessageForm(Form): 
    a = get_channels_list(app.config['SLACK_API_TOKEN']) 
    channel = SelectField('Channel', 
          choices=a,) 

回答

0

你不必要在for迴路get_channels_list功能創建的字符串。

它改成這樣:

for i in a['channels']: 
    list1.append((i['name'], '#' + i['name'])) 

,或者甚至更Python:

return [(i['name'], '#' + i['name']) for i in a['channels']] 

HTML與工作形式:
enter image description here