2015-09-27 79 views
0

我正在通过RealPython工作,我遇到烧瓶动态路线的问题。烧瓶动态路线不工作 - 真正的Python

一切似乎工作,直到动态路线。现在,如果我尝试输入“搜索查询”(即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的其他人有相同的代码的问题,所以我不知道我做错了什么。

+0

那你有没有把动态路由后'app.run()'? –

+0

那么,你的代码可以在这里很好用。 'localhost:5000/test/hi','localhost:5000'或'localhost:5000/hello'会返回正确的字符串,我没有收到404错误。 –

+0

它重新启动我的电脑后工作。 –

回答

2

这是不工作的原因是因为烧瓶永远不会知道您有其他路线,其他//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(),而无需任何参数,并且您的应用可以在本地计算机上正常运行。

enter image description here