Flask - 使用数组填充 SelectField 选择

Flask - Populate SelectField choices with array

这里是新手,编写 Python 脚本已经 6 个多月了。

我正在尝试使用从 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被抛出
我怎样才能做到这一点?我觉得我很接近但缺少一些东西。

解法: 问题是我在如何返回数据并因此将其传递到其他地方方面有错误 understanding/ignorance。

在我的 get_channels_list 函数中修改了以下内容:

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

这是一个 returns 元组列表。
我们现在将它作为参数传递给 SelectField 对象,不带方括号:

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

您在 for 函数的 for 循环中不必要地创建了字符串。

改成这样:

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

或者更像 pythonic:

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

HTML 工作形式: