1.实现正则表达式的过滤器
app.py
#从flask框架中导入Flask类 abort为抛出异常
from flaskimport Flask,render_template,request,abort
#传入__name__初始化实例一个Flask类
app=Flask(__name__)
#实现两个数字之间的运算 传递两个参数
@app.route('/calc/<int:num1>/<int:num2>')
def calc(num1,num2):
if num2==0:
#如果被除数为0程序错误 手动抛出异常编码为500
abort(500)
result=num1/num2
return '计算结果为*%d'%result
from werkzeug.routingimport BaseConverter
'''导入转换器基础类*在路由解析模块*
实现url的万能转发器*
手写一个参数为电话号码的转换器
过滤器/转换器 自定义转换器继承转换器基础类
重写init方法,接受两个参数,url_map,regex*正则名称任意并初始化子类空间和父类空间*
'''
class MyReConverter(BaseConverter):
def __init__(self,url_map,regex):
super(MyReConverter,self).__init__(url_map)
self.regex=regex
app.url_map.converters['re']=MyReConverter
@app.route('/checkage/<re("\d{2}"):num>')
def checkage(num):
print('年龄*%s' %num)
return '芳龄*%s' %num
@app.route('/checkphone/<re("1[3 4 5 7 8]\d{9}"):phone>')
def checkphone(phone):
return '电话号码*%s' %phone
#404和505页面的处理方式
@app.errorhandler(404)
def page_not_found(e):
print(e)
return render_template('404页面显示.html')
@app.errorhandler(500)
def page_not_info(e):
print(e)
return render_template('500页面.html')
#运行本项目 host=0.0.0.0 可以让其他电脑直接运行 port默认值为5000 设置为9000
if __name__ =='__main__':
app.run()


2.404.html
<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8">
<title>显示404页面
<h1>显示404信息找不到页面,请及时和管理员联系
<img src="/static/images/哔哩哔哩404.png">
</html>

3.500.html
<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8">
<title>显示500页面
<h1>后台程序错误,请和管理员及时联系,邮箱*XXXX
<img src="/static/images/哔哩哔哩500.png">
</html>
网友评论