ここでは、6ヶ月以上ちょっとしたPythonスクリプトを書きました。Flask - SelectFieldの配列に配列を設定する
Slf APIからデータを取得する関数から返されたリストを使用して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,)