【校招VIP】出品:普通校招java職位之Spring框架
阿新 • • 發佈:2022-05-19
1.hello word示例
from flask import Flask app = Flask(__name__) @app.route('/') def hello_world(): return 'Hello World!' if __name__ == '__main__': app.run(port='5001')
app.run(host, port, debug, options)
引數 說明 預設值
host 主機名,設定為“0.0.0.0”以使伺服器在外部可用 127.0.0.1(localhost)
port 埠號 5000
debug 除錯模式,程式碼更新會自動重啟服務,提供一個偵錯程式來跟蹤應用程式中的錯誤 False
options 要轉發到底層的Werkzeug伺服器的引數
注:pycharm中修改host和port
2.路由
現代Web框架使用路由技術來幫助使用者記住應用程式URL。Flask中的route()裝飾器用於將URL繫結到函式,例如:
@app.route('/hello') def hello_world(): return 'hello world'
URL /hello
規則繫結到hello_world()函式,如果訪問http://localhost:5000/hello,hello_world()函式的輸出將在瀏覽器中呈現。
3.變數規則
通過把 URL 的一部分標記為 <variable_name>
就可以在 URL 中新增變數,標記的部分會作為關鍵字引數傳遞給函式。
from flask import Flask app = Flask(__name__) @app.route('/hello/<username>') def hello(username): return f'Hello {username}!' if __name__ == '__main__': app.run(debug = True)
在上面的例子中,在瀏覽器中輸入http://localhost:5000/hello/Kint,則Kint
將作為引數提供給 hello()函式,即username的值為Kint
。在瀏覽器中的輸出如下
Hello Kint!
通過使用 <converter:variable_name>
轉換器 | 說明 |
---|---|
string |
(預設值) 接受任何不包含斜槓的文字 |
int |
接受正整數 |
float |
接受正浮點數 |
path |
類似 string ,但可以包含斜槓 |
from flask import Flask from markupsafe import escape app = Flask(__name__) @app.route('/hello/<username>') def hello(username): return f'Hello {username}!' @app.route('/post/<int:post_id>') def show_post(post_id): return f'Post {post_id}' @app.route('/path/<path:path>') def show_path(path): return f'path {escape(path)}' if __name__ == '__main__': app.run(debug=True)