【问题标题】:Flask dynamic route not working - Real PythonFlask 动态路由不起作用 - 真正的 Python
【发布时间】:2015-09-27 06:37:49
【问题描述】:

我正在使用 RealPython,但在烧瓶动态路由方面遇到了问题。

在动态路由之前,一切似乎都正常。现在,如果我尝试输入“搜索查询”(即 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

我看不到其他使用 RealPython 的人在使用相同的代码时遇到过问题,所以我不确定我做错了什么。

【问题讨论】:

  • 那么你把动态路由放在app.run()之后了吗?
  • 好吧,你的代码在这里可以很好地工作。 localhost:5000/test/hilocalhost:5000localhost:5000/hello 将返回正确的字符串,我没有收到 404 错误。
  • 重启电脑后就可以了。

标签: python flask


【解决方案1】:

这不起作用的原因是因为flask永远不会知道你有其他路线//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)

现在这将起作用。

注意:您无需更改 app.run 内部的运行配置。您可以直接使用 app.run() 而不使用任何参数,您的应用程序将在您的本地计算机上正常运行。

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2017-09-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-01
      • 2018-08-15
      • 1970-01-01
      • 2018-11-08
      • 2022-06-11
      相关资源
      最近更新 更多