简体   繁体   中英

Query sqlite using flask routing

I am trying to query my sqlite database using flask routing such as

@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)

The routing does work but the page doesn't display any data from the database.

{% 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 %}

Can anyone see what the issue might be?

The error is probably somewhere else, because this works for me:

File 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()

File templates/test.html :

<ul>
    {%- for movie in movies %}
        <li>{{ movie.movie_name }}</li>
    {%- endfor %}
</ul>

Console:

$ ./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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM