flask中自带session实现登录、校验登录、退出登录小案例
from flask import Flask, abort, request, jsonify, session
app = Flask(__name__)
app.secret_key = "kfdsjfjfkdslfjksd"
@app.route("/")
def hello():
return "hello"
@app.route("/login", methods=["POST"])
def login():
"""
帐号 username test
密码 password test001
:return:
"""
username = request.json.get("username")
password = request.json.get("password")
if not all([username, password]):
return jsonify(msg="参数不完整")
if username == "test" and password == "test001":
session["username"] = username
return jsonify(msg="登录成功!")
else:
return jsonify(msg="帐号或者密码错误")
@app.route("/check_session", methods=["GET"])
def check_session():
username = session.get("username")
print(session)
if username is not None:
return jsonify(username=username)
else:
return jsonify(msg="出错了,没登录")
@app.route("/logout", methods=["GET"])
def logout():
session.clear()
return jsonify(msg="退出成功")
if __name__ == '__main__':
app.run()
Flask Session储存在redis
from flask import Flask, session
from flask_session import RedisSessionInterface
from redis import Redis
from flask_session import Session
from datetime import timedelta
import os
app = Flask(__name__)
app.config['SESSION_TYPE'] = 'redis'
app.config['SESSION_REDIS'] = Redis(
host='127.0.0.1',
port=6379)
app.config['SESSION_USE_SIGNER'] = True
app.config['SECRET_KEY'] = os.urandom(24)
app.config['SESSION_PERMANENT'] = False
app.config['PERMANENT_SESSION_LIFETIME'] = 3600
Session(app)
@app.route('/n1')
def n1():
session["k2"] = "admina"
return "n1"
@app.route('/n2')
def n2():
print(session["k2"])
return "n2"
if __name__ == '__main__':
app.wsgi_app
app.run(debug=True)