Skip to Content
Flask Web开发:基于Python的Web应用开发实战(第2版)
book

Flask Web开发:基于Python的Web应用开发实战(第2版)

by Miguel Grinberg
August 2018
Intermediate to advanced
230 pages
6h 42m
Chinese
O'Reilly Media, Inc. Beijing
Content preview from Flask Web开发:基于Python的Web应用开发实战(第2版)
模板
27
生模板中添加新的
JavaScript
文件,需要这么定义
scripts 区块:
{% block scripts %}
{{ super() }}
<script type="text/javascript" src="my-script.js"></script>
{% endblock %}
3.3
 自定义错误页面
如果你在浏览器的地址栏中输入了无效的路由,会看到一个状态码为
404
的错误页面。与
使用
Bootstrap
的页面相比,现在这个错误页面太简陋、平庸,而且与现有页面不一致。
像常规路由一样,
Flask
允许应用使用模板自定义错误页面。最常见的错误代码有两个:
404
,客户端请求未知页面或路由时显示;
500
,应用有未处理的异常时显示。示例
3-6
使
app.errorhandler 装饰器为这两个错误提供自定义的处理函数。
示例
3-6
 
hello.py
:自定义错误页面
@app.errorhandler(404)
def page_not_found(e):
return render_template('404.html'), 404
@app.errorhandler(500)
def internal_server_error(e):
return render_template('500.html'), 500
与视图函数一样,错误处理函数也返回一个响应。此外,错误处理函数还要返回与错误对
应的数字状态码。状态码可以直接通过第二个返回值指定。
错误处理函数中引用的模板也需要我们编写。这些模板应该和常规页面使用相同的布局 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.

Read now

Unlock full access

More than 5,000 organizations count on O’Reilly

AirBnbBlueOriginElectronic ArtsHomeDepotNasdaqRakutenTata Consultancy Services

QuotationMarkO’Reilly covers everything we've got, with content to help us build a world-class technology community, upgrade the capabilities and competencies of our teams, and improve overall team performance as well as their engagement.
Julian F.
Head of Cybersecurity
QuotationMarkI wanted to learn C and C++, but it didn't click for me until I picked up an O'Reilly book. When I went on the O’Reilly platform, I was astonished to find all the books there, plus live events and sandboxes so you could play around with the technology.
Addison B.
Field Engineer
QuotationMarkI’ve been on the O’Reilly platform for more than eight years. I use a couple of learning platforms, but I'm on O'Reilly more than anybody else. When you're there, you start learning. I'm never disappointed.
Amir M.
Data Platform Tech Lead
QuotationMarkI'm always learning. So when I got on to O'Reilly, I was like a kid in a candy store. There are playlists. There are answers. There's on-demand training. It's worth its weight in gold, in terms of what it allows me to do.
Mark W.
Embedded Software Engineer

You might also like

Python机器学习基础教程

Python机器学习基础教程

Andreas C. Müller, Sarah Guido
Python编程入门与实战

Python编程入门与实战

Posts & Telecom Press, Fabrizio Romano
程序设计导论:Python语言实践

程序设计导论:Python语言实践

罗伯特 塞奇威克, 凯文 韦恩, 罗伯特 唐德罗

Publisher Resources

ISBN: 9787115489456