1、flask中静态文件的调用
flask中默认将一些静态文件如图片/css文件等放入static文件夹下,而我们可以在html文档中对其进行访问.
flask模板中的url_for()函数,该函数在html文档中调用,以视图函数为参数,返回该视图函数对应的url
1)在项目目录下新建一个static文件夹,里面放一名为1111.jpg的图片:
2)在templates目录下新建test.html,内容如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>图片</title>
</head>
<body>
<img src="{{ url_for('static', filename='images/1111.jpg') }} " width="400" height="400" alt="" title=""/>
</body>
</html>
3)python代码如下:
from flask import Flask,render_template
app=Flask(__name__)
@app.route('/login/')
def index():
return render_template('test.html')
if __name__=='__main__':
app.run()
4)执行后,打开http://127.0.0.1:5000/login/
加载静态文件
语法:
‘url_for(‘static’, filename=’路径’)’
静态文件,flask会从’static’文件夹中开始寻找,不需要再写’static’这个路径。
加载css语法:
<link rel="stylesheet" href="{{ url_for('static',filename='css/index.css') }}">
加载js语法:
<script src="{{ url_for('static',filename='js/index.js') }}"></script>
加载图片的语法:
<img src="{{ url_for('static',filename='images/aaa.jpg') }}" alt="">
2、 flask中本地化时间的引用
1)在templates文件夹下新建test14.html,内容如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>本地化时间引用</title>
{{moment.include_jquery()}}
{{moment.include_moment()}}
{{moment.lang("zh-CN")}}
</head>
<body>
{{moment().format('YYYY-MM-DD,h:mm:ss a')}}
</body>
</html>
html中我们需要先引入moment.js和jquery.js两个js库,因为Flask_Mement需要依赖这两个库,我们在html文件中的head标签中进行引用
说明:
{{moment.include_jquery()}}和 {{moment.include_moment()}}分别是对moment.js和jquery.js两个js库的引用, {{moment.lang("zh-CN")}}是设置本地的语言环境为中文. {{moment().format('YYYY-MM-DD,h:mm:ss a')}}是将moment进行格式化输出.
2)python代码如下:
from flask import Flask,render_template
from flask_moment import Moment
app=Flask(__name__)
Moment(app)
@app.route('/')
def test():
return render_template('test14.html')
if __name__=='__main__':
app.run()
导入flask_moment之前需要先安装flask_moment
3)执行后:
常用的格式化参数:
3、url_for()函数是用于构建指定函数的URL,url_for操作对象是函数
python代码如下:
from flask import Flask,url_for,redirect
app=Flask(__name__)
@app.route('/index/')
def index():
return u'这是index首页'
@app.route('/login/')
def login():
return u'这是login首页'
@app.route('/question/<is_login>/')
def question(is_login):
if is_login == '1':
return redirect(url_for('index'))
else:
return redirect(url_for('login'))
if __name__=='__main__':
app.run()
执行这段代码,我们发现在浏览器上输入:
http://127.0.0.1:5000/question/2/直接跳转到http://127.0.0.1:5000/login这个页面,页面显示:这是login首页
http://127.0.0.1:5000/question/1/直接跳转到http://127.0.0.1:5000/index这个页面,页面显示:这是index首页
以上现象是因为:url_for('index')执行的是def index()这个函数对应的路由/index/;url_for('login')执行的是def login()这个函数对应的路由/login/;然后又被redirect重定向了;