1

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.

3
  • So did you put the dynamic route after app.run()? Commented Sep 27, 2015 at 6:41
  • Well, your code can works good at here. localhost:5000/test/hi, localhost:5000 or localhost:5000/hello will return the correct string and I didn't get a 404 error. Commented Sep 27, 2015 at 6:58
  • It worked after restarting my computer. Commented Sep 27, 2015 at 7:09

2 Answers 2

9

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

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

Comments

1

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

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.