Flask每个请求都有生命周期,在生命周期内请求有其上下文环境Request Context。作为在请求中渲染的模板,自然也在请求的生命周期内,所以Flask应用中的模板可以使用到请求上下文中的环境变量,及一些辅助函数。本文就会介绍下这些变量和函数。


标准上下文变量和函数

请求对象request

request对象可以用来获取请求的方法”request.method”,表单”request.form”,请求的参数”request.args”,请求地址”request.url”等。它本身是一个字典。在模板中,你一样可以获取这些内容,只要用表达式符号”{{ }}”括起来即可。



< p > { { request . url } } < / p >

在没有请求上下文的环境中,这个对象不可用。


会话对象session

session对象可以用来获取当前会话中保存的状态,它本身是一个字典。在模板中,你可以用表达式符号”{{ }}”来获取这个对象。


Flask代码如下,别忘了设置会话密钥哦:



@ app . route ( '/' )
def index ( ) :
     session [ 'user' ] = 'guest'
     return render_template ( 'hello.html' )
 
app . secret_key = '123456'

模板代码:



< p > User : { { session . user } } < / p >

在没有请求上下文的环境中,这个对象不可用。


全局对象g

全局变量g,用来保存请求中会用到全局内容,比如数据库连接。模板中也可以访问。


Flask代码:



@ app . route ( '/' )
def index ( ) :
     g . db = 'mysql'
     return render_template ( 'hello.html' )

模板代码:



< p > DB : { { g . db } } < / p >

g对象是保存在应用上下文环境中的,也只在一个请求生命周期内有效。在没有应用上下文的环境中,这个对象不可用。


Flask配置对象config

导入的配置信息,就保存在”app.config”对象中。这个配置对象在模板中也可以访问。



< p > Host : { { config . DEBUG } } < / p >

“config”是全局对象,离开了请求生命周期也可以访问。


url_for()函数

url_for()函数可以用来快速获取及构建URL,Flask也将此函数引入到了模板中,比如下面的代码,就可以获取静态目录下的”style.css”文件。



< link rel = "stylesheet" href = "{{ url_for('static', filename='style.css') }}" >

该函数是全局的,离开了请求生命周期也可以调用。


get_flashed_messages()函数

get_flashed_messages()函数是用来获取消息闪现的。这也是一个全局可使用的函数。


自定义上下文变量和函数

自定义变量

除了Flask提供的标准上下文变量和函数,我们还可以自己定义。下面我们就来先定义一个上下文变量,在Flask应用代码中,加入下面的函数:



from flask import current _app
 
@ app . context_processor
def appinfo ( ) :
     return dict ( appname = current_app . name )

函数返回的是一个字典,里面有一个属性”appname”,值为当前应用的名称。我们曾经介绍过,这里的”current_app”对象是一个定义在应用上下文中的代理。函数用”@app.context_processor”装饰器修饰,它是一个上下文处理器,它的作用是在模板被渲染前运行其所修饰的函数,并将函数返回的字典导入到模板上下文环境中,与模板上下文合并。然后,在模板中”appname”就如同上节介绍的”request”, “session”一样,成为了可访问的上下文对象。我们可以在模板中将其输出:



< p > Current App is : { { appname } } < / p >

自定义函数

同理我们可以自定义上下文函数,只需将上例中返回字典的属性指向一个函数即可,下面我们就来定义一个上下文函数来获取系统当前时间:


import time
 
@ app . context_processor
def get_current_time ( ) :
     def get_time ( timeFormat = "%b %d, %Y - %H:%M:%S" ) :
         return time . strftime ( timeFormat )
     return dict ( current_time = get_time )

我们可以试下在模板中将其输出:



< p > Current Time is : { { current_time ( ) } } < / p >
   < p > Current Day is : { { current_time ( "%Y-%m-%d" ) } } < / p >

上下文处理器可以修饰多个函数,也就是我们可以定义多个上下文环境变量和函数。


完整实例:


flask代码:



from flask import Flask , render_template , session , g , current_app
import time
 
app = Flask ( __name__ )
 
@ app . route ( '/' )
def index ( ) :
     session [ 'user' ] = 'guest'
     g . db = 'mysql'
     return render_template ( 'hello-2.html' )
 
@ app . context_processor
def appinfo ( ) :
     return dict ( appname = current_app . name )
 
@ app . context_processor
def get_current_time ( ) :
     def get_time ( timeFormat = "%b %d, %Y - %H:%M:%S" ) :
         return time . strftime ( timeFormat )
     return dict ( current_time = get_time )
 
app . secret_key = '123456'
 
if __name__ == '__main__' :
     app . run ( debug = True )

模板代码:


< ! doctype html >
< title > Hello Sample < / title >
< link rel = "stylesheet" href = "{{ url_for('static', filename='style.css') }}" >
   < h1 > Hello World ! < / h1 >
   < p > Request URL : { { request . url } } < / p >
   < p > User : { { session . user } } < / p >
   < p > DB : { { g . db } } < / p >
   < p > Host : { { config . DEBUG } } < / p >
   < p > Current App is : { { appname } } < / p >
   < p > Current Time is : { { current_time ( ) } } < / p >
   < p > Current Day is : { { current_time ( "%Y-%m-%d" ) } } < / p >
 
{ % with messages = get_flashed_messages ( ) % }
   { % if messages % }
     { % for message in messages % }
       Flash Message : { { message } } < / li >
     { % endfor % }
   { % endif % }
{ % endwith % }

文章知识点与官方知识档案匹配,可进一步学习相关知识