Emily Hannan
Emily Hannan

Reputation: 21

Flask dynamic route not working - Real Python

I'm working through RealPython and I'm having trouble with the flask dynamic route.

Everything seemed to work until the dynamic route. Now if I try to enter a "search query" (i.e. localhost:5000/test/hi) the page is not found. localhost:5000 still works fine.

# ---- Flask Hello World ---- #

# import the Flask class from the flask module
from flask import Flask

# create the application object
app = Flask(__name__)


# use decorators to link the function to a url
@app.route("/")
@app.route("/hello")
# define the view using a function, which returns a string
def hello_world():
    return "Hello, World!"

# start the development server using the run() method
if __name__ == "__main__":
    app.run()


# dynamic route
@app.route("/test/<search_query>")
def search(search_query):
    return search_query

I can't see that other people using RealPython have had an issue with the same code, so I'm not sure what I'm doing wrong.

Upvotes: 1

Views: 12302

Answers (2)

Seetharaman S
Seetharaman S

Reputation: 11

Try using the entire URL instead of just the IP address.

Upvotes: 1

Nafiul Islam
Nafiul Islam

Reputation: 82600

The reason why this is not working is because flask never learns that you have another route other / and /hello because your program gets stuck on app.run().

If you wanted to add this, all you need to do would be to add the new route before calling app.run() like so:

# ---- Flask Hello World ---- #

# import the Flask class from the flask module
from flask import Flask

# create the application object
app = Flask(__name__)


# use decorators to link the function to a url
@app.route("/")
@app.route("/hello")
# define the view using a function, which returns a string
def hello_world():
    return "Hello, World!"

# dynamic route
@app.route("/test/<search_query>")
def search(search_query):
    return search_query

# start the development server using the run() method
if __name__ == "__main__":
    app.run(host="0.0.0.0", debug=True, port=5000)

Now this will work.

Note: You don't need to change the run configurations inside of app.run. You can just use app.run() without any arguments and your app will run fine on your local machine.

enter image description here

Upvotes: 9

Related Questions