首页 > 解决方案 > 如何在无效网址上显示错误消息?

问题描述

@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        session['link'] = request.form.get('link')
        link = YouTube(session['link'])
        return render_template('video.html', link=link)
    return render_template('index.html')


@app.route('/download', methods=['GET', 'POST'])
def download():
    if request.method == "POST":
        link = YouTube(session['link'])
        itag = request.form.get('itag')
        video = link.streams.get_by_itag(itag)
        filename = video.download()
        return send_file(filename, as_attachment=True)
    return redirect(url_for('index'))


if __name__ == '__main__':
    app.run(debug=True)

我希望我的 youtube 下载器代码在用户输入无效 URL 或视频不可用时显示错误消息。如果用户输入无效的 URL,则会显示内部服务器错误。

改动后:

   @app.route('/', methods=['GET', 'POST'])
   def index():
       try:
          if request.method == 'POST':
             session['link'] = request.form.get('link')
             link = YouTube(session['link'])
             return render_template('video.html', link=link)
          return render_template('index.html')
       except:
           return redirect(url_for('index'))

现在,如果用户输入无效的 URL,用户将被重定向到主页,但是一旦用户被重定向到主页,我想闪烁错误消息。

标签: pythonhtmlcssflask

解决方案


除了当前的 API 调用,您可以使用catch 方法和 Javascript 中的新 Fetch 方法:

fetch('https://example.com/profile', {
  method: 'POST', // or 'PUT'
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify(data),
})
.then(response => response.json())
.then(data => {
  console.log('Success:', data);
})
.catch((error) => {
  console.error('Error:', error);
});

发生错误时,catch 方法会随时触发。您可以做的是指定不同的语句来输出并检查不同的崩溃标准。

资料来源:


推荐阅读