zl程序教程

您现在的位置是:首页 >  IT要闻

当前栏目

Flask 学习-90.Flask-RESTX 返回 HTML 内容

2023-02-19 12:20:22 时间

前言

Flask-RESTX 框架默认返回的是application/json格式,使用render_template()返回html内容遇到了一些问题

遇到的问题

需要使用render_template() 返回HTML内容

from flask_restx import Resource, Namespace, reqparse
from flask import make_response

api = Namespace('render/html')

@api.route('')
class RenderHTML(Resource):

    def get(self):
        """渲染html"""

        return render_template('hello.html')

模板内容

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>demo</title>
</head>
<body>
<h1>hello world</h1>
</body>
</html>

访问后会以字符串格式返回

默认以json 格式响应

make_response 自定义响应

使用make_response() 自定义响应内容

@api.route('')
class RenderHTML(Resource):

    def get(self):
        """渲染html"""
        res = render_template('hello.html')
        response = make_response(res)
        return response

这样 html 就可以正常渲染了.