我正在尝试使用诸如
之类的烧瓶路由来查询我的sqlite数据库@app.route ('/movies/genres/<name>/')
def test(name = None):
g.db = connect_db()
cur = g.db.execute('select * from movies where category = ?', [name])
movies = [dict(id=row[0], movie_name=row[1]) for row in cur.fetchall()]
g.db.close()
return render_template('test.html', movies=movies, name=name)
路由确实有效,但页面不显示数据库中的任何数据。
{% for movie in movies %}
<div>
<div class="well" style="width:220px; height:312px; float:left; margin:10px; padding:5px;">
<img src="{{ movie.poster }}" alt="uh oh" style="width:209px;height:300px"> {{ movie.movie_name }}
</div>
{% endfor %}
{% endblock %}
任何人都可以看到问题所在吗?
答案 0 :(得分:1)
错误可能在其他地方,因为这对我有用:
档案demo.py
:
#!/usr/bin/env python3
from flask import Flask, g, render_template
import sqlite3
app = Flask(__name__)
@app.route('/movies/genres/<name>/')
def test(name=None):
g.db = connect_db()
cur = g.db.execute('select id, name from movies where category = ?', [name])
movies = [dict(id=row[0], movie_name=row[1]) for row in cur.fetchall()]
g.db.close()
return render_template('test.html', movies=movies, name=name)
def connect_db():
return sqlite3.connect('example.db')
def init_db():
conn = connect_db()
c = conn.cursor()
try:
c.execute('create table movies (id int, name text, category text)')
c.execute('insert into movies (id, name, category) values (?, ?, ?)', (1, 'Alien', 'sci-fi'))
c.execute('insert into movies (id, name, category) values (?, ?, ?)', (2, 'Aliens', 'sci-fi'))
c.execute('insert into movies (id, name, category) values (?, ?, ?)', (3, 'Prometheus', 'sci-fi'))
except sqlite3.OperationalError as e:
assert 'table movies already exists' in str(e)
conn.commit()
conn.close()
def main():
init_db()
app.run(debug=True)
if __name__ == '__main__':
main()
档案templates/test.html
:
<ul>
{%- for movie in movies %}
<li>{{ movie.movie_name }}</li>
{%- endfor %}
</ul>
控制台:
$ ./demo.py &
* Running on http://127.0.0.1:5000/
$ curl 127.0.0.1:5000/movies/genres/sci-fi/
<ul>
<li>Alien</li>
<li>Aliens</li>
<li>Prometheus</li>
</ul>