关键词搜索

源码搜索 ×
×

Python笔记-Flask返回字符串、Json、模板数据

发布2020-02-27浏览6687次

详情内容

这里主要是回数据给前端,其中Json,和模板最为常见

程序运行截图如下:

字符串:

Json:

模板:

程序结构如下:

源码如下:

application.py

  1. from flask import Flask
  2. from controller import index_page
  3. app = Flask(__name__)
  4. app.register_blueprint(index_page, url_prefix = "/it1995")
  5. if __name__ == "__main__":
  6. app.run(host = "0.0.0.0", debug=True)

controller.py

  1. from flask import Flask, Blueprint, request, make_response, jsonify, render_template
  2. index_page = Blueprint("index_page", __name__)
  3. @index_page.route("/text")
  4. def text():
  5. return "text/html"
  6. @index_page.route("/text_same")
  7. def text_same():
  8. response = make_response("text/html", 200)
  9. return response
  10. @index_page.route("/json")
  11. def json():
  12. import json
  13. data = {"a" : "b"}
  14. response = make_response(json.dumps(data))
  15. response.headers["Content-Type"] = "application/json"
  16. return response
  17. @index_page.route("/json_same")
  18. def json_same():
  19. data = {"a" : "b"}
  20. response = make_response(jsonify(data))
  21. return response
  22. @index_page.route("/template")
  23. def template():
  24. name = "Hello World"
  25. context = {"name" : name}
  26. context['user'] = {"nickname" : "IT1995", "qq" : "570176391", "url" : "www.it1995.cn"}
  27. context['num_list'] = [1, 2, 3, 4, 5]
  28. return render_template("index.html", **context)
  29. @index_page.route("/index3")
  30. def index3page():
  31. return render_template("index3.html")
  32. @index_page.route("/index4")
  33. def index4page():
  34. return render_template("index4.html")

layout.html

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>统一模版</title>
  6. </head>
  7. <body>
  8. {%block content%}
  9. {%endblock%}
  10. </body>
  11. </html>

index.html

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Title</title>
  6. </head>
  7. <body>
  8. Hello
  9. <p>
  10. {% if user %}
  11. {{user.nickname}} 联系QQ: {{user.qq}} 主页: {{user.url}}
  12. {% endif %}
  13. </p>
  14. <p>
  15. {% for tmp_num in num_list %}
  16. {{tmp_num}}
  17. {% endfor %}
  18. </p>
  19. </body>
  20. </html>

index3.html

  1. {% extends "common/layout.html" %}
  2. {% block content %}
  3. How are you
  4. {% endblock %}

index4.html

  1. {% extends "common/layout.html" %}
  2. {% block content %}
  3. How old are you
  4. {% endblock %}

 

相关技术文章

点击QQ咨询
开通会员
返回顶部
×
微信扫码支付
微信扫码支付
确定支付下载
请使用微信描二维码支付
×

提示信息

×

选择支付方式

  • 微信支付
  • 支付宝付款
确定支付下载