【PythonWeb开发】Flask视图函数传递数据到前端模版的方法总结。

在Flask框架中,视图函数返回响应有四种常见方式,都得掌握。

一、返回文本内容

可以直接返回字符串,Flask会自动将其转换为一个响应对象,具有默认的text/html内容类型。

python 复制代码
@app.route('/return_text')
def return_text():
    return "这是一段文本数据"

二、返回JSON格式内容

使用jsonify函数(前后端分离),它是Flask提供的辅助函数,专门用于将Python字典或其他可序列化对象转换为JSON响应。

python 复制代码
from flask import jsonify

@app.route('/return_json')
def return_json():
    data = {"name": "xiaodai", "age": 18}
    return jsonify(data)

三、返回自定义的Response对象

在Flask中,可以直接实例化一个**Response**对象来更精细地控制响应的内容、状态码以及头部信息。

python 复制代码
from flask import Response

@app.route('/custom_response')
def custom_response():
    # 创建一个自定义的响应内容
    custom_content = "这是自定义的响应内容"

    # 实例化一个Response对象
    response = Response(
        response=custom_content,  # 响应内容
        status=200,  # HTTP状态码,默认是200 OK
        mimetype='text/plain',  # 响应的MIME类型,默认为'text/html'
        headers={  # 自定义响应头
            'X-Custom-Header': 'Some Value'
        }
    )
    
    return response

返回JSON内容还能和Response对象一起使用,只需将jsonify()返回的值用get_data()取出来传给response参数就行。

python 复制代码
@app.route('/api/data', methods=['GET'])
def get_data():
    data = {
        "message": "Hello from the API",
        "status": "success"
    }
    
    # 使用jsonify来创建标准的JSON响应内容,然后包装到自定义的Response中
    json_response = jsonify(data)
    
    # 转换为Response对象以添加自定义头部
    response = Response(
        response=json_response.get_data(),  # 获取jsonify生成的字节流数据
        status=200,
        mimetype='application/json',  # 指定为JSON类型
        headers={
            'X-API-Version': '1.0'  # 自定义响应头
        }
    )
    
    return response

四、渲染模版并返回数据

使用render_template函数(前后端不分离),它会加载指定的HTML模板文件,并且可以传递字典参数给模板以便填充动态内容。

python 复制代码
from flask import render_template

@app.route('/')
def index():
    username = "小呆"
    return render_template('index.html', username=username)

还可以先使用**render_template** 函数渲染模板得到HTML内容,然后将这个内容传入**Response** 的构造函数中,创建一个自定义的**Response**对象。这样,你可以在保留模板渲染功能的同时,进一步自定义响应的其他方面。

python 复制代码
from flask import render_template, Response

@app.route('/custom-rendered-template')
def custom_rendered_template():
    # 使用render_template渲染模板
    rendered_template = render_template('example.html')
    
    # 将渲染结果包装进自定义的Response对象中
    response = Response(
        response=rendered_template,  # 渲染后的模板内容
        status=200,  # 可以根据需要修改状态码
        mimetype='text/html',  # 默认情况下,render_template生成的是HTML内容,所以这里保持'text/html'
        headers={  # 添加任何自定义的响应头
            'X-Custom-Header': 'Custom Value'
        }
    )
    
    return response
相关推荐
许彰午5 小时前
14_Java泛型完全指南
java·windows·python
广州灵眸科技有限公司5 小时前
瑞芯微RV1126B开发板(EASY-EAI-PI2) Easy-Eai编译环境准备与更新
服务器·前端·人工智能·python·深度学习
TechWayfarer6 小时前
IP风险等级评估接入实战:金融信贷如何用IP画像辅助风控审核
python·tcp/ip·安全·金融
Esaka_Forever6 小时前
uv init 完整用法(Python 最快包管理器)
服务器·python·uv
大鸡腿同学7 小时前
AI 知识库搜索不准?问题出在分块
后端
夕颜1117 小时前
Multica 使用心得介绍
后端
星轨zb8 小时前
LangChain4j 集成 Spring Boot:会话记忆 NPE 的根源与 ChatMemoryProvider 正确配置
java·spring boot·后端·langchain4j
混凝土拌意大利面8 小时前
TG-BOOT springboot 功能集散开发框架(AI 协作友好)
人工智能·spring boot·后端
神仙别闹9 小时前
基于Python + SQL server 实现(GUI)原神圣遗物管理与角色数值模拟系统
java·数据库·python
是有头发的程序猿9 小时前
电商自动化实战:淘宝/天猫item_get商品详情API全量采集教程(Python源码)
java·python·自动化