【问题标题】:Query sqlite using flask routing使用flask路由查询sqlite
【发布时间】:2015-10-27 00:02:06
【问题描述】:

我正在尝试使用烧瓶路由查询我的 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 %}

谁能看出问题出在哪里?

【问题讨论】:

  • 您是否尝试过打印您的电影收藏?它会返回任何东西吗?如果您按预期返回电影,请发布您的 test.html。您的模板可能有问题
  • 那么 name 参数可能有问题。尝试在呼叫路线时打印姓名。
  • 添加了上面的模板。它在我在 sql 查询中指定类别时起作用
  • 是的,当我返回它时它会打印
  • 当你执行像'/movies/genres/foo'这样的get请求并打印name时,它会打印foo吗?如果是这样,那么请确保您的 sql 查询中的名称周围有正确的引号。我认为SQL通常需要字符串值的引号

标签: python sqlite flask


【解决方案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>

【讨论】:

  • 这成功了!我认为我的问题是我过早地关闭了数据库连接,这导致代码什么都不返回,但路由工作成功!非常感谢您的帮助!
猜你喜欢
  • 2012-07-26
  • 1970-01-01
  • 2012-11-01
  • 2020-05-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-31
相关资源
最近更新 更多