Python笔记-Flask返回字符串、Json、模板数据
生活随笔
收集整理的這篇文章主要介紹了
Python笔记-Flask返回字符串、Json、模板数据
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
這里主要是回數據給前端,其中Json,和模板最為常見
程序運行截圖如下:
字符串:
Json:
模板:
程序結構如下:
源碼如下:
application.py
from flask import Flask from controller import index_pageapp = 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_templateindex_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 jsondata = {"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 %}?
總結
以上是生活随笔為你收集整理的Python笔记-Flask返回字符串、Json、模板数据的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Java工作笔记-Java函数参传值传引
- 下一篇: websocket python爬虫_p