码迷,mamicode.com
首页 > 其他好文 > 详细

flask学习4-会话

时间:2015-02-12 15:58:46      阅读:215      评论:0      收藏:0      [点我收藏+]

标签:

cookie


 

from flask import Flask, render_template, request, redirect, make_response
app = Flask(__name__)

user_list = [‘wb‘, ‘valentine‘, ‘wb112232‘]
@app.route(‘/login/‘, methods=[‘GET‘,‘POST‘])
def login():
	if request.method == ‘POST‘:
		username = request.form[‘username‘]
		if username in user_list:
			response = make_response(redirect(‘/index/‘))
			response.set_cookie(‘username‘,value=username,max_age=300)
			return response
		else:
			return redirect(‘/login/‘)
	else:
		return render_template(‘login.html‘)

@app.route(‘/index/‘)
def index():
	username=request.cookies[‘username‘]
	if username:
		return render_template(‘index.html‘,username = username)
	else:
		return redirect(‘/login/‘)
	
 
if __name__ == ‘__main__‘:
    app.debug = True
    app.run()

response.setcookie(‘key‘, ‘value‘, max_age=n) n的单位为秒。

response.cookies.get[‘name‘]/response.cookies[‘name‘]获取cookie

将max_age设置为0,即为删除cookie。

Session


 生成一个

app.secret_key

import os
res = os.urandom(24)

后台

from flask import Flask, render_template, request, redirect, session
app = Flask(__name__)

app.secret_key=‘\x18\x0b6\x96\xeaP\x8d"\xc8\x04\xf6G\x8e\xae5\x0f\xf6\xe1\x89\xc1}\x04\xa3\x0c‘
user_list = [‘wb‘, ‘valentine‘, ‘wb112232‘]
@app.route(‘/login/‘, methods=[‘GET‘,‘POST‘])
def login():
	if request.method == ‘POST‘:
		username = request.form[‘username‘]
		if username in user_list:
			session[‘username‘]=username
			return redirect(‘/index/‘)
		else:
			return redirect(‘/login/‘)
	else:
		return render_template(‘login.html‘)

@app.route(‘/index/‘)
def index():
	username=session[‘username‘]
	if username:
		return render_template(‘index.html‘,username = username)
	else:
		return redirect(‘/login/‘)

@app.route(‘/logout/‘)
def logout():
	pass
	
 
if __name__ == ‘__main__‘:
    app.debug = True
    app.run()

cookie安全性差,session对服务器性能有影响,可将登陆信息存放于session

flask学习4-会话

标签:

原文地址:http://www.cnblogs.com/valentineisme/p/4287977.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!