亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在燒瓶中創建裝飾器?

如何在燒瓶中創建裝飾器?

元芳怎么了 2023-05-23 15:00:56
我能做些什么來替換 if 和 else。我將在幾個地方需要這個條件。@blueblue.route('/', methods=['GET', 'Post'])# def deactivate_trainer():    if current_user.is_authenticated and current_user.account_type == 'su':        form = ActivateDeactivateTrainer        return render_template('x.html', form=form)        else:        return redirect(url_for('blueblue.login'))
查看完整描述

2 回答

?
守著星空守著你

TA貢獻1799條經驗 獲得超8個贊

要在登錄時對用戶進行身份驗證,您可以這樣做:


from flask import redirect, render_template, request, session

from functools import wraps


def login_required(f):

? ? @wraps(f)

? ? def decorated_function(*args, **kwargs):

? ? ? ? if not (current_user.is_authenticated and current_user.account_type == 'su'):

? ? ? ? ? ? return redirect(url_for('blueblue.login'))

? ? ? ? return f(*args, **kwargs)

? ? return decorated_function

這為登錄用戶定義了一個單獨的裝飾器。

使用裝飾器就像包含一行簡單的代碼一樣簡單:


@blueblue.route('/', methods=['GET', 'Post'])

@login_required

def deactivate_trainer():

? ? form = ActivateDeactivateTrainer

? ? return render_template('x.html', form=form)

瞧!您不必再使用那些煩人的 if-else 條件!



查看完整回答
反對 回復 2023-05-23
?
慕婉清6462132

TA貢獻1804條經驗 獲得超2個贊

你必須functools.wraps()在燒瓶中使用它來處理

這就是我編輯你的代碼的方式:


from functools import wraps

from flask import redirect, url_for

def my_decorator(function):

? ? @wraps(function)

? ? def decorated_function(*args, **kwargs):

? ? ? ? if current_user.is_authenticated and current_user.account_type == 'su':

? ? ? ? ? ? return function(*args, **kwargs)

? ? ? ? else:

? ? ? ? ? ? return redirect(url_for('blueblue.login'))

你可以這樣使用你的裝飾器


@blueblue.route('/', methods=['GET', 'Post'])

@my_decorator

def deactivate_trainer():

? ? #...


查看完整回答
反對 回復 2023-05-23
  • 2 回答
  • 0 關注
  • 167 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號