Setting Up Flask with MongoDB using PyMongo
Overview
MongoDB is a very popular NoSQL database that can also be used with Flask. MongoDB Flask is a web framework that allows users to create dynamic web applications. PyMongo is a library of Python that enables a convenient working interface for MongoDB. PyMongo allows you to perform various database operations with your Python application.
Introduction to Flask
MongoDB Flask is a lightweight framework of Python that gives features and tools for web application creation in Python Programming Language. Flask allows the faster development of applications. MongoDB and Flask are popular technologies, and they are used together for application development. MongoDB allows data storage flexibly, and Flask is a web framework. Both are, when used together, then used for the development of dynamic web applications.
Prerequisites
- A machine in which Python is already installed.
- Good knowledge of the Python programming language.
- Basic flask concept understanding.
- A machine installed with the MongoDB
MongoDB Configuration
As MongoDB is already in your system, open the MongoDB compass on your machine. And the screen similar to the screen shown below is opened in your system. You can connect by just clicking the connect, or you can also modify the settings if required. And after connecting now on your local system, MongoDB starts running.
Creating Development Environment
Now for the development, virtual environment configuration is required, we can also skip this step, but to prevent dependency clashes, it is always recommended for every project to use the dedicated development environment for every individual project.
Here we are using the mkdir command for creating the folder, and we are creating the folder with the name project, but we can make the folder with any name we desire. After that use the cd command to go into the folder created recently. Now for creating a virtual environment for your project, run the command given below.
Now for utilizing the virtual environment, firstly it is required to activate it, and we can achieve this by the activated binary file execution.
Steps to Set Up Flask with MongoDB Using PyMongo
PyMongo and Flask Setup
The MongoDB PyMongo Library and Flask are installed and set up in this step. With your activated virtual environment, for installing PyMongo and Flask, use the pip command.
After the successful completion of the installation, a line similar to the line given below is displayed on your system in the last of your output. Output:
Now the required Python packages are installed successfully, and you can create a collection after connecting with your server.
Connecting to the Server
Now we will create a client by using the PyMongo library, which is used for interaction with the MongoDB server, database creation, and collection creation. Open an app.py file by our activated programming environment inside the directory named project.
All the required helpers and classes are imported by it from the PyMongo library and MongoDB Flask. You can perform an interaction with the MongoDB server for the database and collection creation for storing the todos. Insert the line of code given below in your app.py file.
Here we have imported the Flask class, which is used for Flask application instance creation named app. We also have MongoClient for client object creation which allows the interaction and connection with the MongoDB server.
A MongoDB database named flask_db can be created by using the client instance. And in a variable db, save a reference to it. With the help of the db variable, a collection named todos can be created on flask_db. A group of documents in MongoDB is stored in the MongoDB collection, such as tables present in relational databases.
Creating Collections and Models
There is a lazy creation of databases and collections in MongoDB, even after the execution of the app.py file, until the creation of the first document, no code related to the database will execute. In the next step, you have to design a small flask application along with the page so that s will be able to add todos documents in your created todos collection.
The flask_db database and the todos collection will be created on the MongoDB server after the insertion of the first to-do document. Now create a web page along the web form so that users will be able to insert todos.
Creating Webpage to Add and Display Todos
Open the app.py file for modification with your activated programming environment.
Firstly add the imports given below from the flask
Add the route given below at the end of the file.
The next step is to create the folder with the name templates in the directory and add the template named index.html in it.
Add the code given below in the file index.html:
When the virtual environment is activated in your directory, then with the help of the FLASK_APP environment variable tell the flask about the application. Set the FLASK_ENV environment variable to development so that application can be run in development mode and can access debuggers. Follow the following commands to implement it.
The next step is to run the application
Visit the URL given below by the browser while the development server is running.
There appears an index page along with an input field for todo content, two radio buttons, and a submit button. Output:
After Filling out the form and submitting it, a POST request was sent to the server, but nothing worked as the POST request was not handled on the route. Open the new terminal.
For handling the POST requests submitted by the user and inserting the data in the todos, you have to open the app.py.
In these changes, POST requests are handled in the condition of request.method == 'POST'. Using the request.form object, you can access the todo content. For the insertion of todos documents in the todos collection, implement insert_one(). And find() method is used to display all the saved todos. Implement this method outside the code that is designed for handling the POST requests, so that it can return all todo documents stored on the todos collection. A variable name all_todos can store the todos from the database. Edit the function call render_template() so that the list of todo documents can be passed to the template index.html and it is present in the template in a variable named todos.
Trashing Todos
Now next step is to the addition of a route for allowing the user for todos delete by clicking on the button.
Firstly, a new route /id/delete/ will be added by which POST requests will be accepted. The ID of the todo required to be deleted is received by the delete_one() method, and then that received ID is used for the deletion of the particular todo.
You receive an ID in the form of a string for todo deletion. And now it is required to convert that in the ObjectID form before sending it to the delete method of the collection. So it required the ObjectId() class importing from the BSON module, by which encoding and decoding of BSON (Binary JSON) are handled. For performing the modification, open the app.py file:
Firstly in the file, at the top, add the import given below:
And here, for converting string IDs intoObjectID objects, we are using the ObjectID() class. And add the route.
The ID of the todo that is required to be deleted is received by the function. This received ID is passed to the delete_one() method and uses the ObjectId() class for converting the ID you received into the ObjectID form.
After successful todo deletion, the user is redirected to the index page. Now perform modification in index.html file for adding the DELETE todo button:
Add a new <form> tag in the loop:
Now save the file and refresh the page, and the delete Todo button is displayed with every todo time. Now you can click on it for todo deletion and confirm it. After successful deletion, the user will be redirected to the index page. Before deleting todo, we have the following view:
After deleting the todo1:
To confirm that deletion is performed successfully, run the find() function from the Mongo shell. And you will find that all the deleted items are no longer displayed.
MongoDB Example
Here is a complete example of performing CRUD operations. In this code, we are taking the roll_no and name as the parameters for the Student model
Output:
For storing data in the database:
After this, data will be added to the database. [IMAGE_4 FINISH]
Fetching particular student data via their id:
Deleting particular student data via their id:
FAQs
Q. How MongoDB can be installed for using Flask?
A MongoDB is a database that we need to download and then install. After the successful installation of MongoDB pip install flask pymongo command is used for using MongoDB Flask and PyMongo library.
Q. What is Flask?
A. MongoDB Flask is a lightweight framework of Python with features and tools provided for web application creation in Python Programming Language. Flask allows the faster development of applications.
Conclusion
- MongoDB Flask is a lightweight framework of Python that gives features and tools for web application creation in Python Programming Language.
- For preventing dependency clashes, it is always recommended to perform virtual environment configuration.
- pip install Flask pymongo is used for installing MongoDB PyMongo Library and Flask.
- There is a lazy creation of databases and collections in MongoDB, even after the execution of the app.py file, until the creation of the first document.
- For the insertion of documents in the collection, implement insert_one(). And find() method is used to display all the saved documents.
- delete_one() method is used for deleting a particular document from the collection.