[07] [Flask 快速上手笔记] 06. Cookie and Session

Cookies

要使用 cookies 可以使用 cookies 属性

设定 cookie

透过 set_cookie 方法

from flask import make_response

@app.route('cookie/set/')
def index():
    resp = make_response('Setting cookie!')
    resp.set_cookie('username', '')
    return resp

可以看到我们设定了一个叫做username内容是the username的 cookie

读取 cookie

透过 get 方法取得 cookie 内容

@app.route('/cookie/get/')
def cookie_get():
    username = request.cookies.get('username')
    # use cookies.get(key) instead of cookies[key] to not get a
    # KeyError if the cookie is missing.
    return f'cookie username = {username}'

删除 cookie

只需要把 cookie 的expires设为 0 就自动删除了!


Session

在使用 session 之前需要设定一组密钥作为加密使用
好的密钥应该是随机产生,可以使用指令产生一组随机的字串作为密钥

python -c 'import os; print(os.urandom(16))'
from flask import session, redirect, url_for

# Set the secret key to some random bytes. Keep this really secret!
app.secret_key = b'_5#y2L"F4Q8z\n\xec]/'

@app.route('/session/')
def session_index():
    if 'username' in session:
        return f'Logged in as {session["username"]}'
    return 'You are not logged in'

@app.route('/session/login/', methods=['GET', 'POST'])
def session_login():
    if request.method == 'POST':
        session['username'] = request.form['username']
        return redirect(url_for('session_index'))
    return '''
        <form method="post">
            <p><input type=text name=username>
            <p><input type=submit value=Login>
        </form>
    '''

@app.route('/session/logout/')
def session_logout():
    # remove the username from the session if it's there
    session.pop('username', None)
    return redirect(url_for('session_index'))

流程展示

一开始进入画面,因为我们的 session 里面没有 username 这个键值
所以显示尚未登入

使用 GET 方法存取了 login 页面,显示表单内容

按下按钮後发送 POST 请求到当前页面
路由判断是 POST 请求,建立 session 并且重新跳转到初始画面
而初始画面这次就有取得 session 中的 username 键值,所以显示对应的值

在 /logout/ 路由中,使用session.pop()删除指定的 session
那个None是什麽意思呢?如果 session key 不存在会引发 KeyError
而给他一个 None 作为预设值的话就可以避免这个问题

因为 Session 这个类别是一种 Dict 型别:dict.pop()
pop(key[, default]) 当 key 存在的时候会移除他并且回传内容
若是不存在则回传 default 内容,如果这时候 default 不存在就会引发 KeyError


<<:  MySQL学习_Day5

>>:  @Day21 | C# WixToolset + WPF 帅到不行的安装包 [Log在哪边查询]

Day26 React Router useLocation

useLocation 函数是当 URL 网址改变时useState()会返回一个新的包含有关目前U...

Day 15:更多开源专案

JUCE 在「声音处理」领域的知名度高,除了 GUI 元件可高度客制化,最重要的是 JUCE 提供的...

#4-图片资讯藏起来!(Hover图片&CSS Filter, Rotation)

前几天都比较专注在文字上的CSS动态,今天就来看看图片的吧! 比起一堆文字,放图片绝对能够说个好故事...

qpushbutton 不同的字不同大小和顔色

由於不同的字用不同的样式,所以需要用到html来设定: //add take buttons wit...

Day 28 品质分数等於产品绩效吗?

我们在之前的分享中得知,品质分数多少会影响自然排序的表现,但很多人会把它和绩效挂上等号,这并不是必然...