RESTful API - 在html表格中显示返回的json [英] RESTful API - display returned json in html table

查看:575
本文介绍了RESTful API - 在html表格中显示返回的json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在烧瓶和蟒蛇中做一个平静的API。这里是我的代码:

  from flask import Flask,jsonify,request,render_template $ b $ from flask_restful import Api,Resource 

app = Flask(__ name__)
api = Api(app)
$ b $ class类别(资源):
@ app.route('/')
def get(self):
test = {
name:json2html,
description:将JSON转换为HTML表格形式
}
返回jsonify(测试)

api.add_resource(曲目,'/曲目')

如果__name__ =='__main__':
app.run (port ='5002')

我的问题是我该如何修改它才能显示我的返回表中的值并添加例如一些CSS。在您的应用程序中返回以下内容:

解决方案



<$ p $如果你的代码中没有任何代码,那么你可以使用这个代码来实现这个功能。

return Response(render_template('test.html',result = test,mimetype ='text / html'))


$ b

test.html

 <!DOCTYPE html> 
< html>
< head>< / head>
< body>
< table>
{%for key,result.iteritems()中的值%}

< tr>
< th> {{key}}< / th>
< td> {{value}}< / td>
< / tr>
{%endfor%}
< / table>
< / body>
< / html>

这是我的输出:

I'm trying to do a restful api in flask and python. Here's my code:

from flask import Flask, jsonify, request, render_template
from flask_restful import Api, Resource

app = Flask(__name__)
api = Api(app)

class Tracks(Resource):
    @app.route('/')
    def get(self):
        test = {
            "name": "json2html",
            "description": "Converts JSON to HTML tabular representation"
        }
        return jsonify(test)

api.add_resource(Tracks, '/tracks') 

if __name__ == '__main__':
    app.run(port='5002')

My question is how should I modify it to be able to display my returned value in table and add e.g. some CSS. Thanks!

解决方案

in your application return the following:

return Response(render_template('test.html', result=test, mimetype='text/html'))

and in test.html

<!DOCTYPE html>
<html>
<head></head>
<body>
    <table>
        {% for key, value in result.iteritems() %}

        <tr>
            <th> {{ key }} </th>
            <td> {{ value }} </td>
        </tr>
        {% endfor %}
    </table>
</body>
</html>

this was my output:

这篇关于RESTful API - 在html表格中显示返回的json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆