I just got the following type error while executing my Python script:
File "/Library/Python/2.7/site-packages/Flask-0.9-py2.7.egg/flask/app.py", line 1701, in __call__
return self.wsgi_app(environ, start_response)
File "/Library/Python/2.7/site-packages/Flask-0.9-py2.7.egg/flask/app.py", line 1689, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "/Library/Python/2.7/site-packages/Flask-0.9-py2.7.egg/flask/app.py", line 1687, in wsgi_app
response = self.full_dispatch_request()
File "/Library/Python/2.7/site-packages/Flask-0.9-py2.7.egg/flask/app.py", line 1360, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/Library/Python/2.7/site-packages/Flask-0.9-py2.7.egg/flask/app.py", line 1358, in full_dispatch_request
rv = self.dispatch_request()
File "/Library/Python/2.7/site-packages/Flask-0.9-py2.7.egg/flask/app.py", line 1344, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/Users/Zach/Dropbox/stock/stk.py", line 31, in stock
url="http://finance.yahoo.com/d/quotes.csv?s="+stock+"&f=snl1"
TypeError: cannot concatenate 'str' and 'function' objects
The line causing the problem seems to be url="http://finance.yahoo.com/d/quotes.csv?s="+stock+"&f=snl1", specifically the variable stock. After research and from the little I know from previous errors, I deduced that the cause must be an issue with how the variable is defined (it’s either not a string, or possibly not defined at all); that said, I define this variable as a string in the function before:
@app.route('/', methods=['GET', 'POST'])
def home_search():
if request.method == 'POST':
stock = request.form['s']
return redirect(url_for('stock'))
return render_template('stk.html')
And here is the function, stock where I attempt to call and display the value earlier defined:
@app.route('/stock', methods=['GET', 'POST'])
def stock():
print type(stock)
url="http://finance.yahoo.com/d/quotes.csv?s="+stock+"&f=snl1"
text=urllib2.urlopen(url).read()
return render_template('stock.html')
However, it is being defined in a different @app.route than when I call it. Shouldn’t variables in Python be stored and recalled like that, or are variables emptied when new pages are loaded? If this is the case, any suggestions for a work around or a better approach would be greatly appreciated.
Named functions are variables just like everything else. The
stockthat is being used in this line:is the function that contains it. You shouldn’t rely on Python variables across requests; instead, you should pass the variable along as a request variable, e.g.
and then read it back out of the new
request.formin the handler for that URL.The
stockvariable that you’re creating in yourhome_searchfunction is a local variable that only lives for the life of the call tohome_search, which ends as soon as you redirect the client to a different URL (such as/stock).