欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Flask中session和cookies的使用

程序员文章站 2022-05-11 23:14:41
...

from flask import Flask,render_template,redirect,request,make_response,session
from flask_sqlalchemy import SQLAlchemy
app=Flask(name)
app.config[‘SECRET_KEY’]=‘asdfghhjfh4555555555555555555555djskahfjdahjfhdjsafh///////////jsfh’
@app.route(’/’,methods=[‘GET’,‘POST’])
def index(name):
# setcookies
if name==‘c’:
resp=make_response(‘tiancookiesok’)
resp.set_cookie(‘uname’,‘jiack’,606024*365)
return resp
elif name==‘a’:
return ‘%s’%request.cookies.get(‘uname’,’’)
elif name==‘b’:
session[‘uname’]=‘zhangsan’

    return 'set ok'
elif name=='g':
    uname=session.get('uname','')
    if uname:
        return '%s'%uname
    else:
        return 'not ok'
elif name=='d':
    return render_template('longgin.html')
elif name=='index':
    return 'firstweb'
elif name=='login':
    if request.method=='GET':
        if 'uname' in session:
            return render_template('longgin.html')
        else:
            if 'uname' in request.cookies:
                uname=request.cookies.get('uname','')
                session['uname']=uname
                return render_template('longgin.html')
            else:
                return render_template('longgin.html')

    else:
        uname=request.form.get('uname','')
        upwd=request.form.get('upassword','')
        if uname=='admin' and upwd=='admin':
            #
            resp=redirect('/login')
            #     现将数据保存到session
            session['uname']=uname
            if 'remember' in request.form:
                resp.set_cookie('uname',uname,60*60*24)
        else:
            return render_template('longgin.html')

if name == ‘main’:
app.run(debug=True,port=5001)

################################

Title

用户名称:

用户密码:

记住密码

相关标签: flas cookies