2015-09-27 35 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