6

I started learning Flask framework recently and made a short program to understand request/response cycle in flask.

My problem is that last method called calc doesn't work.

I send request as:

http://127.0.0.1/math/calculate/7/6

and I get error:

"Not Found: The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again."

Below is my flask app code:

from flask import Flask
app = Flask(__name__)

@app.route('/')
def index():
    return "<h1>Hello, World!</h1>"

@app.route('/user/<name>')
def user(name):
    return '<h1>Hello, {0}!</h1>'.format(name)

@app.route('/math/calculate/<string:var1>/<int:var2>')
def calc(var1, var2):
    return  '<h1>Result: {0}!</h1>'.format(int(var1)+int(var2))

if __name__ == '__main__':
      app.run(host='0.0.0.0', port=80, debug=True)
3
  • 2
    Why are you trying to grab var1 as a string? Have you tried it with <int:var1> ? Commented Dec 16, 2018 at 7:49
  • 3
    The following is working for me: @app.route('/math/calculate/<int:var1>/<int:var2>') def calculate(var1,var2): return '<h1>Result %s</h1>' % str(var1+var2) Commented Dec 16, 2018 at 7:55
  • @DavidScottIV Thanks man it is working. But My real intent is : 127.0.0.1:8081/math/calculate/?var1=4&var2=5 how can I do that? Commented Dec 16, 2018 at 8:31

1 Answer 1

6

To access request arguments as described in your comment you can use the request library:

from flask import request

@app.route('/math/calculate/')
def calc():
    var1 = request.args.get('var1',1,type=int)
    var2 = request.args.get('var2',1,type=int)
    return '<h1>Result: %s</h1>' % str(var1+var2)

The documentation for this method is documented here:

http://flask.pocoo.org/docs/1.0/api/#flask.Request.args

the prototype of the get method for extracting the value of keys from request.args is:

get(key, default=none, type=none)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.