python框架之Flask基础篇(三)-------- 模版的操作

栏目: Python · 发布时间: 8年前

内容简介:python框架之Flask基础篇(三)-------- 模版的操作

1.flask特有的变量和函数:

变量:g、session、request、config

函数:url_for()、 get_flashed_messages()这个函数注意了啊,记住这是个函数,别忘了写括号!!!!!!!!!

废话不多说,直接上代码体验一下:

先解释一个bug,当我们设置了 # -*- coding:utf-8 -*-, 但是当返回浏览器页面的数据是汉字的时候还会出现字符编码问题,如下:

UnicodeDecodeError: 'ascii' codec can't decode byte 0xe8 in position 0: ordinal not in range(128)

此时就需要在视图函数的那个.py文件中加入一下几行代码,就解决了编码问题:

import sys
reload(sys)
sys.setdefaultencoding("utf-8")

# -*- coding:utf-8 -*-
from flask import Flask
from flask import flash,render_template,session,g
# 解决编码问题
import sys
reload(sys)
sys.setdefaultencoding("utf-8")


app = Flask(__name__)
app.secret_key = 'hello'


@app.route('/',methods=["GET","POST"])
def hello_world():
    # flash底层是将闪现信息放在了session中,所以需要设置secret_key
    flash("python")
    return g.age

@app.route('/set_session', methods=['GET', 'POST'])
def set_session():
    session["name"] = "wangwu"
    g.age = 18
    return render_template('six_variable.html')

if __name__ == '__main__':
    app.run(debug=True)
这是前段代码:
1.flash:
{% for message in get_flashed_messages() %}
    {{ message }}
{% endfor %}
<br>
2.request:<br>
{{ request.url }} <br>  比如:得到的该路径为:http://localhost:5000/get_session
{{ request.url_root }} <br>  结果为:http://localhost:5000/
{{ request.url_rule }} <br>  结果为:/get_session
{{ request.url_charset }} <br>结果为:utf-8
3.config:<br>
{{ config.root_path }} <br>  获取项目跟路径
{{ config.DEBUG }} <br>    获取DEBUG模式的值   在前段页面字典取值得两种方法
{{ config["SECRET_KEY"] }}<br>
4.session:<br>
{{ session.name }} <br>
{{ session["name"] }} <br>
5.url_for:<br>
{{ url_for("set_session") }}<br>
<a href="{{ url_for("hello_world") }}">hello_world</a><br>
6.g:<br>
{{ g.age }}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Making Things See

Making Things See

Greg Borenstein / Make / 2012-2-3 / USD 39.99

Welcome to the Vision Revolution. With Microsoft's Kinect leading the way, you can now use 3D computer vision technology to build digital 3D models of people and objects that you can manipulate with g......一起来看看 《Making Things See》 这本书的介绍吧!

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

html转js在线工具
html转js在线工具

html转js在线工具