zoukankan      html  css  js  c++  java
  • Flask-1-05-Cookie&Session

    接下来我会演示一下设置Cookie 读取Cookie 删除Cookie,以及添加Cookie的原理

     接下来我们分别定义3个视图为 set_cookie、get_cookie、del_cookie

    # coding:utf-8
    
    from flask import Flask, make_response, request
    
    app = Flask(__name__)
    
    @app.route("/set_cookie")
    def set_cookie():
        # 创建一个响应的对象
        resp = make_response('设置成功')
        # 设置cookie
        resp.set_cookie('username1', 'hannibal')
        # 设置多个cookie
        resp.set_cookie('username2', 'circle')
        # 默认的有效期是关闭浏览器之前 max_age 是手动添加有效期 单位是妙
        resp.set_cookie('username3', 'benjamin', max_age=3600)
        return resp
    
    
    @app.route("/get_cookie")
    def get_cookie():
        c = request.cookies.get('username1')
        return c
    
    
    @app.route('/del_cookie')
    def del_cookie():
      # 删除Cookie的时候也需要先创建响应对象 resp
    = make_response('del cookie') resp.delete_cookie('username3') return resp if __name__ == '__main__': app.run(host='0.0.0.0', debug=True)

    通过返回结果我们可以看出:设置了3个Cookie

    如果不指定过期时间默认是会话结束时候

    同样我们这里还有设置了一个过期时间为1小时(3600)

    当我们访问get_cookie时

     

    当我们删除Cookie时,通过结果可以看出,并没有在浏览器真正的删除了username3这个Cookie,而是帮我们把过期时间更改为了创建时间。显然这么做也是足够的

    通过上面的返回信息,我们可以看出,其实就是通过设置Cookie就是在响应头里给我们添加了一条数据而已

    其实我们就可以在响应头里自己添加一个Set-Cookie 这个键 并且按照他的格式给它赋值,原理就是这么个原理

    resp.headers["Set-Cookie"] = "username3=benjamin; Expires=Tue, 23-Jul-2019 09:49:51 GMT; Max-Age=3600; Path=/"

    Session

    session对象。它允许你在不同请求间存储特定用户的信息。它是在 Cookies 的基础上实现的,并且对 Cookies 进行密钥签名。这意味着用户可以查看你 Cookie 的内容,但却不能修改它,除非用户知道签名的密钥。

    如果你想用有一个看都看不懂的密钥,还不想自己一顿乱敲,你可以通过Python的编译器做一个密钥生成器比如下面的那个方法:

    >>> import os
    >>> os.urandom(24)
    'ux8a
    x9bx89xad7//xd6x9ax19	xdb3Ax92xbaCNxeexc8x-'

    把这个值复制粘贴进你的代码中,你就有了强壮而且看似专业的密钥

    下面将用一个简单的例子来了解session的基本应用方法:

    # coding:utf-8
    from flask import Flask, session, redirect, url_for, escape, request
    import sys
    
    reload(sys)
    sys.setdefaultencoding('utf8')
    
    app = Flask(__name__)
    # 设置密钥 这个是必须要有的否则会抛出一个RuntimeError
    app.config['SECRET_KEY'] = 'ux8a
    x9bx89xad7//xd6x9ax19	xdb3Ax92xbaCNxeexc8x-'
    
    
    @app.route('/')
    def index():
        if 'username' in session:
            print(session['username'])
            return '欢迎 %s 登陆' % escape(session['username'])
        return '抱歉你还没有登陆'
    
    
    @app.route('/login', methods=['GET', 'POST'])
    def login():
        if request.method == 'POST':
            session['username'] = request.form['username']
            # 重定向到index页面
            return redirect(url_for('index'))
        return '''
            <form action="" method="post">
                <p><input type=text name=username>
                <p><input type=submit value=Login>
            </form>
        '''
    
    
    @app.route('/logout')
    def logout():
        # 如果有就将它删除
        session.pop('username', None)
        return redirect(url_for('index'))
    
    
    if __name__ == '__main__':
        app.run(host='0.0.0.0', debug=True)

    当你访问127.0.0.1:5000/logout就会帮你删除那个session

  • 相关阅读:
    vmvare桥接模式下无法连接网络
    netty LEAK: ByteBuf.release() was not called before it's garbage-collected
    FileOutputStream write与原文件md5不一致,文件变大了 或者 SpringMVC的 ResponseEntity 下载的文件与原文件md5值不一样
    小技巧:linux怎么查看连接的创建时间
    org.springframework.dao.QueryTimeoutException: Redis command timed out; nested exception is io.lettuce.core.RedisCommandTimeoutException: Command timed out after 300 millisecond(s)
    fastJson转换json字符串到对象中时类型为list的字段为空
    zookeeper集群搭建Exception when following the leader java.io.EOFException
    用ab测试代理程序
    centos7 配置java程序自启动
    log4j2配置模板
  • 原文地址:https://www.cnblogs.com/Hannibal-2018/p/11232824.html
Copyright © 2011-2022 走看看