INTERNET

How to Connect Your Flask App With CouchDB: A NoSQL Database

0

Connecting Flask with SQL databases like PostgreSQL and SQLite is a cinch. But the framework syncs perfectly with NoSQL databases like CouchDB, too. And as an added benefit, you can query your data easily when you use CouchDB with Flask.

Ready to make a change by using a NoSQL like CouchDB with your Flask app? Here's how to set CouchDB up on your local machine and connect it with Flask.

What Is CouchDB?

CouchDB is a NoSQL database currently owned by the Apache Software Foundation. Written with Erlang, the software was first released in 2005.

Unlike the regular table-linked databases you're most likely used to, CouchDB is a non-relational database management system that stores data as raw JSON.

CouchDB is non-blocking, so it doesn't lock the database during data input. One of the strong points of CouchDB is that it uses a multi-version concurrency control policy to read and write data. So it allows simultaneous inputs from multiple users without interference from the existing structure of the data in the database.

Thus, CouchDB is fast during queries and easy to work with while using asynchronous methods. That said, this doesn't make it any better than its SQL counterpart. Each technology has its pros and cons.

CouchDB Set Up

To start using CouchDB, download and install a compatible version from CouchDB's official website.

And if that latest version doesn't work for you, proceed to the CouchDB archive and download version 1.6.1, which is an earlier version of CouchDB.

Once you install CouchDB, run it on your PC like you would any other desktop app.

Open your browser. Then launch CouchDB's server by pasting the following into your address bar:

http://localhost:5984/_utils/index.html

Set Up Python and Flask

This tutorial, however, assumes that you already have Python installed on your PC. Otherwise, go to python.org and install the latest version of Python on your PC.

Once you set up CouchDB, create a project root folder. Then open up your command line to that directory and create a Python virtual environment.

Install the latest version of Flask in the virtual space using pip:

pip install flask

Connect Flask With CouchDB

To start using CouchDB with your Flask app, install Flask-CouchDB, the runtime package for connecting the database with Flask.

To do this:

pip install Flask-CouchDB

Once you install Flask-CouchDB successfully, create an app.py file in that root folder. Similarly, create a database.py file—this handles your database creation.

Open database.py and import the following packages:

from couchdb import Server

Next, create your database in that same file using the following block of code:

from couchdb import Serverserver = Server()db = server.create('muocouch')

Execute database.py via the CLI. Then open or refresh CouchDB's local server via your browser as you did earlier. You should now see the database (muocouch in this case) listed in CouchDB.

Note: Ensure that you use a lower-case naming convention for databases, as CouchDB might not accept upper or mixed cases.

Store Your First CouchDB Data Using Flask

Ultimately, the purpose of any database is data storage. Once you have a database in CouchDB, you can start storing data into it from your Flask app right away.

To start, open app.py and import the following packages:

from flask import Flaskfrom couchdb import Serverfrom flaskext.couchdb import Document

Next, create a Flask app and CouchDB server instance:

app = Flask(__name__, static_url_path='/static')app.debug=Trueserver = Server()

Now let's store some user inputs into CouchDB:

@app.route('/', methods=['GET', 'POST'])def register():user = {"username":"media site", "email":"justmail@gmail.com","password":"encrypteddata"}db = server['muocouch'] #select the databasedoc_id, doc_rev = db.save(user) #store your data in th databasereturn "<h2>Your data should now be in the database</h2>"

If you like, you can set your Flask server to the development mode before running it.

To do this, run the following command via your CLI:

set FLASK_ENV=development

Note that setting the server mode is optional. It only makes debugging your code hassle-free.

But regardless of the server mode setting, here's how to start the Flask server via the CMD:

flask run

Flask, however, defaults your port to localhost:5000. You should now see the message in the H2 tag once you load this address via your browser.

Validate Data and Check Duplicates Using CouchDB Queries

To standardize this further, you can use queries to validate inputs and prevent duplicates in your database. Querying CouchDB is a bit different from how you do this with SQL databases.

CouchDB uses what it calls "JavaScript views" to query data from the database. Fortunately, this is relatively simple.

Before you progress further, here's how a basic CouchDB query view looks:

map_func = '''function(doc) { emit(doc.doc_rev, doc); }''' myQuery = [docType].query(db, map_func, reduce_fun=None)

Now let's use the above code practically:

#Create a document object model called "Users:"class User(Document):    doc_type = 'User'@app.route('/', methods=['GET', 'POST'])def register():   user = {   "username":"media site",    "email":"justmail@gmail.com",   "password":"encrypteddata"   }   db = server['muocouch'] #select the database   # Use the view function to fetch your data from CouchDB   map_func = '''function(doc)    { emit(doc.doc_rev, doc); }'''   # Get all the data by running a query set   myQuery = User.query(db, map_func, reduce_fun=None, reverse=True)   q = [i['username'] for i in myQuery] # Loop out all the usernames from the database   q2 = [i['email'] for i in myQuery] # Loop out all the email addresses from the database   q3 = q+q2 # Merge both queries into a single list   print(q3)   return "<h2>Your data is now in the database</h2>"

The code above uses the User class to query the data fetched by the view function. Pay close attention to the parameters within the query set (myQuery).

Printing q3, as you did above, should now output all the usernames and email addresses in the database within the command line.

So here's how you can use this query to validate users' inputs:

if not (user['username'] in q3 or user['email'] in q3):#store your data into the database if itdoesn't existdoc_id, doc_rev = db.save(user) return "<h2>Registered successfully</h2>"else:return "<h2>Username or email exists</h2>"

Refreshing your browser returns the else statement each time you try to input a username or an email that's already in the database. And if you're entering a new one, it successfully stores your data by executing the if condition.

That's it! You just created your first NoSQL database using Flask-CouchDB.

Although creating and querying databases in CouchDB revolves around the examples we highlighted here, you can scout Flask's functionalities further. For instance, you can spin up input fields using wtforms and flag duplicates using Flask's message flash.

You can even pass your query over to JavaScript's jQuery to validate inputs and check duplicates asynchronously.

Is CouchDB Better Than SQL Databases?

Using CouchDB or any other NoSQL database with Flask or any other programming technology depends on your preference. But it comes in handy while dealing with structureless data and raw media.

That said, before you decide, you might want to look at the differences between NoSQL and SQL databases to help you decide which of them is suitable for your project.

admin

How to Use Scene Cut Detection in DaVinci Resolve

Previous article

Safari on macOS Monterey: What’s New, and How to Test it Now

Next article

You may also like

Comments

Leave a reply

Your email address will not be published. Required fields are marked *

More in INTERNET

Login/Sign up