天天看点

用flask开发个人博客(4)—— flask中4种全局变量

一  current_app

        current_app代表当前的flask程序实例,使用时需要flask的程序上下文激活,我们以本专栏第一篇文章中写的test.py为例介绍下它的用法:

1.1 激活程序上下文

>>> from test import app
>>> from flask import current_app
>>> from flask import g
>>> ctx=app.app_context()
>>> ctx.push()
           

        app.app_context()为flask程序的上下文,简单说来就是flask程序需要运行的环境变量等等.ctx.push()是激活上下文的操作,类似的,如果我们想要回收上下文,用ctx.pop()

1.2 打印当前程序名称

>>> current_app.name
'test'
           

二  g变量

        g作为flask程序全局的一个临时变量,充当者中间媒介的作用,我们可以通过它传递一些数据,下面的例子,通过g传递了一个名字叫做"Hyman",使用g之前也需要激活程序上下文:

>>> g.name='Hyman'
>>> g.name
'Hyman'
           

三 request对象

        请求对象,封装了客户端发送的HTTP请求的内容.可参照<<用flask开发个人博客(2)—— Flask中的请求对象request>>  .

四 session

        用户会话,用来记住请求(比如前后一个GET请求和一个POST请求)之间的值,从数据格式上来说它是字典类型。它存在于连接到服务器的每个客户端中,属于私有存储,会保存在客户端的cookie中。如下面的代码,用于重定向url:

@app.route('/', methods=['GET','POST'])
def index():
    form = NameForm()
    if form.validate_on_submit():
        session['name']=form.name.data
        return redirect(url_for('index'))
    renturn render_template('index.html',form=form,name=session.get('name'))
           

继续阅读