Flask 相应对象(Response)和模板(Jinja2)

对请求进行多个格式的响应

text/html

from flask import Blueprint,request,make_response,jsonify,render_template

@index_page.route("/text")
def text():
    return "text/html"

@index_page.route("/text_same")
def text_same():
    response = make_response( "text/html",200 )
    return response

Json

@index_page.route("/json")
def json():
    import json
    data = { "a":"b" }
    response = make_response( json.dumps( data ) )
    response.headers["Content-Type"] = "application/json"
    return response
@index_page.route( "/json_same" )
def json_same():
    data = { "a":"b" }
    response = make_response( jsonify( data )  )
    return response

模块响应

这样写会自动进入项目的子文件夹templates寻找index.html页面。

@index_page.route("/template")
def template():
    return render_template( "index.html" )

Jinja2 模板语法详细讲解

传递变量

@index_page.route("/template")
def template():
    ##传值
    name = "kevin"
    context = { "name" : name }
    context['user'] = { "nickname":"kevin","qq":"xxxxx","home_page":"http://www.javami.com" }
    context['num_list'] = [ 1,2,3,4,5]
    #return render_template( "index.html",name = name )
    return render_template( "index.html",**context ) #**表示传递字典

Jinja2显示变量

<p>var name = {{ name }}</p>

Jinja2基本语法

<p>var name = {{ name }}</p>
<p>
    {% if user %}
    {{ user.nickname }} 联系QQ:{{  user.qq }} 主页:{{ user.home_page }}
    {% endif %}
</p>
<p>
    {% for tmp_num in num_list %}
    {{ tmp_num }}
    {% endfor %}
</p>
</body>

Jinja2模板继承

父模板

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>这是统一模板</title>
</head>
<body>
{% block content %} {% endblock %}
</body>
</html>

子模块记得要写extends

{% extends "common/layout.html" %}

{% block content %}
hello i love imooc
{% endblock %}