Facebook Twitter Instagram
    Facebook Twitter Instagram Pinterest Vimeo
    Hand On CodeHand On Code
    Hand On CodeHand On Code
    Home»Flask»Rethink Flask A Simple Todo List Powered by Flask and RethinkDB
    Flask

    Rethink Flask A Simple Todo List Powered by Flask and RethinkDB

    March 30, 2023No Comments6 Mins Read
    Share
    Facebook Twitter LinkedIn Pinterest Email

    After a lot of inquiries about a fundamental Flask and RethinkDB template, I made up my mind to go ahead and compose an article for this blog. This is the post in question.

    FYI: Your requests are always welcome here. Send us an email with any suggestions you may have on the topics we cover or the products we develop.

    We are going to put up a basic to-do list that you will be able to adapt to fit your specific requirements as we work on it together today. Before getting started, I strongly recommend reading this essay in its entirety. It explains how RethinkDB is unique among the many alternative NoSQL databases.

    databases.

    Set up RethinkDB

    Install RethinkDB

    Just go to this link and download the file that corresponds to your operating system. I downloaded and installed the software with the help of Homebrew ($ brew install rethinkdb), and the process took approximately twenty minutes.

    build:

    ==> Installing rethinkdb
    ==> Downloading http://download.rethinkdb.com/dist/rethinkdb-     1.11.2.tgz
    ######################################################################## 100.0%
    ==> ./configure --prefix=/usr/local/Cellar/rethinkdb/1.11.2 --  fetch v8 --fetch protobuf
    ==> make
    ==> make install-osx
    ==> Caveats
    To have launchd start rethinkdb at login:
      ln -sfv /usr/local/opt/rethinkdb/*.plist   ~/Library/LaunchAgents
    Then to load rethinkdb now:
      launchctl load   ~/Library/LaunchAgents/homebrew.mxcl.rethinkdb.plist
    ==> Summary
    beer_mug  /usr/local/Cellar/rethinkdb/1.11.2: 174 files, 29M, built in   19.7 minutes
    

    Install the Python drivers globally

    $ sudo pip install rethinkdb
    

    Note that I have installed Rethink globally (rather than inside a virtual environment) since it is likely that I will use the same version across a variety of projects written in a variety of languages. Later on in this process, we will be installing inside of a virtual environment.

    tutorial.

    Test your setup

    To begin, let’s begin the process of starting the server using the following.

    command:

    $ rethinkdb
    

    If everything was installed properly, you should see something that looks like this.

    to:

    info: Creating directory /Users/michaelherman/rethinkdb_data
    info: Creating a default database for your convenience. (This is because you ran 'rethinkdb' without 'create', 'serve', or '--join', and the directory '/Users/michaelherman/rethinkdb_data' did not already exist.)
    info: Running rethinkdb 1.11.2 (CLANG 4.2 (clang-425.0.28))...
    info: Running on Darwin 12.4.0 x86_64
    info: Loading data from directory    /Users/michaelherman/rethinkdb_data
    info: Listening for intracluster connections on port 29015
    info: Listening for client driver connections on port 28015
    info: Listening for administrative HTTP connections on port 8080
    info: Listening on addresses: 127.0.0.1, ::1
    info: To fully expose RethinkDB on the network, bind to all addresses
    info: by running rethinkdb with the `--bind all` command line option.
    info: Server ready
    

    The connection should then be tested. Launch a new tab on your computer’s terminal and type in the commands below.

    commands:


    >>>

    $ python
    >>> import rethinkdb
    >>> rethinkdb.connect('localhost', 28015).repl()
    

    You need to do this.

    see:


    >>>

    <rethinkdb.net.Connection object at 0x101122410>
    

    Leave the Python shell going, but close the second terminal window where the RethinkDB server is running.

    window.

    Set up a Basic Flask project

    Create a directory to store your project

    $ mkdir flask-rethink
    $ cd flask-rethink
    

    Set up and

    $ virtualenv --no-site-packages env
    $ source env/bin/activate
    

    Install Flask and Flask-WTF

    $ pip install flask
    $ pip install flask-wtf
    

    Create a Pip requirements file

    $ pip freeze > requirements.txt
    

    Download the Flask boilerplate

    Discovered in this repository’s directory devoted to templates. This is what the structure of your project should look like today.

    this:

    ├── app
    │   ├── __init__.py
    │   ├── forms.py
    │   ├── models.py
    │   ├── templates
    │   │   ├── base.html
    │   │   └── index.html
    │   └── views.py
    ├── readme.md
    ├── requirements.txt
    └── run.py
    

    Run the app

    $ python run.py
    

    You should see the following when you go to http://localhost:5000/ in your web browser:

    Rethink Flask A Simple Todo List Powered by Flask and RethinkDB

    Do not attempt to submit anything just now since we are in the process of setting up a database first. Let’s get RethinkDB

    going.

    RethinkDB Config

    Install RethinkDB

    $ pip install rethinkdb
    

    Add the following code to “views.py”

    # rethink imports
    import rethinkdb as r
    from rethinkdb.errors import RqlRuntimeError
    # rethink config
    RDB_HOST =  'localhost'
    RDB_PORT = 28015
    TODO_DB = 'todo'
    # db setup; only run once
    def dbSetup():
        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'
        except RqlRuntimeError:
            print 'Database already exists.'
        finally:
            connection.close()
    dbSetup()
    # open connection before each request
    @app.before_request
    def before_request():
        try:
            g.rdb_conn = r.connect(host=RDB_HOST, port=RDB_PORT, db=TODO_DB)
        except RqlDriverError:
            abort(503, "Database connection could be established.")
    # close the connection after each request
    @app.teardown_request
    def teardown_request(exception):
        try:
            g.rdb_conn.close()
        except AttributeError:
            pass
    

    If you check the comments, you’ll get a concise description of what each of the functions does.

    do.

    Start your server again

    It is possible that you could receive the following warning in your

    terminal:

    Database setup completed
    

    In the event that you notice the message rethinkdb.errors.RqlDriverError: Unable not connect to localhost:28015, please contact support. It seems that your RethinkDB server is not active. Launch a fresh terminal window and type in the command $ rethinkdb.

    As a result, we devised a brand-new database that we named “todo.” Inside this database is a table that we dubbed “todos.”

    The RethinkDB Admin is where you can check this for yourself. Go to http://localhost:8080/ in your web browser. The administrator needs to load. When you choose “Tables,” you should see the database and table that we developed, which are as follows:

    Rethink Flask A Simple Todo List Powered by Flask and RethinkDB

    Display Todos

    Now that the database is prepared, let’s add the code necessary to show the to-do list. Make sure the index() function in is up to date.

    “views.py”:

    @app.route("/")
    def index():
        form = TaskForm()
        selection = list(r.table('todos').run(g.rdb_conn))
        return render_template('index.html', form=form, tasks=selection)
    

    At this point, we are picking the “todos” table, extracting all of the data, which is formatted as JSON, and sending the complete table to the.

    template.

    Add data manually

    In order to examine any of the to-dos, we will need to first create some of them. Let’s go through the motions of adding them in, shall we?

    manually.


    >>>

    $ python
    >>> import rethinkdb
    >>> conn = rethinkdb.connect(db='todo')
    >>> rethinkdb.table('todos').insert({'name':'sail to the moon'}).run(conn)
    {u'errors': 0, u'deleted': 0, u'generated_keys': [u'c5562325-c5a1-4a78-8232-c0de4f500aff'], u'unchanged': 0, u'skipped': 0, u'replaced': 0, u'inserted': 1}
    >>> rethinkdb.table('todos').insert({'name':'jump in the ocean'}).run(conn)
    {u'errors': 0, u'deleted': 0, u'generated_keys': [u'0a3e3658-4513-48cb-bc68-5af247269ee4'], u'unchanged': 0, u'skipped': 0, u'replaced': 0, u'inserted': 1}
    >>> rethinkdb.table('todos').insert({'name':'think of another todo'}).run(conn)
    {u'errors': 0, u'deleted': 0, u'generated_keys': [u'b154a036-3c3b-47f4-89ec-cb9f4eff5f5a'], u'unchanged': 0, u'skipped': 0, u'replaced': 0, u'inserted': 1}
    >>>
    

    After establishing a connection to the database, we added three new entries to the table that is included inside the database. For further details, have a look at the API documentation.

    Prepare to start the server. At this point, you should see the following three tasks:

    Rethink Flask A Simple Todo List Powered by Flask and RethinkDB

    Finalize the form

    Make the necessary changes to the index() method so that the data can be extracted from the form and added to the

    database:

    @app.route('/', methods = ['GET', 'POST'])
    def index():
        form = TaskForm()
          if form.validate_on_submit():
              r.table('todos').insert({"name":form.label.data}).run(g.rdb_conn)
              return redirect(url_for('index'))
          selection = list(r.table('todos').run(g.rdb_conn))
          return render_template('index.html', form = form, tasks = selection)
    

    Try it out and see. Add some todos. Go insane.

    Learn Python free Python Code Python Course Free download python coursefree Courses Download Python Language Rethink Flask A Simple Todo List Powered by Flask and RethinkDB
    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    Previous ArticleFunctional Programming in Python When and How to Use It
    Next Article Build a Flashcards App With Django

    Related Posts

    python

    Class method vs Static method in Python

    April 7, 2023
    python

    Python Program to Count the Number of Matching Characters in a Pair of String

    April 7, 2023
    python

    Coroutine in Python

    April 7, 2023
    Add A Comment

    Leave A Reply Cancel Reply

    Facebook Twitter Instagram Pinterest
    © 2023 ThemeSphere. Designed by ThemeSphere.

    Type above and press Enter to search. Press Esc to cancel.