这里主要是回数据给前端,其中Json,和模板最为常见
程序运行截图如下:
字符串:

Json:

模板:

程序结构如下:

源码如下:
application.py
- from flask import Flask
- from controller import index_page
-
- app = Flask(__name__)
-
- app.register_blueprint(index_page, url_prefix = "/it1995")
-
- if __name__ == "__main__":
- app.run(host = "0.0.0.0", debug=True)
controller.py
- from flask import Flask, Blueprint, request, make_response, jsonify, render_template
-
- index_page = Blueprint("index_page", __name__)
-
- @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
-
- @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
-
- @index_page.route("/template")
- def template():
- name = "Hello World"
- context = {"name" : name}
- context['user'] = {"nickname" : "IT1995", "qq" : "570176391", "url" : "www.it1995.cn"}
- context['num_list'] = [1, 2, 3, 4, 5]
- return render_template("index.html", **context)
-
- @index_page.route("/index3")
- def index3page():
- return render_template("index3.html")
-
- @index_page.route("/index4")
- def index4page():
- return render_template("index4.html")
layout.html
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <title>统一模版</title>
- </head>
- <body>
- {%block content%}
- {%endblock%}
- </body>
- </html>
index.html
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <title>Title</title>
- </head>
- <body>
- Hello
- <p>
- {% if user %}
- {{user.nickname}} 联系QQ: {{user.qq}} 主页: {{user.url}}
- {% endif %}
- </p>
- <p>
- {% for tmp_num in num_list %}
- {{tmp_num}}
- {% endfor %}
- </p>
- </body>
- </html>
index3.html
- {% extends "common/layout.html" %}
- {% block content %}
- How are you
- {% endblock %}
index4.html
- {% extends "common/layout.html" %}
- {% block content %}
- How old are you
- {% endblock %}



















