使用 Flask 和 render_template 显示 HTML 表格 [英] Show HTML table with Flask and render_template

查看:103
本文介绍了使用 Flask 和 render_template 显示 HTML 表格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在使用 Google Cloud SQL 和 Google App Engine 的网站上显示一个表格.我正在使用 Flask 和 pymysql.为了显示我的查询结果,我使用了 Flask 的 render_template.

I would like to show a table on a website using Google Cloud SQL and Google App Engine. I am using Flask and pymysql. To show the result of my query I use the render_template of Flask.

我已经在这里找到了其他类似的主题(例如 主题:将表格结果列出到HTML with Flask),但在部署应用程序时仍然出现错误.似乎错误与 for 循环有关.. 错误说jinja2.exceptions.TemplateSyntaxError: tag name expected".

I already found other similar topics here (like Topic: Listing table results to HTML with Flask), but I still get an error when I deploy my app. It seems that the error has to do with the for loop.. The error says "jinja2.exceptions.TemplateSyntaxError: tag name expected".

这是我收到的完整错误消息:

Here's the full error message I get:

ERROR in app: Exception on /analysis [GET]
Traceback (most recent call last):    File "/env/lib/python3.7/site-packages/flask/app.py", line 2292, in wsgi_app      response = self.full_dispatch_request()
File "/env/lib/python3.7/site-packages/flask/app.py", line 1815, in full_dispatch_request      rv = self.handle_user_exception(e)
File "/env/lib/python3.7/site-packages/flask/app.py", line 1718, in handle_user_exception      reraise(exc_type, exc_value, tb)
File "/env/lib/python3.7/site-packages/flask/_compat.py", line 35, in reraise      raise value
File "/env/lib/python3.7/site-packages/flask/app.py", line 1813, in full_dispatch_request      rv = self.dispatch_request()
File "/env/lib/python3.7/site-packages/flask/app.py", line 1799, in dispatch_request      return self.view_functions[rule.endpoint](**req.view_args)
File "/srv/main.py", line 61, in analysis      return render_template("analysis.html", result = result)
File "/env/lib/python3.7/site-packages/flask/templating.py", line 134, in render_template      return _render(ctx.app.jinja_env.get_or_select_template(template_name_or_list),    File "/env/lib/python3.7/site-packages/jinja2/environment.py", line 869, in get_or_select_template      return self.get_template(template_name_or_list, parent, globals)
File "/env/lib/python3.7/site-packages/jinja2/environment.py", line 830, in get_template      return self._load_template(name, self.make_globals(globals))
File "/env/lib/python3.7/site-packages/jinja2/environment.py", line 804, in _load_template      template = self.loader.load(self, name, globals)
File "/env/lib/python3.7/site-packages/jinja2/loaders.py", line 125, in load      code = environment.compile(source, name, filename)
File "/env/lib/python3.7/site-packages/jinja2/environment.py", line 591, in compile      self.handle_exception(exc_info, source_hint=source_hint)
File "/env/lib/python3.7/site-packages/jinja2/environment.py", line 780, in handle_exception      reraise(exc_type, exc_value, tb)
File "/env/lib/python3.7/site-packages/jinja2/_compat.py", line 37, in reraise      raise value.with_traceback(tb)
File "/srv/templates/analysis.html", line 23, in template      <p class="p1"><span class="s1"><span class="Apple-tab-span"> </span>{% </span><span class="s2">for</span><span class="s1"> r </span><span class="s2">in</span><span class="s1"> result %}</span></p>
File "/env/lib/python3.7/site-packages/jinja2/environment.py", line 497, in _parse      return Parser(self, source, name, encode_filename(filename)).parse()
File "/env/lib/python3.7/site-packages/jinja2/parser.py", line 901, in parse      result = nodes.Template(self.subparse(), lineno=1)
File "/env/lib/python3.7/site-packages/jinja2/parser.py", line 883, in subparse      rv = self.parse_statement()
File "/env/lib/python3.7/site-packages/jinja2/parser.py", line 125, in parse_statement      self.fail('tag name expected', token.lineno)
File "/env/lib/python3.7/site-packages/jinja2/parser.py", line 59, in fail      raise exc(msg, lineno, self.name, self.filename)  jinja2.exceptions.TemplateSyntaxError: tag name expected

我在 main.py 中的代码:

My Code in main.py:

    import logging
    import os
    from flask import Flask, render_template
    from flask import request
    import urllib.request
    from urllib.parse import parse_qs, urlparse
    import platform
    import pymysql
    import datetime

    db_user = os.environ.get('CLOUD_SQL_USERNAME')
    db_password = os.environ.get('CLOUD_SQL_PASSWORD')
    db_name = os.environ.get('CLOUD_SQL_DATABASE_NAME')
    db_connection_name = os.environ.get('CLOUD_SQL_CONNECTION_NAME')

    app = Flask(__name__)

    @app.route('/analysis', methods=['GET'])
    def analysis():
        if os.environ.get('GAE_ENV') == 'standard':
            unix_socket = '/cloudsql/{}'.format(db_connection_name)
            cnx = pymysql.connect(user=db_user, password=db_password,
                                  unix_socket=unix_socket, db=db_name)
        else:
            host = '127.0.0.1'
            #unix_socket = '/cloudsql/{}'.format(db_connection_name)
        cnx = pymysql.connect(user=db_user, password=db_password,
                                  unix_socket=unix_socket, db=db_name)
        with cnx.cursor() as cursor:
            sql = 'SELECT * FROM content'
            cursor.execute(sql)
            result = cursor.fetchall()
        cnx.close()
        return render_template("analysis.html", result = result)

if __name__ == '__main__':
    app.run(host='127.0.0.1', port=8080, debug=True)

文件分析.html:

<!doctype html>
<table>
<tr>
  <th>contentID</th>
  <th>timestamp</th> 
  <th>clientID</th>
  <th>content</th>
</tr>
{% for r in result %}
<tr>
  <td>{{ r[0] }}</td>
  <td>{{ r[1] }}</td> 
  <td>{{ r[2] }}</td>
  <td>{{ r[3] }}</td>
</tr>
{% endfor %}
</table>

您有什么建议我可以更改以使其正常工作吗?
提前致谢!

Do you have any suggestions what I can can change to make it work?
Thanks in advance!

推荐答案

根据堆栈跟踪,您用于 analysis.html 的文本编辑器不是纯文本编辑器.它以其他格式保存文件,使其成为无效的 Jinja2 语法.

Based on the stack trace, the text editor you're using for analysis.html isn't a plain text editor. It's saving the file in some other format, making it invalid Jinja2 syntax.

所以你在编辑器中看到的这一行:

So this line that you see in your editor:

{% for r in result %}

Python 将显示为(基于堆栈跟踪;为清晰起见添加了一些换行符):

Python will see as (based on the stack trace; added some line breaks for clarity):

<p class="p1">
<span class="s1">
<span class="Apple-tab-span">
</span>
{% </span><span class="s2">for</span><span class="s1"> r </span><span class="s2">in</span><span class="s1"> result %}
</span>
</p>

要解决此问题,请在纯文本编辑器中打开文件 analysis.html 并根据需要对其进行编辑.

To fix the problem, open the file analysis.html in a plain text editor and edit it as needed.

这篇关于使用 Flask 和 render_template 显示 HTML 表格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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