一 Flask的基礎知識

2021-10-24 12:10:34 字數 2185 閱讀 5860

1、建立flask的核心物件:

from flask import flask

# 初始化乙個flask的核心物件

2、註冊路由的兩種方法:
# 路由註冊的兩種方法

# 可以指定請求方法

"/", methods=

["get"])

"/home"

, methods=

["get"])

defhome()

:return

"this is home page!"

deflogin()

:return

"this is login page!"

# 裝飾器和函式呼叫的形式其實就是同一邏輯

"/login"

, view_func=login)

3、啟動flask除錯伺服器的引數:
"""

host 伺服器位址,設定成0.0.0.0監聽所有區域網內機器的請求

port 埠號

debug 除錯模式,開啟後:1、修改**後自動重啟服務;2、如有異常會直接顯示在網頁上

""""127.0.0.1"

, port=

8081

, debug=

true

)

4、構造服務端響應:
4.1 返回json格式的資料

# 返回json格式的資料

headers =

return

,200

, headers

# 也可以直接使用jsonify函式返回json物件

return jsonify(

)

4.2 返回html模板

# 也可以使用多個返回值得形式返回,元祖的形式

return render_template(

"index.html"

, word=

"index"),

200, headers

# 使用render_template返回templates資料夾裡面的html檔案

4.3 返回字串

# 使用make_response來製造響應

headers =

response = make_response(

"hello index"

,200

, headers)

# 直接新增返回headers

response.headers = headers

return response

5、判斷客戶端發起的http請求型別:
# 使用methods引數,可以傳入支援的多個請求方法

"/index"

, view_func=index, methods=

["get"

,"post"

,"put"])

# 在檢視函式內部,使用requets.method屬性來判斷當前請求的方式

if request.method ==

"get"

: headers =

response = make_response(render_template(

"index.html"

, word=

"index"))

# 使用render_template返回templates裡面的html檔案

return

,200

, headers

elif request.method ==

"post"

:return jsonify(

)

6、動態匹配客戶端訪問的url:

"/r////"

)def

url_re

(name, age,

file

, f)

:return f"---"

'''# 限制位置傳參進來的引數型別

string: 字串

int: 整型

path: 路徑

float: 浮點型

'''

Flask 基礎知識(一)

flask上下文 應用上下文 當前應用的應用例項 g應用上下文 處理請求是用做臨時儲存的物件,每次請求都會重設這個變數 request 請求上下文 請求物件,封裝了客戶端發出的http請求中的內容 session 請求上下文 使用者回話,值為乙個字典,儲存請求之間需要 記住 的值 request f...

Flask基礎知識

flask渲染jinja2模板和傳參 渲染模板的方法 render template from flask import render template defhello name none return render template hello.html name name 模板例項 hello...

FLASK基礎知識

from flask import flask 初始化乙個flask物件 傳遞乙個引數 name 1.方便flask框架去尋找資源 2.方便flask外掛程式比如flask sqlalchemy出現錯誤的時候,好去尋找問題所在位置 defhello world return hello world ...