1. 程式人生 > 實用技巧 >Flask 的 5 種返回值

Flask 的 5 種返回值

一、字串

# 返回值是字串
@app.route('/one')
def one():
    return "This is a string!"

二、重定向

# 引入重定向函式
from flask import redirect
# 返回值是路由的重定向,和第一個的頁面相同
@app.route('/two')
def two():
    return redirect("/one")

三、html介面渲染

# 引入渲染函式
from flask import render_template
# 返回值是html介面渲染
@app.route('/three')
def three():
    return render_template("hello.html", name="xkj")

注意:hello.html檔案是在templets檔案下直接建立的!

四、返回檔案

# 引入傳送檔案的函式
from flask import send_file
# 開啟並返回檔案內容
@app.route('/four')
def four():
    return send_file("4.jpeg")

五、返回json

#引入返回json的函式
from flask import jsonify
#返回json
@app.route('/five')
def five():
    obj = {
        "status": 1,
        "content": {
            "from": "python"
        }
    }
    return jsonify(obj)

本文首發於python黑洞網,部落格園同步更新