python bottle开发实例-用python web框架 bottle 开发网站(四)

在第三节我们熟悉并编写了用户登录逻辑,这一节我们要实现用户状态保持,就是判断用户当前的登录状态,我们用加密cookie的方式来实现,在bottle中用response.set_cookie()和requests.get_cookie()来写入和读取用户cookie,非常简单,让我们在5分钟内实现它。

from bottle import run,route,template,request,response

from user import read_user

@route('/login', method = 'GET')

def index():

username = request.get_cookie('username', secret = 'usafe')

password = request.get_cookie('password', secret = 'psafe')

if read_user(username, password):

return '你已经登录'

return template('login')

@route('/login', method = 'POST')

def index():

username = request.forms.get('username')

password = request.forms.get('password')

if read_user(username, password):

response.set_cookie('username', username, secret = 'usafe', httponly = True, max_age = 600)

response.set_cookie('password', password, secret = 'psafe', httponly = True, max_age = 600)

return '登录成功'

return '账号密码错误'

run(host = 'localhost', port = 80, debug = True, reloader = True)

解释:

request.get_cookie('username', secret = 'usafe')是获取用户客户端的加密cookie,然后用自定义的安全字符串usafe来解密,获取username。

request.get_cookie('password', secret = 'psafe')是获取用户客户端的加密cookie,然后在服务端解密password。

response.set_cookie('username', username, secret = 'usafe', httponly = True, max_age = 600)是写入用户浏览器cookie,把username这个变量用安全字符串usafe加密,httponly指不允许通过javascript获取cookie,降低用户信息泄露风险,max_age = 600指这个cookie的有效期为600秒,600秒后就会过期,用户需要重新登录。

你可能会疑惑,这种方式安全吗?

首先并不是说cookie放到客户端就一定是不安全的,对于一些在服务端多次加salt然后用RSA加密方式加密,最后放到客户端的cookie安全性还是比较高的,也就是说Cookie != 不安全。在bottle中并不推荐我们使用把敏感信息放到cookie中的做法。

8556eaf6f694

image.png

也就是说bottle的cookie并没有经过强加密,我们只是用cookie实现用户登录状态的保持,想要安全?你可以自己写加密函数,把敏感信息加密后再放到cookie。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值