【问题标题】:Flask - Populate SelectField choices with arrayFlask - 使用数组填充 SelectField 选项
【发布时间】:2017-08-25 17:43:26
【问题描述】:

这里是新手,写 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 会被抛出。
我怎样才能做到这一点?我觉得我很接近但缺少一些东西。

解决方案: 问题在于我对数据如何返回并因此传递到其他地方的错误理解/无知。

在我的 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,)

【问题讨论】:

    标签: python flask flask-wtforms


    【解决方案1】:

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

    改成这样:

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

    或者更pythonic:

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

    带有工作表单的 HTML:

    【讨论】:

      猜你喜欢
      • 2021-01-30
      • 2012-12-20
      • 2017-09-18
      • 1970-01-01
      • 2019-12-19
      • 1970-01-01
      • 2020-05-10
      • 1970-01-01
      • 2019-03-09
      相关资源
      最近更新 更多