美文网首页
(技术)Python 3 Flask中的session

(技术)Python 3 Flask中的session

作者: 点映文艺 | 来源:发表于2017-12-15 15:11 被阅读0次
# 引入Flask类,Flask类实现了一个WSGI应用
from flask import Flask, render_template, session, current_app
import time

# 获取Flask的实例,它接收包或者模块的名字作为参数,但一般都是传递__name__
app = Flask(__name__)

# 进入首页
@app.route('/',methods=['GET'])
def index():
    session['user'] = 'tom'
    return render_template('index.html')

'''
app_context_processor作为一个装饰器修饰一个函数,称作上下文处理器,
借助app_context_processor我们可以让所有自定义变量在模板中可见
函数的返回结果必须是dict,届时dict中的key将作为变量在所有模板中可见
'''
@app.context_processor
def appinfo():
    print('session中数据:   ', session['user'])  # session中数据:    tom
    return dict(appname=current_app.name)

@app.context_processor
def get_current_time():
    print('session中数据:   ', session['user'])  # session中数据:    tom
    def get_time(timeFormat="%b %d, %Y - %H:%M:%S"):
        return time.strftime(timeFormat)
    return dict(current_time=get_time)


'''
app.secret_key 不能少,否则会报下述错误
raise RuntimeError('The session is unavailable because no secret '
'''
app.secret_key = '123456'

if __name__ == '__main__':
    app.run(debug=True)



html文件,注意模板文件必须放在项目的子目录templates文件夹中

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Flask Session 示例</title>
</head>
<body>

<p>请求路径: {{ request.url }}</p>

<p>session中的数据: {{ session.user }}</p>

<p>当前应用名(说文件名应该更准确) is: {{ appname }}</p>

<p>当前时间 is: {{ current_time() }}</p>

<p>格式化当前时间 is: {{ current_time("%Y-%m-%d") }}</p>

</body>
</html>









相关文章

网友评论

      本文标题:(技术)Python 3 Flask中的session

      本文链接:https://www.haomeiwen.com/subject/iqldwxtx.html