SQLAlchemy as a back-end for flask-restful CRUD modules

1   Introduction

Previous blog post described the use of Flask and flask-restful CRUD application with the use of SQLObject as a back-end store. See: http://www.davekuhlman.org/python-flask-restful-rest-crud.html.

This post reworks that example and substitutes the SQLAlchemy ORM in place of SQLObject for database storage.

You can click here to to download this new code.

There is lots of information and help with SQLAlchemy here: http://www.sqlalchemy.org/.

You can use the same set of shell scripts to test the various operations: create, read, update, and delete. See: http://www.davekuhlman.org/python-flask-restful-rest-crud.html#testing.

2   Notes and explanation

Here are a few notes on the differences between the module that used SQLObject and this one which uses SQLAlchemy:

  1. See function open_db for changes in the way that we connect to our database. This example uses the SQLite3 back-end and stores our data in a file. Also, note that we only create the table if the data file does not exist.
  2. Our query has changed in function get_task_by_name and also in the get method of our handler class.
  3. Notice the comment lines containing "begin fill-in" and "end fill-in". I used the template from a previous post to create this module. See: http://www.davekuhlman.org/flask-restful-crud-template.html.
  4. With SQLObject our database was automatically updated when we changed or created a database object. However, with SQLAlchemy we need to do an explicit commit: SQLSession.commit().