python入门Flask框架学习(二)

 自定义转换器

 结合昨天路由学习的基础转换器,今日自定义一个 通过基础demo和一个功能demo 来记录

第一步自定义需要导入相关包 需要引

from werkzeug.routing import BaseConverter

 第二步 创建转换器(定义类继承BaseConverter父类)

             1、父类初始化

              2、将自定义的转换器添加到flask应用

              3、在视图函数设置自定义路由转换器

'''
转换器demo
'''
#定义创建转换器
class RegexConverter(BaseConverter): # RegexConverter类继承BaseConverter类
   # init 初始化
    def __init__(self, url_map, regex): #函数方法
        """
        :param url_map: 固定传递参数 用于调用初始化方法
        :param regex:  从url() 传递的正则参数
        """
        # 调用父类初始化方法super
        super(RegexConverter, self).__init__(url_map)
        # 将正则表达式参数保存到对象属性中,flask会使这个属性进行路由的正则匹配
        self.regex = regex

#将自定义的转换器类添加到flask应用中
app.url_map.converters['re'] = RegexConverter
# 在视图函数中设置自定义路由转换器
# 127.0.0.1:5000/send/18912345678
# <re(''): param> 使用re自定义转换器,其中()则是需要传递的参数
@app.route("/send/<re('1[345789]\d{9}'):mobile>")
def send(mobile):
    return "send sms to %s" % mobile
 创建专属手机号码转换器 demo案例

与其基础demo 区别:

  1、正则指定在转换器类中设置

   2、使用to_url 与 to_python 

 

在Flask中可以使用专属转换器的to_python和to_url两个函数
来处理url请求至视图函数之间的业务处理,例如:权限验证,session数据记录等等
to_python 将url传递的参数,直接将其传递至视图函数之中
to_url 则是当另一个视图函数使用 url_for() 这个方法跳至该转换器的时候,会将url的参数传递到url路径的参数中
"""
在Flask中可以使用专属转换器的to_python和to_url两个函数
来处理url请求至视图函数之间的业务处理,例如:权限验证,session数据记录等等
to_python 将url传递的参数,直接将其传递至视图函数之中
to_url 则是当另一个视图函数使用 url_for() 这个方法跳至该转换器的时候,会将url的参数传递到url路径的参数中
"""
class MobileConverter(BaseConverter):
    def __init__(self, url_map):
        """
        调用父方法一
        super(MobileConverter, self).__init__(url_map)
        调用父方法二
        super().__init__(url_map)
        """
        super().__init__(url_map)
        #正则指定
        self.regex = '1[356789]\d{9}'

   #打印结果可知to_python方法就是url传递到视图函数中间的业务处理方法
   # to_python可用做权限校验之类的需求
    def to_python(self, value):
       if value != "13131630227" :
           print("调用to_python的手机号 %s" % value)
           return "当前手机号与to_python中不一致"
       return "当前手机号 %s" % value

    #to_url 可作用url重定向跳转携带参数校验
    """
       to_url 使用过程
       1、first_send redirect  url_for send
       2、将重定向携带参数mobile_number='12456124567' to_url 进行校验 输出参数为13131630227
       3、如果存在to_python 的话 to_url 后 传入 to_python (逻辑校验后)输出到 send方法进行输出 
    """
    def to_url(self, value):
        if value != "12456124567" :
            print("to_url %s" % value)
            return "当前手机号与to_url中不一致"
        return "13131630227"


#注册MobileConverter转换器
app.url_map.converters['mobile'] = MobileConverter

#设置视图函数
@app.route("/send/<mobile:mobile_number>", methods=['GET', 'POST'])
def send(mobile_number):
    if request.method == 'POST':
        return "POST 方法打印手机号:%s" % mobile_number
    return "GET 方法打印手机号:%s" % mobile_number

@app.route('/first_send')
def first_send():
    return  redirect(url_for('send',mobile_number="12456124567"))
 to_url 与 to_python的使用分析
to_url 使用过程
1、first_send redirect  url_for send
2、将重定向携带参数mobile_number='12456124567' to_url 进行校验 输出参数为13131630227
3、如果存在to_python 的话 to_url 后 传入 to_python (逻辑校验后)输出到 send方法进行输出 

 #打印结果可知to_python方法就是url传递到视图函数中间的业务处理方法 # to_python可用做权限校验之类的需求

二者关系 需亲身运行一下方可体会!!!

 form表单

"""  如何进行前后端交互
1、 创建软件包 为 templates (模板)
2、 在模板文件中创建h5文件 例如:index.html 书写前端页面
3、 引入render_template 包进行前后端渲染
"""
@app.route('/index')
def index():
    return render_template('index.html')

request对象

request 包含前端发送过来的 所有请求数据 导入包 request
def index():
    if request.method == 'POST':
        # 获取表单值
        # username = request.form['username']
        # password = request.form['password']
        data = request.form  # 获取所有
        print(data['username'],data['password'])
        return "这是post请求"
    if request.method == 'GET':
        return render_template('index.html')

 abort函数

abort 在网页主动抛出异常 导包abort  raise 主动抛出异常
def index():
    if request.method == 'GET':
        return render_template('index.html')
    if request.method == 'POST':
       data = request.form
       if data['username'] == 'admin' and data['password'] == 'root':
           return 'login successfully'
       #如果账号密码错误则抛出异常
       abort(404)
       return None

自定义错误

#定义自定义错误处理方法
# 简易文字报错
# @app.errorhandler(404)
# def handle_404_error(error):
#     return "出现了404错误%s"%error
#跳转页面 加载静态文件 需创建静态软件包static
def index():
    if request.method == 'GET':
        return render_template('index.html')
    if request.method == 'POST':
       data = request.form
       if data['username'] == 'admin' and data['password'] == 'root':
           return 'login successfully'
       #如果账号密码错误则抛出异常
       abort(404)
       return None

#定义自定义错误处理方法
# 简易文字报错
# @app.errorhandler(404)
# def handle_404_error(error):
#     return "出现了404错误%s"%error
#跳转页面 加载静态文件 需创建静态软件包static
@app.errorhandler(404)
def handle_404_error(error):
    return render_template('404.html')

 json响应格式

两种方法:make_response  / jsonify

  data = {
        'code' : 200 ,
        'msg' : "测试成功" ,
        'data' : {
            'id' : '1',
            'name' : '小米'
        }
    }
    ## 第一种 导入两个包 make_response , json
      response =  make_response(json.dumps(data,ensure_ascii=False))
      response.mimetype = 'application/json' # 设置为json 数据

    ##第二种 导入jsonify  需要添加app.config['JSON_AS_ASCII'] = False
    response = jsonify(data)
    return response

 重定向同自定义转换器

 


# @app.route('/index')
# def index():
#     return redirect('http://www.baidu.com')

# 接口重定向 导入url_for
# @app.route('/index')
# def index():
#     return "url_for 测试"
#
# @app.route('/')
# def hello():
#     return redirect(url_for('index'))

#重定向url_for 携带参数
@app.route('/index/<id>')
def index(id):
    if id != "1001":
        return "id 异常"
    return "测试成功"

@app.route('/')
def hello():
    return redirect(url_for('index',id="1001"))

注: 自定义转换器中涉及多个功能点需认真分析

本文章仅作者学习笔记

  • 6
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值