Flask 装饰器

本文探讨了Flask框架中装饰器的使用,特别是在遇到wrapper()函数导致异常的情况时,解析了错误原因并提供了相应的解决策略。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

from functools import wraps

from flask import session, redirect, url_for

# 登录限制的装饰器
def login_required(func):

	@wraps(func)
	def wrapper(*args,**kwargs):
		if session.get['user_id']:
			return func(*args,**kwargs)
		else:
			return redirect(url_for('login'))
	return wrapper()

使用wrapper()时,报异常

Traceback (most recent call last):
  File "D:/developer/pycharm/project/myapp/myapp.py", line 15, in <module>
    @login_required
  File "D:\developer\pycharm\project\myapp\decorators.py", line 23, in login_required
    return wrapper()  #不能return wrapper()
  File "D:\developer\pycharm\project\myapp\decorators.py", line 19, in wrapper
    if session.get['user_id']:
  File "E:\workspace\virtualenv\venv2\lib\site-packages\werkzeug\local.py", line 347, in __getattr__
    return getattr(self._get_current_object(), name)
  File "E:\workspace\virtualenv\venv2\lib\site-packages\werkzeug\local.py", line 306, in _get_current_object
    return self.__local()
  File "E:\workspace\virtualenv\venv2\lib\site-packages\flask\globals.py", line 37, in _lookup_req_object
    raise RuntimeError(_request_ctx_err_msg)
RuntimeError: Working outside of request context.

This typically means that you attempted to use functionality that needed
an active HTTP request.  Consult the documentation on testing for
information about how to avoid this problem.
正确写法:

from functools import wraps

from flask import session, redirect, url_for

# 登录限制的装饰器
def login_required(func):

	@wraps(func)
	def wrapper(*args,**kwargs):
		if session.get['user_id']:
			return func(*args,**kwargs)
		else:
			return redirect(url_for('login'))
	return wrapper




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值