Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capture a list of integers with a Flask route

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
like image 721
Frank Avatar asked Feb 16 '16 15:02

Frank


People also ask

How do you route a Flask?

Routing in FlaskThe route() decorator in Flask is used to bind an URL to a function. As a result when the URL is mentioned in the browser, the function is executed to give the result. Here, URL '/hello' rule is bound to the hello_world() function.

How do you pass a parameter to a route in Flask?

flask route paramsA parameter can be a string (text) like this: /product/cookie . So you can pass parameters to your Flask route, can you pass numbers? The example here creates the route /sale/<transaction_id> , where transaction_id is a number.

How can I use the same route for multiple functions in Flask?

In some cases you can reuse a Flask route function for multiple URLs. Or you want the same page/response available via multiple URLs. In that case you can add a second route to the function by stacking a second route decorator to the function.


2 Answers

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
like image 90
davidism Avatar answered Sep 29 '22 10:09

davidism


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)
like image 34
lord63. j Avatar answered Sep 29 '22 10:09

lord63. j