【Flask项目2】登录拦截器的使用和退出登录的接口开发(14)

comment—utils—》decorators.py

自定义一个装饰器,如果登录了继续访问。如果没有登录直接返回(不能继续访问)

from flask import g

def login_required(func):
	def wrapper(*args,**kwargs):
		if g.user_id is not None:
			return func(*args,**kwargs)
		else:
			return {'message':'用户没有登录,不能访问'}
	return wrapper

financial—》resource—》user—》user_resource.py
退出登录接口开发

from comment.utils.decorators import login_required

class LoginOut(Resource):
	'''
	退出登录
	'''
	#使用登录拦截的装饰器,post方法加上了登录拦截,因为前提必须登录后,才能退出登录
	
	method_decorators=[login_required]
	def post(self):
		if g.user_id:
			g.user_id=None
		return {'msg':'成功推迟登录'}
	

蓝图中加载资源

financial—》resource—》user—》init.py

#登录退出的资源
user_api.add_resource(LoginOut,'/loginOut',endpoint='loginOut')

使用了登录拦截的装饰器,资源类中的3个视图函数都加上了登录拦截

class Test(Resource):
	
	method_decorators = [login_required]

	def post(self):
	 	pass
	
	def get(self):
	 	pass
	
	def put(self):
	 	pass

使用了登录拦截的装饰器,在指定的视图方法下加登录拦截,post、get方法加上了登录拦截

class Test(Resource):
	
	method_decorators = {
		'post':[login_required],
		'get':[login_required]
	}

	def post(self):
	 	pass
	
	def get(self):
	 	pass
	
	def put(self):
	 	pass
  • 8
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

敲代码敲到头发茂密

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值