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

我有一个奇怪的问题,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)


肥皂起泡泡
浏览 96回答 1
1回答

DIEA

这部分:if&nbsp;result&nbsp;is&nbsp;None:&nbsp;&nbsp;#&nbsp;if&nbsp;result&nbsp;is&nbsp;none&nbsp;means&nbsp;ticker&nbsp;exists &nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;redirect(url_for('infoPage',&nbsp;ticker=ticker))你的代码执行是因为result从这一行得到一个 None 的值:result&nbsp;=&nbsp;match.find('h4').textreturn redirect(url_for('infoPage', ticker=ticker))因此,在你跑步之前触发ever&nbsp;return render_template('stockInfo.html', ticker=ticker, info=info)。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python