简体   繁体   English

Flask 动态路由不起作用 - 真正的 Python

[英]Flask dynamic route not working - Real Python

I'm working through RealPython and I'm having trouble with the flask dynamic route.我正在使用 RealPython,但在使用 Flask 动态路由时遇到了问题。

Everything seemed to work until the dynamic route.在动态路线之前,一切似乎都有效。 Now if I try to enter a "search query" (ie localhost:5000/test/hi) the page is not found.现在,如果我尝试输入“搜索查询”(即 localhost:5000/test/hi),则找不到该页面。 localhost:5000 still works fine. localhost:5000 仍然可以正常工作。

# ---- 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.我看不到使用 RealPython 的其他人在使用相同代码时遇到了问题,所以我不确定我做错了什么。

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() .这不起作用的原因是,flask 永远不会知道您有另一条//hello路由,因为您的程序卡在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:如果你想添加这个,你需要做的就是调用app.run()之前添加新路由如下所示:

# ---- 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 .注意:您不需要更改app.run的运行配置。 You can just use app.run() without any arguments and your app will run fine on your local machine.您可以不带任何参数使用app.run() ,您的应用程序将在您的本地机器上正常运行。

在此处输入图片说明

尝试使用整个 URL 而不仅仅是 IP 地址。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM