当前位置:网站首页>[flask introduction series] exception handling
[flask introduction series] exception handling
2022-07-19 14:46:00 【Hall owner a Niu】
Personal profile
- Author's brief introduction : Hello everyone , I'm Daniel , New star creator of the whole stack .
- Blogger's personal website : A Niu's blog house
- Stand by me : give the thumbs-up + Collection ️+ Leaving a message.
- Series column :flask Framework quick start
- Maxim : To be light , Because there are people who are afraid of the dark !

Preface
Today is a brief introduction flask Methods for exception handling in , It belongs to the knowledge point that is less popular , Because we use python Knowledge to achieve these needs processing , But we still need to learn , Because he can help us deal with exceptions , Instead of exception handling in each view .
HTTP Exception active throw
- abort Method
Throw a given status code HTTPException Or specify the response , For example, you want to terminate a request with a page that does not find an exception , You can call abort(404) - Parameters
code-HTTP Error status code of . Can only throw http Error code for protocol .
# Import Flask Classes and request object
from flask import Flask,request,abort
app = Flask(__name__)
@app.route('/articles')
def get_articles():
channel_id = request.args.get('channel_id')
if channel_id is None:
abort(400) #400 Bad Request
return 'you want get articles of channel {}'.format(channel_id)
# Flask Application's run Method start up web The server
if __name__ == '__main__':
app.run(port=8000)

Capture the error
- errorhandler Decorator
Register an error handler , When the program throws the specified error status code , Will call the method decorated by the decorator . - Parameters
code_or_exception - HTTP Error status code or specified exception . - For example, the unified processing status code is 500 The error of gives users a good prompt .
@app.errorhandler(500)
def internal_server_err(e):
return " Server moved "
- Catch the specified exception
@app.errorhandler(ZeroDivisionError)
def zero_division_err(e):
return " Divisor cannot be zero "
example :
# Import Flask class
from flask import Flask
app = Flask(__name__)
@app.errorhandler(ZeroDivisionError)
def zero_division_err(e):
# there e It's an exception object
print(e)
return " Divisor cannot be zero "
@app.route("/")
def index():
s = 1/0
return s
# Flask Application's run Method start up web The server
if __name__ == '__main__':
app.run(port=8000)


As can be seen from the figure , If you encounter an exception, you will immediately stop executing the current view , Instead, execute the corresponding exception handling view .
Conclusion
If you think the blogger's writing is good , You can pay attention to the current column , Bloggers will finish this series ! You are also welcome to subscribe to other good columns of bloggers .
Series column
Soft grinding css
Hard bubble javascript
The front end is practical and small demo
边栏推荐
- C speech Young's matrix · left-hand string · judge whether the string is rotated
- Codeforces Round #808 (Div. 1)(A~C)
- Win10 Microsoft Store cannot be opened (enable TLS 1.2)
- STM32 positioning hardfault location method and encountered situation in keil environment
- 运行时加载 Objective-C
- Si446 usage record (III): match function
- TDesign CompositionAPI 重构之路
- JVM性能优化
- Mvcc multi version concurrency control
- Classification of blocks
猜你喜欢

Database SQL Server

The manual is not complete. How to manually dig out the monitoring information of tongweb?

Manuel incomplet, comment tracer manuellement l'information de surveillance de tongweb?

Zhikanghu property elderly care service plan

微信小程序---wxss模板样式

Mvcc multi version concurrency control

Abstract classes and derived classes

One article, teach you to achieve single sign on

慎用TongWeb的热部署功能

Huawei wireless device configuration intelligent roaming
随机推荐
SQL相关的时间日期类型
JVM performance optimization
單片機軟件定時器V2.0
智康护物业养老服务方案
Authing practice | unified management solution for manufacturing identity authentication
SQL related time date type
Tree and bipartite graph [thinking]
单片机软件定时器V2.0
Win10 Microsoft Store cannot be opened (enable TLS 1.2)
Alibaba微服务组件Nacos注册中心
Can [C language - user defined type] be adjusted like this?
C - pointer
Classes abstraites et dérivées
论文阅读 TEMPORAL GRAPH NETWORKS FOR DEEP LEARNING ON DYNAMIC GRAPHS
AcWing 274. 移动服务【DP】
Tongweb production system emergency treatment plan
SCM software timer v2.0
学习记录[email protected]之moveActivityIdTo任务回退特殊案例分析
Win10 Microsoft Store打不开(开启TLS 1.2)
Deep understanding of transaction isolation levels