Wednesday, March 20, 2013

Paint Application Using Flask and Sqlite3


     Now, I have rewritten the paint application in Google AppEngine using Flask framework.The html frontend and javascript are same.Please refer my earlier post about paint application for more info.Instead of google datastore, sqlite3 was used for data storage.I will explain how to connect to database and retrive data from it.


def connect_db():
    return sqlite3.connect('paint.db')

@app.before_request

def before_request():
    g.db = connect_db()
    g.db.execute("CREATE TABLE IF NOT EXISTS drawings(fname string primary key, img_data text)")
@app.after_request
def after_request(response):
    g.db.close()
    return response

First we define a function 'connect_db()' for connecting to database before requesting.Then create a table in database file(paint.db) for storing fname and img_data.


@app.route('/', methods=['GET', 'POST'])
def paint():
    if request.method == 'GET':
        py_all = {}
        all_data = g.db.execute("SELECT * FROM drawings")
        for data in all_data:
            py_all[data[0]] = data[1]
        return render_template('paint.html', py_all= py_all)
    elif request.method == 'POST':
        filename = request.form['fname']
        data = request.form['whole_data']
        g.db.execute("REPLACE INTO drawings(fname, img_data) VALUES (?, ?)", (filename, data));
        g.db.commit()
        return redirect('/')

          In GET method the data executed from database is render to  paint.html file.The data taken from data base is stored in 'py_all' object.When user tries to save the image, server gets a POST request.  the image name and its data are saved into a table using the sqlite3 module available in python. Sqlite3 is a basic database interface available in python.
The code can be found Here

1 comment: