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
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.
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With