1. 程式人生 > >【flask學習】01-flask自帶轉換器的使用規則

【flask學習】01-flask自帶轉換器的使用規則

為了不影響閱讀,原始碼放在最後,需要的可以自己閱讀 本文主要驗證flask自帶轉換器的使用規則

整理後的原始碼

class BaseConverter(object): 
    """Base class for all converters."""
    兩個變數: regex  weight
    函式:
        初始化
        def __init__(self, map):

        給python返回一個value
        def to_python(self, value):

        給url返回一個編碼後的value
        def to_url(self, value):

class UnicodeConverter(BaseConverter):
    """預設轉換器 接收任何字串"""

     例::

        規則( '/頁/<頁>'),
        規則( '/<字串(長度=2):LANG_CODE>')

     :param map:the:class:`Map`。
     :param minlength:字串的最小長度。 必須更大
                       或等於1。
     :param maxlength:字串的最大長度。
     :param length:字串的確切長度。

class NumberConverter(BaseConverter):
    """IntegerConverter和FloatConverter的基類"""
    變數:
        map, fixed_digits, min, max

class IntegerConverter(NumberConverter):
    """此轉換器僅接受整數值"""
    支援:
        固定位數
        最小值
        最大值

class FloatConverter(NumberConverter):
    """此轉換器僅接受浮點值"""
    支援:
        最小值
        最大值

# 預設轉換器
DEFAULT_CONVERTERS = {
    'default':          UnicodeConverter,
    'string':           UnicodeConverter,
    'any':              AnyConverter,
    'path':             PathConverter,
    'int':              IntegerConverter,
    'float':            FloatConverter,
    'uuid':             UUIDConverter,
}

分割線=======================================

驗證使用方法 程式碼演示:

from flask import Flask

app = Flask(__name__)


@app.route('/')
def index():
    return 'index'

# # 預設轉換器
# DEFAULT_CONVERTERS = {
#     'default':          UnicodeConverter,
#     'string':           UnicodeConverter,
#     'any':              AnyConverter,
#     'path':             PathConverter,
#     'int':              IntegerConverter,
#     'float':            FloatConverter,
#     'uuid':             UUIDConverter,
# }


# UnicodeConverter 預設轉換器
# @app.route('/demo1/<default(minlength=5, maxlength=10):page_id>') 最小長度 最大長度
# @app.route('/demo1/<default(length=6):page_id>')  固定長度
# @app.route('/demo1/<string(length=6):page_id>')  default string 都可用於 UnicodeConverter
@app.route('/demo1/<string(minlength=5, maxlength=10):page_id>')
def demo1(page_id):
    """
    UnicodeConverter
    預設轉換器 接收任何字串
     例::
        規則( '/頁/<頁>'),
        規則( '/<字串(長度=2):LANG_CODE>')
     :param map:the:class:`Map`。
     :param minlength:字串的最小長度。 必須更大或等於1。
     :param maxlength:字串的最大長度。
     :param length:字串的確切長度。
    """
    return 'demo1--page_id is--%s' % page_id


# IntegerConverter(NumberConverter) 整數型轉換器
# @app.route('/demo2/<int:page_id>')  整型
# @app.route('/demo2/<int(6):page_id>')  固定位數
# @app.route('/demo2/<int(min=10):page_id>') 最小值
# @app.route('/demo2/<int(max=10):page_id>') 最大值
@app.route('/demo2/<int(min=10, max=100):page_id>')  # 取區間值
def demo2(page_id):
    """
    此轉換器僅接受整數值
    支援:
        固定位數
        最小值
        最大值
    """
    return 'demo2--page_id is--%s' % page_id


# FloatConverter(NumberConverter) 浮點型轉換器
# @app.route('/demo3/<float:page_id>')  浮點型
# @app.route('/demo3/<float(min=5):page_id>')  最小值
# @app.route('/demo3/<float(max=5):page_id>')  最大值
@app.route('/demo3/<float(min=5, max=10):page_id>')  取最小最大區間值
def demo3(page_id):
    """
    支援:
        最小值
        最大值
    :return:
    """
    return 'demo3--page_id is--%s' % page_id

if __name__ == '__main__':
    app.run(debug=True)

分割線=======================================

flask的轉換器原始碼

class BaseConverter(object):

    """Base class for all converters."""
    regex = '[^/]+'
    weight = 100

    def __init__(self, map):
        self.map = map

    def to_python(self, value):
        return value

    def to_url(self, value):
        return url_quote(value, charset=self.map.charset)


class UnicodeConverter(BaseConverter):

    """This converter is the default converter and accepts any string but
    only one path segment.  Thus the string can not include a slash.

    This is the default validator.

    Example::

        Rule('/pages/<page>'),
        Rule('/<string(length=2):lang_code>')

    :param map: the :class:`Map`.
    :param minlength: the minimum length of the string.  Must be greater
                      or equal 1.
    :param maxlength: the maximum length of the string.
    :param length: the exact length of the string.
    """

    def __init__(self, map, minlength=1, maxlength=None, length=None):
        BaseConverter.__init__(self, map)
        if length is not None:
            length = '{%d}' % int(length)
        else:
            if maxlength is None:
                maxlength = ''
            else:
                maxlength = int(maxlength)
            length = '{%s,%s}' % (
                int(minlength),
                maxlength
            )
        self.regex = '[^/]' + length


class AnyConverter(BaseConverter):

    """Matches one of the items provided.  Items can either be Python
    identifiers or strings::

        Rule('/<any(about, help, imprint, class, "foo,bar"):page_name>')

    :param map: the :class:`Map`.
    :param items: this function accepts the possible items as positional
                  arguments.
    """

    def __init__(self, map, *items):
        BaseConverter.__init__(self, map)
        self.regex = '(?:%s)' % '|'.join([re.escape(x) for x in items])


class PathConverter(BaseConverter):

    """Like the default :class:`UnicodeConverter`, but it also matches
    slashes.  This is useful for wikis and similar applications::

        Rule('/<path:wikipage>')
        Rule('/<path:wikipage>/edit')

    :param map: the :class:`Map`.
    """
    regex = '[^/].*?'
    weight = 200


class NumberConverter(BaseConverter):

    """Baseclass for `IntegerConverter` and `FloatConverter`.

    :internal:
    """
    weight = 50

    def __init__(self, map, fixed_digits=0, min=None, max=None):
        BaseConverter.__init__(self, map)
        self.fixed_digits = fixed_digits
        self.min = min
        self.max = max

    def to_python(self, value):
        if (self.fixed_digits and len(value) != self.fixed_digits):
            raise ValidationError()
        value = self.num_convert(value)
        if (self.min is not None and value < self.min) or \
           (self.max is not None and value > self.max):
            raise ValidationError()
        return value

    def to_url(self, value):
        value = self.num_convert(value)
        if self.fixed_digits:
            value = ('%%0%sd' % self.fixed_digits) % value
        return str(value)


class IntegerConverter(NumberConverter):

    """This converter only accepts integer values::

        Rule('/page/<int:page>')

    This converter does not support negative values.

    :param map: the :class:`Map`.
    :param fixed_digits: the number of fixed digits in the URL.  If you set
                         this to ``4`` for example, the application will
                         only match if the url looks like ``/0001/``.  The
                         default is variable length.
    :param min: the minimal value.
    :param max: the maximal value.
    """
    regex = r'\d+'
    num_convert = int


class FloatConverter(NumberConverter):

    """This converter only accepts floating point values::

        Rule('/probability/<float:probability>')

    This converter does not support negative values.

    :param map: the :class:`Map`.
    :param min: the minimal value.
    :param max: the maximal value.
    """
    regex = r'\d+\.\d+'
    num_convert = float

    def __init__(self, map, min=None, max=None):
        NumberConverter.__init__(self, map, 0, min, max)


class UUIDConverter(BaseConverter):

    """This converter only accepts UUID strings::

        Rule('/object/<uuid:identifier>')

    .. versionadded:: 0.10

    :param map: the :class:`Map`.
    """
    regex = r'[A-Fa-f0-9]{8}-[A-Fa-f0-9]{4}-' \
            r'[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{12}'

    def to_python(self, value):
        return uuid.UUID(value)

    def to_url(self, value):
        return str(value)


#: the default converter mapping for the map.
DEFAULT_CONVERTERS = {
    'default':          UnicodeConverter,
    'string':           UnicodeConverter,
    'any':              AnyConverter,
    'path':             PathConverter,
    'int':              IntegerConverter,
    'float':            FloatConverter,
    'uuid':             UUIDConverter,
}