如何在装饰器中获得Flask可选的URL参数

如何在装饰器中获得Flask可选的URL参数

本文介绍了如何在装饰器中获得Flask可选的URL参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我有Flask API都使用手机作为可选的url参数,如下所示,我想用一个装饰器来验证电话号码是否正确。
所以我可以得到参数手机的地方没有解析请求的网址?


$ p $ @ user_api.route(/< phone> / login)
@check_phone
def login(phone):
f = OrderedDict()
f ['error'] = 0
return jsonify(f)

@ user_api.route / $ lt; phone> / logout)
@check_phone
def logout(phone):
f = OrderedDict()
f ['error'] = 0
return jsonify(f)


解决方案
有一个更好的机制来验证内置到Werkzeug(和Flask)的url值。定义一个,并像使用任何其他转换器一样使用它(例如,< int:id> )。

 从werkzeug.routing导入BaseConverter,ValidationError 
$ b $ class PhoneConverter(BaseConverter):
regex = r'\d {7,10}'#这个验证值的基本形式
$ b $ def to_python(self,value):
#做更复杂的验证
如果不是复杂的电话号码(值):
raise ValidationError('not a valid phone number')

返回值

app.url_map.converters ['phone'] = PhoneConverter

@ app.route('/< phone:phone> ;')
def get_phone(phone):
#phone is valid






您还可以使用 before_request 函数来验证所有路由与电话argum而不必装饰它们。

 来自瓶子导入请求,中止

@ app.before_request
def valid_phone():
如果'phone'不在request.view_args:
返回#view没有电话arg

如果不是复杂的电话号码验证(request.view_args [ 'phone']):
abort(404)

@ app.route('/< phone>')
def get_phone(phone):
#电话有效

@ app.route('/< other>)
def get_other(其他):
#无电话参数,不验证






如果您真的想使用装饰器,参数。

  from functools import wrapps 

def check_phone(f):
@wraps (f)
def内部(** kwargs):
phone = kwargs ['phone']
#做一些验证
返回f(** kwargs)

返回内部

@ app.route('/ < phone>')
@check_phone
def get_phone(phone):
#phone is valid


I have Flask APIs all use phone as optional url parameters as showed below, and I want to use a decorator to verify if the phone number is correct.So can I get the parameter "phone" somewhere without parsing the request url?

@user_api.route("/<phone>/login")
@check_phone
def login(phone):
    f = OrderedDict()
    f['error'] = 0
    return jsonify(f)

@user_api.route("/<phone>/logout")
@check_phone
def logout(phone):
    f = OrderedDict()
    f['error'] = 0
    return jsonify(f)
解决方案

There is a better mechanism to validate url values built in to Werkzeug (and Flask). Define a converter and use it like you would use any other converter in the route (for example, <int:id>).

from werkzeug.routing import BaseConverter, ValidationError

class PhoneConverter(BaseConverter):
    regex = r'\d{7,10}'  # this validates the basic form of the value

    def to_python(self, value):
        # do more complicated validation
        if not complicated_phone_validation(value):
            raise ValidationError('not a valid phone number')

        return value

app.url_map.converters['phone'] = PhoneConverter

@app.route('/<phone:phone>')
def get_phone(phone):
    # phone is valid


You can also use a before_request function to validate all routes with a phone argument without having to decorate them all.

from flask import request, abort

@app.before_request
def valid_phone():
    if 'phone' not in request.view_args:
        return  # view has no phone arg

    if not complicated_phone_validation(request.view_args['phone']):
        abort(404)

@app.route('/<phone>')
def get_phone(phone):
    # phone is valid

@app.route('/<other>')
def get_other(other):
    # no phone arg, no validation


If you really want to use a decorator, a decorated function gets called with arguments.

from functools import wraps

def check_phone(f):
    @wraps(f)
    def inner(**kwargs):
        phone = kwargs['phone']
        # do some validation
        return f(**kwargs)

    return inner

@app.route('/<phone>')
@check_phone
def get_phone(phone):
    # phone is valid

这篇关于如何在装饰器中获得Flask可选的URL参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-07 00:42