Flask Cookies和Sessions

Cookies保存在客户端,控制重复登录不用再输入账号密码;
Sessions保存在服务端,控制登录时长之类的;需要设置secret_key;

首页模板./templates/index.html

<html>
    <body>
        <form action = "/setcookie" method = "POST">
            <p><h3>Enter userID</h3></p>
            <p><input type = 'text' name = 'nm'/></p>
            <p><input type = 'submit' value = 'Login'/></p>
        </form>
    </body>
</html>

控制器文件IndexController.py

from flask import Flask, render_template, request, make_response, session, redirect, url_for;

app = Flask(__name__);
app.strict_slashes = False;
# 越复杂越好
app.secret_key = '123456';


@app.route('/')
@app.route('/index')
def index():
    if 'userID' in session:
        userID = session['userID'];
        return 'Logged in as ' + userID + "<br/><a href='/logout'>Click here to logout</a>";
    else:
        return render_template('index.html');


@app.route('/setcookie', methods = ['POST', 'GET'])
def setcookie():
    if request.method == 'POST':
        user = request.form['nm'];
        # 设置session
        session['userID'] = user;

        # 设置cookie
        resp = make_response("登录成功<br/><a href='/getcookie'>Click here to read cookie</a>");
        # resp = make_response(render_template('readcookie.html'));
        resp.set_cookie('userID', user);

        return resp;

@app.route('/getcookie')
def getcookie():
    name = request.cookies.get('userID')
    return '<h1>welcome '+name+'</h1>'

@app.route('/logout')
def logout():
    # 删除session
    session.pop('userID', None)
    return redirect(url_for('index'))


if __name__ == '__main__':
    app.run('0.0.0.0', 8080, debug = True);

运行

$ python IndexController.py
Running on http://0.0.0.0:8080/ (Press CTRL+C to quit)

使用浏览器访问

http://127.0.0.1:8080/

参考
https://www.tutorialspoint.com/flask/flask_cookies.htm

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值