flask的兩種巧妙封裝形式

2022-05-08 15:18:12 字數 1290 閱讀 1939

1,使用裝飾器來封裝登入驗證!

'''

functools.wraps(fn) 使得呼叫裝飾器的時候能改為自己原來的名字

使用裝飾器,增加了驗證的功能!必須這樣設定,因為不設定所有使用這個裝飾器的都會改成一樣的名字!

'''def

user_show(fn):

@functools.wraps(fn)

user_id = session.get('

user_id')

#在這裡設定預設為 none是為了下面沒有session記錄時候,以none執行!

user =none

ifuser_id:

try:

user =user.query.get(user_id)

except

exception as e:

#g 變數的生命週期只是乙個請求的週期

g.user =user

return fn(*args, **kwargs)

裝飾器的使用!

from info.utils.common import

user_show

@news_blue.route('/

')@user_show

defget_news_detail(news_id):

user =g.user

pass

2,巧妙的生成資料庫物件的屬性!在模型類之中定義 to_dict() 方法生成物件屬性的字典!

def

to_dict(self):

resp_dict =

return resp_dict

在檢視之中直接使用 to_dict() 方法

paginates = news.query.filter(*filter).order_by(news.create_time.desc()).paginate(page, per_page, false)

#獲取分頁的每一條資料!

new_model_list =paginates.items

#總頁數

total_page =paginates.pages

#當前頁數

current_page =paginates.page

news_dict_li =

for new in

new_model_list:

data =

return jsonify(errno=ret.ok, errmag='

ok', data=data)

C C 的兩種多型形式

1 2 test.cpp4 5 created by mac on 15 8 11.6 7 8 include9 include10 using namespace std 11class person 基類person12 25person person 26 person person stri...

include的兩種指令形式

在程式設計過程中不在意的細節 搬運於c程式設計 include include stdio.h include使用尖括號的形式時,編譯系統從存放c編譯系統的子目錄中去找所要包含的檔案如 stdio.h 這稱為 標準方式 若使用 include指令是為了使用系統庫函式,因而要包含系統提供的相應標頭檔案...

寫出Singleton的兩種形式

public class test01singleton 餓漢式 class singleton1 private static singleton1 instance1 newsingleton1 加靜態是因為要被靜態呼叫 public static singleton1 getinstance ...