Flask - Populate SelectField choices with array

倾然丶 夕夏残阳落幕 提交于 2019-12-11 07:08:18

问题


Newbie here, been writing Python scripts for little bit more than 6 months.

I'm trying to populate a wtf SelectField with a list, returned from a function that fetches the data from Slack API. The list contains channel names, that i wanted to setup as the choices of the SelectField.

Here's the code of my function:

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   

They come in this format:

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

Which i would like to pass into my function in this format:

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

And here is the code in question:

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

Of course, ValueError: too many values to unpack is thrown.
How can I accomplish this? I feel I am very close but missing something.

Solution: The issue was with my wrong understanding/ignorance in how data is returned and therefore passed elsewhere.

modified the following in my get_channels_list function:

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

This returns a list of tuples.
We now pass it on as an argument to the SelectField object, without the square brackets:

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

回答1:


You unnecessarily create string in for loop in get_channels_list function.

Change it to this:

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

or to be even more pythonic:

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

HTML with working form:



来源:https://stackoverflow.com/questions/45877050/flask-populate-selectfield-choices-with-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!