Rethink Flask - a Simple Todo List Powered by Flask and RethinkDB

After a number of requests for a basic Flask and RethinkDB template, I decided to go ahead and write a blog post. This is that post.

BTW: We always welcome requests. If you have something you’d like us to write about, or build, shoot us an email.

Today we’ll be creating a simple todo list, which you’ll be able to modify to meet your own needs. Before beginning, I highly suggest reading over this article, which details how RethinkDB differs from some of the other NoSQL databases.

Set up RethinkDB

Install

Navigate here and download the appropriate package for your system. I used Homebrew – $ brew install rethinkdb – and it took almost twenty minutes to download and install the build:

Install the Python drivers globally:

1

$ sudo pip install rethinkdb

Note: I installed Rethink globally (outside of a virtualenv) since I’ll probably use the same version with a number of projects, with a number of different languages. We will be installing in within a virtualenv later on in this tutorial.

Run the app:

Don’t try to submit anything yet, because we need to get a database setup first. Let’s get RethinkDB going.

RethinkDB Config

Install RethinkDB:

1

pip install rethinkdb

Add the following code to “views.py”:

12345678910111213141516171819202122232425262728293031323334353637

# rethink importsimportrethinkdbasrfromrethinkdb.errorsimportRqlRuntimeError,RqlDriverError# rethink configRDB_HOST='localhost'RDB_PORT=28015TODO_DB='todo'# db setup; only run oncedefdbSetup():connection=r.connect(host=RDB_HOST,port=RDB_PORT)try:r.db_create(TODO_DB).run(connection)r.db(TODO_DB).table_create('todos').run(connection)print'Database setup completed'exceptRqlRuntimeError:print'Database already exists.'finally:connection.close()dbSetup()# open connection before each request@app.before_requestdefbefore_request():try:g.rdb_conn=r.connect(host=RDB_HOST,port=RDB_PORT,db=TODO_DB)exceptRqlDriverError:abort(503,"Database connection could be established.")# close the connection after each request@app.teardown_requestdefteardown_request(exception):try:g.rdb_conn.close()exceptAttributeError:pass

Check the comments for a brief explanation of what each of the functions do.

Start your server again.

You should see the following alert in your terminal:

1

Database setup completed

If you see this error rethinkdb.errors.RqlDriverError: Could not connect to localhost:28015. your RethinkDB server is not running. Open up a new terminal window and run $ rethinkdb.

So, we created a new database called “todo”, which has a table called “todos”.

You can verify this in the RethinkDB Admin. Navigate to http://localhost:8080/. The admin should load. If you click “Tables”, you should see the database and table we created:

Display Todos

With the database setup, let’s add code to display todos. Update the index() function in “views.py”: