我想使用Google Cloud SQL和Google App Engine在网站上显示表格。 我正在使用Flask和pymysql。为了显示查询的结果,我使用了Flask的render_template。
我已经在这里找到其他类似的主题(例如Topic: Listing table results to HTML with Flask),但是在部署应用程序时仍然出现错误。似乎该错误与for循环有关。错误显示为“ jinja2.exceptions.TemplateSyntaxError:期望标记名称”。
这是我收到的完整错误消息:
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中的我的代码:
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)
file analysis.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>
您有什么建议可以改变以使其正常工作吗?
预先感谢!
答案 0 :(得分:1)
基于堆栈跟踪,用于analysis.html
的文本编辑器不是纯文本编辑器。它将以其他格式保存文件,使其成为无效的Jinja2语法。
因此您在编辑器中看到的这一行:
{% for r in result %}
Python将显示为(基于堆栈跟踪;为清楚起见添加了一些换行符):
<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
,然后根据需要进行编辑。
答案 1 :(得分:0)
一种方法是先拥有一个对象,或者使用 Pandas 读取_csv,然后使用数据框的 to_html 方法。
如果您的数据格式正确,这将节省大量时间:
group value Latitude Longitude Depth
S1 OTU1 0.000055 -42.3640 -44.0318 50.0
S2 OTU1 0.000230 -39.9648 -42.4232 149.0
S3 OTU1 0.000083 -35.0093 -39.4310 151
....
现在您将 HTML 字符串粘贴到您的模板中,而无需将其作为 JSON 或需要 Jinja 模板格式的 dict 发送:
import pandas as pd
from flask import Flask, render_template
@app.route("/table-page", methods=['GET'])
def table():
data_dic = {
'id': [100, 101, 102],
'color': ['red', 'blue', 'red']}
columns = ['id', 'color']
index = ['a', 'b', 'c']
df = pd.DataFrame(data_dic, columns=columns, index=index)
table = df.to_html(index=False)
return render_template(
"at-leaderboard.html",
table=table)
答案 2 :(得分:0)
{% for r in result %}
<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">
</span>
</p>
{% endfor %}