dimanche 10 janvier 2016

Reading from sqlite DB using form answers when using Flask

I apologize ahead of time, I'm sure this is a silly question. I wanted to try and teach myself Flask over the weekend but I hit my first hurdle. Here is a basic idea of my program:

  • Large database named plugin.db
  • Finished the flask tutorial, and now I'm using those files for reference when writing my own.
  • Currently my application works (meaning it doesn't crash), but nothing is coming back when I attempt to query my sqlite database.

Here is my main code:

import os
import sqlite3
from flask import Flask, request, session, g, redirect, url_for, abort, \
 render_template, flash

app = Flask(__name__)
app.config.from_object(__name__)

# Load default config and override config from an environment variable
app.config.update(dict(
    DATABASE=os.path.join(app.root_path, 'plugin.db'),
))
app.config.from_envvar('PLUGINDB_SETTINGS', silent=True)

def connect_db():
    """Connects to the specific database."""
    rv = sqlite3.connect(app.config['DATABASE'])
    rv.row_factory = sqlite3.Row
    return rv

def init_db():
    with app.app_context():
        db = get_db()
        with app.open_resource('schema.sql', mode='r') as f:
            db.cursor().executescript(f.read())
        db.commit()

@app.cli.command('initdb')
def initdb_command():
    """Initializes the database."""
    init_db()
    print 'Initialized the database.'

def get_db():
    """Opens a new database connection if there is none yet for 
    the current application context
    """
    if not hasattr(g, 'sqlite_db'):
        g.sqlite_db = connect_db()
    return g.sqlite_db

@app.teardown_appcontext
def close_db(error):
    """Closes the database again at the end of the request."""
    if hasattr(g, 'sqlite_db'):
        g.sqlite_db.close()

@app.route("/",methods=["GET","POST"])
@app.route("/index",methods=["GET","POST"])
def index():
    db = get_db()
    cur = db.execute('select * from t0109161144 where pluginID is 19506')
    plugins = cur.fetchall()
    return render_template("index.html")

@app.route('/query', methods=["GET","POST"])
def script_id():
    db = get_db()
    script_id = request.form['script_id']
    plugin_info = dependencies(script_id)
    return redirect(url_for('index'))

def dependencies(script_id):
    db = get_db()
    dependencies = db.execute("select * from t0109161144 where pluginID is (script_id) values (?)', (script_id)
    return dependencies

My script has become quite crowded along the way while I was testing a few different things. Here is my current index.html:

{% extends "layout.html" %}
{% block body %}
    <form action="{{ url_for('index') }}" method=post class=index>
      <dl>
        <dt>Plugin ID:
        <dd><input type=text size=30 name=script_id>
        <dd><input type=submit value=Query>
      </dl>
    </form>
  <ul class=plugins>
  {% for plugin in plugins %}
    <li><h2>{{ plugin.pluginID }}</h2>{{ plugin.pluginname|safe }}
  {% else %}
    <li><em>Unbelievable.  No entries here so far</em>
  {% endfor %}
  </ul>
{% endblock %}

What I'm trying to do is this:

  • User searches by plugin ID (or other variables that I will worry about later) in the text box.
  • The value entered by the user is then used to query the database and return results.

I tried to hardcode a known good value, but that isn't even showing up on index.html:

cur = db.execute('select * from t0109161144 where pluginID is 19506')

After posting here, I can see where I definitely have unnecessary code, but I would just like this one part of the application working and then I'll work on cleaning up the code. Any pointers or advice would be greatly appreciated, thanks!

Aucun commentaire:

Enregistrer un commentaire