Flask Application with MongoDB Cluster

Flask Application with MongoDB Cluster

·

2 min read

A few days back I've published an article about MongoDB explaining its use cases and how it is solving the industry problems efficiently. Now it's time to do some practical, in this article I'm gonna use CURD operations in the MongoDB cluster using the Python Flask application.

First let's create MongoDB Cluster:-

To create the cluster go to the MongoDB website. Sign up with Email and set up your account.:- setupacc-1.jpg

Choose the Free tier to use free services:- setupacc-2.jpg

Select the Cloud service provider and availability zone:- setupacc-3.jpg

Now the cluster is created, go to the collections to create the new database:- setupacc-4.jpg

Click on Add my own data :- setupacc-5.jpg

Give the database name and collections name and click on create :- setupacc-6.jpg

Now the database is created, go to the overview and on the right-centre corner click on connect :- setupacc-8.jpg

First, you have to configure the firewall you can either set your own IP or you can set 0.0.0.0/0 so that any computer can connect to the cluster:- setupacc-7.2.jpg

Now create the user and password :- setupacc-7.1.jpg

Now at the bottom click Choose a connection method :- setupacc-7.jpg

Click on the button Connect your application :- 9.jpg

It will give you a connection string copy this connection string to your python code, don't forget to replace the database name , username and password . 10.jpg

My connection string looks like this:-

mongodb+srv://admin:ab12345678cd@cluster0.gx5mz.mongodb.net/mydb?retryWrites=true&w=majority

Now its time for the Flask App:-

So I've created three files:-

  • index.html (Main HTML file where I've created all the inputs)
  • app.py (Python file where I've written the flask app code)
  • res.html (HTML file with the jinja templating where all the responses are shown)

three files.jpg

Index.html:-

hotmlcode1.jpg htmlcode2.jpg

App.py:-

pycode1.jpg pycode2.jpg

Res.html:-

resfile.jpg

So these are the files, now its time to run the code:-

flask run

It will run the application, and by default, it runs on http://127.0.0.1/5000 .

app opened in browser.jpg

Now if you insert something in the fields and click on the Submit Query button:- insert.jpg

Even if you check the database:- saved in database.jpg

If you found a error like this :- cert error.jpg Just change your connection string from:-

mongodb+srv://admin:<password>@cluster0.gx5mz.mongodb.net/<database_name>?retryWrites=true&w=majority

To this :-

mongodb+srv://admin:<password>@cluster0.gx5mz.mongodb.net/<database_name>?ssl=true&ssl_cert_reqs=CERT_NONE

So now our task is complete of connecting Flask application with MongoDB cluster.

Thank you!!