Fine Radar
The News Hub

Sending Data from a Flask app to MongoDB Database – GeeksforGeeks

This article covers how we can configure a MongoDB database with a Flask app and store some data in the database after configuring it. Before directly moving to the configuration phase here is a short overview of all tools and software we will use.

MongoDB is an open-source database that stores data in JSON-like documents. It is classified as a NoSQL database because it is based on different fundamentals as compared to a SQL relational database.

Prerequisites

  • A decent understanding of Python and a machine with Python installed.
  • Understanding of basic concepts of Flask.
  • MongoDB is installed on your local machine if not you can refer to this article.

Configuring MongoDB

Till this step, you have a local machine with MongoDB installed on it now run the MongoDB compass and the following screen will appear. You can edit the settings or just click connect and MongoDB will be running on your local machine.

 

Setup a Development Environment

Let’s configure the virtual environment for development, this step can be skipped but it is always recommended to use a dedicated development environment for each project to avoid dependency clash, this can be achieved using a Python virtual environment.

# Create gfg folder
$ mkdir gfg

# Move to gfg folder
$ cd gfg

 

We created a folder named `gfg` for the project, you can name it anything you want and cd (change directory) to go into your newly created directory then run the following command that will create a virtual environment for your project.

$ python -m venv venv

Now to use the virtual environment we need to first activate it, this can be done by executing the activated binary file.

$ .\venv\Scripts\activate # for Windows OS
$ source venv/bin/activate # for Linux OS

 

Installing Dependencies for the Project

We are done configuring a development environment now let us install the tools that we will be using including Flask, `pymongo` which provide the interface for Python-based apps to the MongoDB database.

$ pip install Flask pymongo

 

Next, we’ll connect a FLask app to MongoDB and send some data into it.

Creating a Flask App

We are done with the database setup and installing the required libraries now we will create a Flask app and connect it to the MongoDB we created and insert some user data into it. First, let’s create a Flask app as follows.

Create a `main.py` file in the project directory and add the following code to the file.

Python3

from flask import Flask

  

app = Flask(__name__)

  

  

@app.route('/')

def hello_world():

    return 'Hello, World!'

  

  

if __name__ == '__main__':

    app.run()

Over here we have created a starter Flask App with a single route that returns a string “Hello, World!”, Now test this thing out by running the app as shown below:

Output:

 

The app is up and running now let us test the output at `http://127.0.0.1:5000`,

 

Connecting Flask App to Database

We have got a running starter Flask App with some basic code let’s connect it to the MongoDB database using the following script.

Python3

from flask import Flask, request

from pymongo import MongoClient

  

app = Flask(__name__)

  

db = client['demo']

collection = db['data']

The above script will connect to the MongoDB database that we configured earlier now we need a post route to add some data in the database which can be done as follow:

Python3

@app.route('/add_data', methods=['POST'])

def add_data():

    

    data = request.json

  

    

    collection.insert_one(data)

  

    return 'Data added to MongoDB'

Here we created a route named `/add_data` which when invoked with a post request reads the JSON data from the body and inserts it into the database.

For reference here is the overall code that I used for the demo.

Python3

from flask import Flask, request

from pymongo import MongoClient

  

app = Flask(__name__)

  

@app.route('/')

def hello_world():

    return 'Hello, World!'

  

  

db = client['demo']

  

collection = db['data']

  

@app.route('/add_data', methods=['POST'])

def add_data():

    

    data = request.json

  

    

    collection.insert_one(data)

  

    return 'Data added to MongoDB'

  

  

if __name__ == '__main__':

    app.run()

Sending Data from Flask to MongoDB

Now let us test the entire script and if we can insert some data into the database using it, First run the Flask App shown before then make a POST request to `/add_data` a route using a tool like Postman.

 

The response above looks fine let us check the MongoDB database if there is any data inserted or not.

 

As you can see a database named demo is created with a collection of `data` with a single document that we just inserted using Flask.

 

Stay connected with us on social media platform for instant update click here to join our  Twitter, & Facebook We are now on Telegram. Click here to join our channel (@TechiUpdate) and stay updated with the latest Technology headlines. For all the latest Technology News Click Here 

Read original article here

Denial of responsibility! FineRadar is an automatic aggregator around the global media. All the content are available free on Internet. We have just arranged it in one platform for educational purpose only. In each content, the hyperlink to the primary source is specified. All trademarks belong to their rightful owners, all materials to their authors. If you are the owner of the content and do not want us to publish your materials on our website, please contact us by email – [email protected]. The content will be deleted within 24 hours.
Leave A Reply

Your email address will not be published.