Skip to content Skip to sidebar Skip to footer

Passing Variables Through Url To A Flask App

Well i've this in my flask app : @app.route('/changeip/') def change_ip(ip) : return ip Now if i invoke it like : http://127.0.0.1:5000/changeip?ip=1.2.2.2 It spit

Solution 1:

The first route describes a url with a value as part of the url. The second url describes a route with no variables, but with a query parameter in the url.

If you are using the first route, the url should look like http://127.0.0.1/changeip/1.2.2.2.

If you are using the second url, the route should look like /changeip, the function should be def change_ip():, and the value should be read from request.args['ip'].

Usually the route should describe any arguments that should always be present, and form or query params should be used for user-submitted data.

Solution 2:

You should use:

app.route('/something/<ip>')
def function(ip):

And when you are using url_for, you should pass value of ip aswell:

url_for('function', ip='your_ip_address')

Solution 3:

The accepted answer is correct, but I wanted to add the method that it appears the OP was originally trying in his http request.

Another way to pass in variables is through the question mark that separates variables in the url, and using requests.

import requests

Then in the method,

@app.route("/changeip")
def change_ip():
    return requests.args.get('ip', '')

For the url, you pass the variable in using the question mark delimiter, the way you were originally trying.

http://127.0.0.1:5000/changeip?ip=1.2.2.2

Post a Comment for "Passing Variables Through Url To A Flask App"