我正在使用 RealPython,但在使用 Flask 动态路由时遇到了问题。
一切似乎都在工作,直到动态路线。现在,如果我尝试输入“搜索查询”(即 localhost:5000/test/hi),则找不到该页面。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
Run Code Online (Sandbox Code Playgroud)
我看不到使用 RealPython 的其他人对相同的代码有问题,所以我不确定我做错了什么。
这不起作用的原因是,flask 永远不会知道您还有另一条路线 other/并且/hello因为您的程序卡住了app.run()。
如果你想添加这个,你需要做的就是在调用之前添加新路由,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)
Run Code Online (Sandbox Code Playgroud)
现在这将起作用。
注意:您不需要更改
app.run. 您可以app.run()不带任何参数使用,您的应用程序将在您的本地机器上正常运行。
| 归档时间: |
|
| 查看次数: |
9412 次 |
| 最近记录: |