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
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