1. 程式人生 > >flask入門--搭建一個Flask程式

flask入門--搭建一個Flask程式

新建一個HelloWorld.py

# 匯入Flask類
from flask import Flask,render_template,abort,redirect
# Flask函式接收一個引數name,它會指向程式所在的模組
app=Flask(__name__)

# 裝飾器的作用是將路由對映到檢視函式welcome
@app.route('/')
def welcome():
    return '歡迎介面'

# 給路由傳參示例 <>尖括號表示變數是引數
@app.route('/hello')
@app.route('/hello/<name>')
def hello_flask(name=None):
    return render_template('hello.html',name=name)

# 重定向和錯誤處理
@app.route('/check1')
def index():
    # 重定向到/check2頁面
    return redirect("/check2")

@app.route('/check2')
def f_check():
    # 立刻向客戶端傳送401錯誤
    abort(401)
    # 這裡的程式碼不會執行
    # dont_coding_here()

# Flask應用程式例項的run方法啟動WEB伺服器
if __name__=='__main__':
    app.run()
    # app.run(host='0.0.0.0',port=80,debug=False)

新建一個templates資料夾,在資料夾中新建一個hello.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Hello from Flask</title>
</head>
<body>
{% if name %}
    <h1>Hello {{ name }}!</h1>
{% else %}
    <h1>Hello World!</h1>
{% endif %}
</body>
</html>

執行HelloWorld.py

在瀏覽器中開啟網址:  http://127.0.0.1:5000/

在瀏覽器中開啟網址:  http://127.0.0.1:5000/hello

在瀏覽器中開啟網址:  http://127.0.0.1:5000/hello/python

在瀏覽器中開啟網址:  http://127.0.0.1:5000/check1  頁面會重定向到check2頁面