首页 > 解决方案 > 如何将响应类型转换为适合 Html 文件的格式?

问题描述

我正在烧瓶应用程序中编写一个方法。我get从数据http://localhost:5000/product和返回响应为text. 这个方法的代码是:

import requests


@app.route('/product')
def product():
    info = requests.get('http://localhost:5000/product') 
    return info.text

该方法的输出是:

[ { "P_ID": 1, "active": true, "count": 100, "price": 1000, "title": "product1" },
  { "P_ID": 2, "active": false, "count": 12, "price": 2500, "title": "Product2" } ]

现在,我想在html文件中使用这些数据。我在html文件中有一个包含P_IDtitle、和列的表count。我想将这些数据放到这个表中,但我不知道该怎么做。我改变了这个方法如下,但它不能正常工作。priceactive

当我运行 usingpython app.py时,我在表的列中看到整数,但我看不到info表中的信息。当我在文件中使用product.title或时,我会在表格的标题栏中看到。product["title"]product.html<built-in method title of str object at 0x018311C0>

import requests
from flask import render_template


@app.route('/product')
def product():
    info = requests.get('http://localhost:5000/product') 
    info = info.text
    return render_template('product.html', info=info)

product.html文件是:

{% block body %}
<body>
<h1>Products List</h1>

<table  style="text-align: center" width="15%" border="3px" bgcolor="#FFE4E1">
    <tr><td><a href='/add'>Add New Product</a></td></tr>
</table>
<br><br>
<table style="text-align: center" width="50%" align="left" border= "3px solid black" border- 
collapse= collapse bgcolor="#E0FFFF">
    <tr>
        <th> ID </th>
        <th> Title </th>
        <th> Count </th>
        <th> Price </th>
        <th> Active </th>
        <th> Actions </th>
   </tr>
    {% for product in info %}
   <tr>
        <td> {{product[0]}} </td>
        <td> {{product[1]}} </td>
        <td> {{product[2]}} </td>
        <td> {{product[3]}} </td>
        <td> {{product[4]}} </td>
        <td> <a href='/edit/{{product[0]}}'>Edit</a> 
        <a href='/delete/{{product[0]}}' onclick="return confirm('Are You Sure To Delete?')">Delete</a> </td>

     </tr>
    {% endfor %}
 </table>
 </body>
 {% endblock %}

你能帮助我吗?

标签: pythonjsonapiflaskflask-restful

解决方案


推荐阅读