为了账号安全,请及时绑定邮箱和手机立即绑定

Flask 在重定向之前路由运行代码并在 python 控制台中抛出错误

Flask 在重定向之前路由运行代码并在 python 控制台中抛出错误

肥皂起泡泡 2023-03-30 09:48:37
我有一个奇怪的问题,python 终端抛出一个AttributeError: 'NoneType' object has no attribute 'find'但我在 Flask 调试控制台中没有收到任何错误并且应用程序正常工作,没有任何问题。python 控制台中的错误让我抓狂,我想了解发生了什么。我的应用程序的布局如下。我呈现一个主页,该主页通过 html 表单检索用户的输入并获取该值,在本例中为股票代码,并重定向到函数 infoPage,其中股票代码用于执行一些网络抓取。@app.route('/', methods=['GET', 'POST'])def stockTickerInput():    if request.method == "POST":        ticker = request.form['ticker'].upper()        return redirect(url_for('infoPage', ticker=ticker))    return render_template('home.html')出于某种原因,python 在 flask 重定向到infoPage. 我知道这一点,因为一旦呈现,我就会在用户甚至在 html 表单中输入股票行情之前home.html收到错误。AttributeError: 'NoneType' object has no attribute 'find'@app.route('/<ticker>')def infoPage(ticker):         # scrapes stock chart/company info from finviz    def stockInfo():                url = 'https://finviz.com/quote.ashx?t=' + ticker        html = requests.get(url, headers={'User-Agent': 'Mozilla/5.0'})        soup = BeautifulSoup(html.text, 'lxml')                # finds news table within finviz website        stock_website = soup.find('table', class_="fullview-title")        company_name = stock_website.find('a', class_='tab-link').text                return company_name        # functions to be passed as variables in jinja2 template    info = stockInfo()        return render_template('stockInfo.html', ticker=ticker, info=info)
查看完整描述

1 回答

?
DIEA

TA贡献1820条经验 获得超2个赞

这部分:

if result is None:  # if result is none means ticker exists
    return redirect(url_for('infoPage', ticker=ticker))

你的代码执行是因为result从这一行得到一个 None 的值:

result = match.find('h4').text

return redirect(url_for('infoPage', ticker=ticker))因此,在你跑步之前触发ever return render_template('stockInfo.html', ticker=ticker, info=info)


查看完整回答
反对 回复 2023-03-30
  • 1 回答
  • 0 关注
  • 92 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信