python - 如何在无效网址上显示错误消息?
问题描述
@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,用户将被重定向到主页,但是一旦用户被重定向到主页,我想闪烁错误消息。
解决方案
除了当前的 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 方法会随时触发。您可以做的是指定不同的语句来输出并检查不同的崩溃标准。
资料来源:
推荐阅读
- javascript - 如何在 JavaScript 中显示无序列表?
- prometheus - 链接 grafana 变量
- c++ - 更改 QLineEdit 的 x 和 y 位置
- r - R 当相关性为 1 时,与 1 相同的检查给出 FALSE
- python - Pyspark - SparkStreaming - Python v3.5 - java.lang.ClassCastException:java.lang.Integer 不能转换为 java.lang.Long
- java - Java:如何在 UTC 中获取“1000-01-01 00:00:00”的时间戳?
- python - 用定义的值替换列表列表中的元素 - Python
- laravel - Laravel - 语法错误,意外的“电话”(T_CONSTANT_ENCAPSED_STRING),期待“]”
- angular - 通过 HttpRequest 加载安全缓存的图像
- javascript - 如何在 ar.js 中使用自定义标记