Python Flask-使用数组填充SelectField选项
这里的新手,已经写了6个多月的Python脚本了 我试图用一个列表填充wtf SelectField,该列表是从从Slack API获取数据的函数返回的。该列表包含频道名称,我想将其设置为SelectField的选项 以下是我的函数代码:Python Flask-使用数组填充SelectField选项,python,flask,flask-wtforms,Python,Flask,Flask Wtforms,这里的新手,已经写了6个多月的Python脚本了 我试图用一个列表填充wtf SelectField,该列表是从从Slack API获取数据的函数返回的。该列表包含频道名称,我想将其设置为SelectField的选项 以下是我的函数代码: def get_channels_list(slack_token): sc = SlackClient(slack_token) a = sc.api_call('channels.list', exc
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
for i in a['channels']:
# str1 = ("('%s','#%s')," % (i['name'],i['name']))
list1.append((i['name'],'#'+i['name']))
它们的格式如下:
[u"('whoisdoingwhat','#whoisdoingwhat'),",
u"('windowsproblems','#windowsproblems'),",
u"('wow','#wow'),",
u"('wp-security','#wp-security'),",]
('whoisdoingwhat','#whoisdoingwhat'),
('windowsproblems','#windowsproblems'),
('wow','#wow'),
('wp-security','#wp-security'),
我希望以以下格式将其传递到我的函数中:
[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:抛出了太多无法解压缩的值。
我怎样才能做到这一点?我觉得我很接近,但错过了一些东西
解决方案:
问题在于我对数据如何返回并因此传递到其他地方的理解错误/无知
在my get_channels_list函数中修改了以下内容:
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
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,)
在获取频道列表
函数中,为
循环不必要地在中创建字符串
将其更改为:
for i in a['channels']:
list1.append((i['name'], '#' + i['name']))
或者更像蟒蛇:
return [(i['name'], '#' + i['name']) for i in a['channels']]
带有工作表单的HTML: