Youssef S. Youssef S. - 4 months ago 18
Python Question

Flask unsupported operand type(s) for +: 'dict' and 'str'

I tried to implement this code into flask, it's working correctly in the console but with http requests I got this obscure error:

app.py

@app.route('/results')
def results():

keyword = {'keyword': request.args.get('keyword')}

num_tweets=5

for tweet in tweepy.Cursor(api.search,q=keyword+
" -filter:retweets",
result_type='recent',
lang="en").items(num_tweets):
raw = tweet.text
clean = re.sub(r"(?:@\S*|#\S*|http(?=.*://)\S*)", "", raw)
result = cool.api(clean)
return render_template('pages/results.html')


My html form looks like this:

<form action="/results">
Input:
<br>
<input type="text" name="keyword">
<br>
<input type="submit" value="Submit">
</form>


I also tried a different method:

kwargs = {
'keyword': request.form['keyword'],
}


Adding
methods=['POST', 'GET']
do not fix the problem.

In the error page, the problem is in this line:

" -filter:retweets",

Answer Source

As the error says, you're trying to add a dictionary to a string:

tweepy.Cursor(api.search,q=keyword+ " -filter:retweets",

keyword is a dictionary. Because Python leans towards strong typing, the conversion to string isn't automatic like it is in some languages. Cast it to a string first:

tweepy.Cursor(api.search,q=str(keyword) + " -filter:retweets",

As the commentor mentioned, Python's error messages are usually quite clear. Make sure you really read them over, as they're often self-explanatory.