【问题标题】:How to fix rendering issues in Python script如何修复 Python 脚本中的渲染问题
【发布时间】:2017-08-03 11:23:51
【问题描述】:

我编写了一个 python 脚本,它读取 csv 文件并将其显示在网页上。该网页是一个简单的html。

我正在尝试以某种格式显示它。我通过stackoverflow搜索并发现了这个: Formatting output of CSV file in Python 这很有帮助。

但是,使用print 函数时它工作正常,但是当我尝试渲染到我的网页时,格式不一样,它也只显示一行结果而不是整个文件。

那么我怎样才能让它在我的网页上显示与它在 python shell 上显示的相同格式呢?

这是我目前所拥有的:

@app.route('/results/view')
def my_results():

        with open(str(get_file(filename)), "r") as f:
            content = csv.reader(f)
            for row in content:
                content =(('{:^15}  {:^15}  {:^20} {:^25}'.format(*row)))

            return render_template("results.html",content=content)


if __name__ == '__main__':
    app.debug = True #Uncomment to enable debugging
    app.run() #Run the Server

结果.html

<!DOCTYPE html>
<html>
<head>
<title>My webpage</title>
</head>
<body>
  <a>{{ content }}</a>
</body>
</html>

带有print 语句而不是'content=' 的结果(我想要的)

  A       B
 blue     Car
 yellow   Bike
 green    Boat

content = 得到的结果

A green B Boat

【问题讨论】:

  • 为什么这被否决了?

标签: python html rendering webpage


【解决方案1】:

与:

    content = csv.reader(f)
    for row in content:
        content =(('{:^15}  {:^15}  {:^20} {:^25}'.format(*row)))

你是:

  • 将 csv 的内容分配给content
  • 遍历content
  • 将格式化字符串分配给content(使用print则没有这一步)

所以content 在每次迭代时都会被覆盖。

你可能想要这样的东西:

    content = csv.reader(f)
    html_content=""
    for row in content:
        html_content += (('{:^15}  {:^15}  {:^20} {:^25}'.format(*row)))
        html_content += "<br>" #or p/div/…

然后是return render_template("results.html",content=html_content)

或者

    content = csv.reader(f)
    html_content=[]
    for row in content:
        html_content.append(('{:^15}  {:^15}  {:^20} {:^25}'.format(*row)))

然后在你的视图中执行一个 for 循环。使用 jinja,类似于:

{% for row in content %}
  <p>{{ row|e }}</p>
{% endfor %}

【讨论】:

  • 感谢您的澄清。尽管您的建议可以显示所有结果,但它的格式仍然不正确。这只是一条没有中断的长线
  • 您添加了html_content += "&lt;br&gt;" 吗?也许他们逃脱了?
  • 我做到了。 '
    ' 只是打印在结果之间。所以A
    蓝色
    汽车...
  • 您的模板引擎正在转义 html 标签(这实际上是一件好事)。使用第二种解决方案(将列表传递给模板并在模板中对其进行迭代)将避免此问题。此外,在 HTML 中,一系列 N 个连续空格被视为一个空格,因此您的行格式也不起作用。如果要显示表格数据,请改用适当的 html 标签(table / th / tr / td)。
  • 我正在使用烧瓶,但它有点工作。现在它在每一行打印一个字母。一旦正确,我会更新我的答案。
【解决方案2】:

经过一番研究,我发现了这个Python dictionary in to html table 这是需要的。

Fredtantini 的回答很接近。我需要在我的 html 代码中添加一个嵌套的 for 循环。

<table>
{% for row in content %}
    <tr>
    {% for i in row %}
        <td>{{ i}}</td>
    {% endfor %}
    </tr>
{% endfor %}
 </table>

这对我有用

【讨论】:

    猜你喜欢
    • 2019-04-28
    • 1970-01-01
    • 1970-01-01
    • 2019-06-23
    • 2014-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-13
    相关资源
    最近更新 更多