Capture a list of integers with a Flask route

一曲冷凌霜 提交于 2019-11-29 14:55:50

Create a custom url converter that matches comma separated digits, splits the matched string into a list of ints, and passes that list to the view function.

from werkzeug.routing import BaseConverter

class IntListConverter(BaseConverter):
    regex = r'\d+(?:,\d+)*,?'

    def to_python(self, value):
        return [int(x) for x in value.split(',')]

    def to_url(self, value):
        return ','.join(str(x) for x in value)

Register the converter on app.url_map.converters.

app = Flask(__name__)
app.url_map.converters['int_list'] = IntListConverter

Use the converter in the route. values will be a list of ints.

@app.route('/add/<int_list:values>')
def add(values):
    return str(sum(values))
/add/1,2,3 -> values=[1, 2, 3]
/add/1,2,z -> 404 error
url_for('add', values=[1, 2, 3]) -> /add/1,2,3

How about this one? We just take the list of integers as a variable and then add them up.

import re

from flask import Flask


app = Flask(__name__)


@app.route('/add/<int_list>')
def index(int_list):
    # Make sure it is a list that only contains integers.
    if not re.match(r'^\d+(?:,\d+)*,?$', int_list):
        return "Please input a list of integers, split with ','"
    result = sum(int(i) for i in int_list.split(','))
    return "{0}".format(result)


if __name__ == '__main__':
    app.run(debug=True)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!