Capture a list of integers with a Flask route

淺唱寂寞╮ 提交于 2019-11-28 09:10:16

问题


I'm trying to implement a basic calculator in Flask. I define two url parameters, which is manageable when I only want to add two values. However, I want to add any number of values. How can I get a list of integers without writing an infinitely long route?

@app.route('/add/<int:n1>,<int:n2>')
def add(n1,n2):
    sum = n1+n2
    return "%d" % (sum)

I tried to solve my problem with this code, but it's not working

integer_list = [] 
@app.route('/add/integer_list') 
def fun (integer_list):
    sum = 0
    for item in integer_list:
        sum = sum + item
    return '%d' % sum

回答1:


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



回答2:


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)


来源:https://stackoverflow.com/questions/35437180/capture-a-list-of-integers-with-a-flask-route

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