Movatterモバイル変換


[0]ホーム

URL:


Open In App
Next Article:
Making a Flask app using a PostgreSQL database
Next article icon

This article covers how we can configure aMongoDB database with aFlask 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 inJSON-like documents. It is classified as aNoSQL database because it is based on different fundamentals as compared to aSQL relational database.

Prerequisites

  • A decent understanding ofPython and a machine withPython installed.
  • Understanding of basic concepts ofFlask.
  • MongoDB is installed on your local machine if not you can refer to thisarticle.

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 Pythonvirtual 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 includingFlask, `pymongo` which provide the interface for Python-based apps to theMongoDB 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 willcreate 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
fromflaskimportFlaskapp=Flask(__name__)@app.route('/')defhello_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
fromflaskimportFlask,requestfrompymongoimportMongoClient# Flask app objectapp=Flask(__name__)# Set up MongoDB connectionclient=MongoClient('mongodb://localhost:27017/')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'])defadd_data():# Get data from requestdata=request.json# Insert data into MongoDBcollection.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
fromflaskimportFlask,requestfrompymongoimportMongoClientapp=Flask(__name__)# root route@app.route('/')defhello_world():return'Hello, World!'# Set up MongoDB connection and collectionclient=MongoClient('mongodb://localhost:27017/')# Create database named demo if they don't exist alreadydb=client['demo']# Create collection named data if it doesn't exist alreadycollection=db['data']# Add data to MongoDB route@app.route('/add_data',methods=['POST'])defadd_data():# Get data from requestdata=request.json# Insert data into MongoDBcollection.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 likePostman.

 

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.


Improve
Practice Tags :

Similar Reads

We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood ourCookie Policy &Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences

[8]ページ先頭

©2009-2025 Movatter.jp