flask使用restful api规范无法响应html资源

本文介绍如何在 Flask RESTful 应用中正确返回 HTML 内容而非默认的 JSON 格式。通过自定义响应类型,可以实现浏览器直接加载 HTML 页面。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题复现
核心代码
from flask import Blueprint, request, render_template
from flask_restful import Resource, Api
user_bp = Blueprint('user', __name__, url_prefix='/v1')
api = Api(user_bp)

class LoginView(Resource):
    def get(self):
        return  render_template('login1.html')
        
api.add_resource(LoginView, "/login")
浏览器访问:127.0.0.1:8000/v1/login

使用F12进入开发者模式查看详情,可以看到浏览器显示的响应头响应类型为 application/json,而正常响应头响应类型应该为 text/html。

问题原因与解决

原因: 因为 flask restful 支持的mediatype仅为application/json,对应的处理函数为 output_json。

如果要输出 html 格式的内容,则需要自己添加处理对应mediatype的函数

解决: 在实例化的api中添加处理html格式的资源配置,重新运行flask项目即可。

from flask import Blueprint, request, render_template
from flask_restful import Resource, Api
user_bp = Blueprint('user', __name__, url_prefix='/v1')
api = Api(user_bp)

@api.representation("text/html")
def out_html(data,code, headers=None):
    resp = make_response(data, code)     
    resp.headers.extend(headers or {})
    return resp
    
class LoginView(Resource):
    def get(self):
        return  render_template('login1.html')
        
api.add_resource(LoginView, "/login")
再次浏览器访问:127.0.0.1:8000/v1/login

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值