python - 在函数内调用 return 时如何中断 Python Flask Controller 流程?

标签 python rest flask

我正在使用 Python Flask,并且定义了以下函数:

def verify_session():

    if not 'logged_in' in session:
        flash("You are not logged in.<br/>Please, log in to use our application.", "warning")
        return redirect(url_for('login_path'))

这应该在每个 Controller 中调用。我知道我可以使用 @app.before_request 但在某些地方我不希望调用此函数(例如,在同一个登录页面中)并且我真的不希望该函数检查排除的内容路径。

我的问题是这样的:在每个路径的任何 Flask Controller 中,第一行看起来像这样:

@app.route('/web/account', methods=["GET"], endpoint="account_path")
def account():
    verify_session()
    return render_template('account')

但是,尽管我收到“您需要登录”的闪烁消息,它仍然返回帐户页面,因为 verify_session 中的 return 只是返回此函数。

我需要的是类似 return verify_session() 的东西,但这不会结束 Controller 流程,除非实际上有必要返回它。

也许这个问题只是 Python/编程特定的而不是 Flask,所以我原谅自己并要求版主相应地编辑我的问题。我提到 Flask 是因为我在这个环境中遇到了麻烦。

如果需要更多信息,我愿意更新。预先感谢您。

最佳答案

result = verify_session()
if not result:
   result = render_template("account")
return result

但实际上你应该为此使用装饰器

def verify_session(fn):
  def inner(*args,**kwargs):
    if not 'logged_in' in session:
        flash("You are not logged in.<br/>Please, log in to use our application.", "warning")
        return redirect(url_for('login_path'))
    return fn(*args,**kwargs)
  return inner

然后你会像这样使用它

@app.route('/web/account', methods=["GET"], endpoint="account_path")
@verify_session  #make sure to use any decorators after the route decorator
def account():
    return render_template('account')

最后......我希望你意识到你正在重新发明轮子,你可能应该使用flask-login来管理这些东西(除非你有一个非常令人信服的理由不这样做)

关于python - 在函数内调用 return 时如何中断 Python Flask Controller 流程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30199562/

相关文章:

python - Python 是否与 QML(Qt-Quick)配合得很好?

python - 如何自动化 Python Dash 应用程序数据拉取?

Python:将多列转换为具有分类数据的单列

http - HTTP 中的 POST 和 PUT 有什么区别?

python - uWSGI应用程序找不到挂载点,但加载了html

python - Viewset 的 Django 更新方法即使在覆盖后仍返回 415

spring - Jersey ExceptionMapper 不映射异常

javascript - 如何在REST中有效地更新复杂的大对象?

python - 无法在 Twisted Web 服务器上运行 Flask,WSGI 应用程序错误

python - flask.ext.script 已弃用