1

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 Answer 1

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:
enter image description here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.