Flask中session和cookies的使用

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',60*60*24*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)


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

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="/login" method="post">
    <p>
        用户名称:<input type="text" name="uname">
    </p>
    <p>
        用户密码:<input type="password" name="upassword">
    </p>
    <p>
        <input type="checkbox" name="remember">记住密码
    </p>
    <p>
        <input type="submit" value="登录">
    </p>
</form>

</body>
</html>

你可能感兴趣的:(flask)