在執行我的Python腳本我剛剛得到了以下類型的錯誤:什麼可能導致TypeError:無法連接'str'和'function'對象?
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
引起該問題的路線似乎是url="http://finance.yahoo.com/d/quotes.csv?s="+stock+"&f=snl1"
,特別是變量stock.
經過研究,並從我從以前的錯誤,知道一點,我推斷原因必須是變量定義的問題(它不是一個字符串,或者可能根本沒有定義);這麼說,我定義這個變量作爲字符串中的函數之前:
@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')
這裏是我嘗試調用並顯示前面定義的值的函數,stock
:
@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')
然而,它被定義在與我稱之爲不同的@app.route
中。不應該像Python那樣存儲和調用Python中的變量,或者在加載新頁面時變量被清空了嗎?如果是這種情況,任何有關工作或更好的方法的建議將不勝感激。
測試'stock'的類型以確保:'type(stock)' – gecco
我不是燒瓶專家,但是一旦退出函數'home_search()','stock'就會被垃圾回收,再加上你無法在函數之外訪問它。 –
我認爲問題是,你正在將'stock'視爲'return'重定向(url_for('stock'))中的字符串' – avasal