Simple Python Flask Program with MongoDB

This is a sample Python Flask program uses mongodb as database.

Introduction

In this article, we are going to create a simple Python Flask application with MongoDB as database.

Background

We use Flask framework to build REST APIs and also use Pymongo to connect flask with MongoDB.

Implementation

We are going to create a sample python web application using Flask framework and MongoDB. It is very easy to work with flask as well as mongodb.

Download python from https://www.python.org/downloads/.

You can select the Customize installation for adding python environment variables.

If you choose default installation, please set these variables manually.

Image 1

Please click Add Python 3.7 to PATH option. It will add one entry in environment variable.

Image 2

If needed, you can modify the installation path. Please select the Python to environment variables.

After successful installation, if you check the system environment variable, you can see the below two entries are added in the system.

Image 3

We installed the python 3.7 version, so it added as Python 37-32.

Also note that Python37-32\Scripts folder is used for handling additional packages needed for python.

Now you can check the python and PIP version in command prompt. PIP is the abbreviation for python package index which is used for installing, upgrading or removing the additional python libraries from our system.

> python --version and pip -- version

Image 4

By default, pip version may not be 18. This is the latest version as of today. If your pip version is older than it, please upgrade it.

>python -m pip install -U pip

Now we are going to install Flask. Flask is a web framework for python. Flask provides you with tools, libraries and technologies that allow you to build a web application in python.

Its dependencies are:

  • Werkzeug a WSGI utility library
  • jinja2 which is its template engine

WSGI is basically a protocol defined so that Python application can communicate with a web-server and thus be used as web-application outside of CGI.

Jinja2 is used for creating views in flask application. It holds all the static files like HTML, CSS and JavaScript files.

First, install Flask using pip command in command prompt.

>pip install Flask

It will install the latest version of Flask library from its global repository and in Windows machines, it saved the below file location:

C:\Program Files (x86)\Python\Python37-32\Lib\site-packages

Our sample application uses MongoDB as database. So, we are going to install MongoDB from the below URL.

It is a free community version. After successful installation, it is all set to run mongodb instance.

Before running the mongodb instance, we must create a data folder and run the below command in command prompt.

"C:\Program Files\MongoDB\Server73499.0\bin\mongod.exe" --dbpath="C:\mongo-data"

Here, C:\mongo-data folder is used for saving mongodb files.

While installing the mongodb in Windows system, you can choose the compass community edition also.

This is a free edition and will help to handle our mongodb databases, collections (tables in mongodb) and documents (records) graphically.

Image 5

By default, mongodb is running in localhost 27017 port.

We can see that there are 3 databases (adminconfig and local) that are created automatically in the installation time.

Image 6

Now we are going to install PyMongo library in python. PyMongo is a simple but powerful python distribution containing tools for working with mongodb and is the recommended way to work with mongodb from python. It's a kind of ODM (object document mapper). There is mongoengine and so many libraries also available as ODM for python.

>pip install pymongo

We need to install another Python library bson too. It is used for getting objectId property of mongodb document.

>pip install bson

Now we are all set and ready to start our Python program.

Create a folder named FlaskwithMongo and add two sub folders, static and templates inside it.

There is a convention to name like static and templates used in jinja2 framework.

Please open the folder in any of the code editors. I am using Visual Studio code as an IDE.

경축! 아무것도 안하여 에스천사게임즈가 새로운 모습으로 재오픈 하였습니다.
어린이용이며, 설치가 필요없는 브라우저 게임입니다.
https://s1004games.com

Create a new file named app.py. This is the only Python file we have used in this application.

First, we are going to import the required libraries into our application.

from flask import Flask, render_template,request,redirect,url_for # For flask implementation
from bson import ObjectId # For ObjectId to work
from pymongo import MongoClient
import os

Now we are going to declare the app variable in our program.

app = Flask(__name__)

This app variable is used in the entire application.

Now we are going to declare two variables, title and heading which are later used in jinja2 template.

title = "TODO sample application with Flask and MongoDB"
heading = "TODO Reminder with Flask and MongoDB"

We must declare the connection string for mongodb and select a database. Also, we are going to select our collection name to a variable.

client = MongoClient("mongodb://127.0.0.1:27017") #host uri
db = client.mymongodb #Select the database
todos = db.todo #Select the collection name

As I mentioned earlier, mongodb is running in the port 27017 by default. Please note that we have selected mymongodb as database and todo as collection name. When we create our first transaction, pymongo will generate the database and collection automatically. Unlike SQL server or any other RDBMS, mongodb doesn’t require predefined schemas.

In flask, it is easy to implement routing unlike any other programming language.

For that, we are using render_templaterequestredirect and url_for. All these methods helped us to establish redirection and show HTML templates in the browser.

def redirect_url():
    return request.args.get('next') or \
        request.referrer or \
        url_for('index')

In the above code, we defined a method named redirect_url and it is used to redirect page to index page.

@app.route("/")
@app.route("/uncompleted")

def tasks ():
    #Display the Uncompleted Tasks
    todos_l = todos.find({"done":"no"})
    a2="active"
    return render_template('index.html',a2=a2,todos=todos_l,t=title,h=heading)

In the above code, we defined a method named tasks and it is used for two routes. One for default “/” route and another for “/uncompleted” route. In this code, we defined a variable todos_l and it gets the documents from mongodb filter by condition done equal to no. We defined one more variable named a2 and it is used for controlling active records. Both todos_l and a2 variables passed with other two variables, title and heading and passed to the jinja2 template index.html which we must create in the template folder.

Now we are going to finish all the remaining route definitions for adding and deleting the documents to mongodb.

app.py

from flask import Flask, render_template,request,redirect,url_for # For flask implementation
from bson import ObjectId # For ObjectId to work
from pymongo import MongoClient
import os

app = Flask(__name__)

title = "TODO sample application with Flask and MongoDB"
heading = "TODO Reminder with Flask and MongoDB"

client = MongoClient("mongodb://127.0.0.1:27017") #host uri
db = client.mymongodb #Select the database
todos = db.todo #Select the collection name

def redirect_url():
    return request.args.get('next') or \
        request.referrer or \
        url_for('index')

@app.route("/list")
def lists ():
    #Display the all Tasks
    todos_l = todos.find()
    a1="active"
    return render_template('index.html',a1=a1,todos=todos_l,t=title,h=heading)

@app.route("/")
@app.route("/uncompleted")
def tasks ():
    #Display the Uncompleted Tasks
    todos_l = todos.find({"done":"no"})
    a2="active"
    return render_template('index.html',a2=a2,todos=todos_l,t=title,h=heading)

@app.route("/completed")
def completed ():
    #Display the Completed Tasks
    todos_l = todos.find({"done":"yes"})
    a3="active"
    return render_template('index.html',a3=a3,todos=todos_l,t=title,h=heading)

@app.route("/done")
def done ():
    #Done-or-not ICON
    id=request.values.get("_id")
    task=todos.find({"_id":ObjectId(id)})
    if(task[0]["done"]=="yes"):
        todos.update({"_id":ObjectId(id)}, {"$set": {"done":"no"}})
    else:
        todos.update({"_id":ObjectId(id)}, {"$set": {"done":"yes"}})
    redir=redirect_url()    
    return redirect(redir)

@app.route("/action", methods=['POST'])
def action ():
    #Adding a Task
    name=request.values.get("name")
    desc=request.values.get("desc")
    date=request.values.get("date")
    pr=request.values.get("pr")
    todos.insert({ "name":name, "desc":desc, "date":date, "pr":pr, "done":"no"})
    return redirect("/list")

@app.route("/remove")
def remove ():
    #Deleting a Task with various references
    key=request.values.get("_id")
    todos.remove({"_id":ObjectId(key)})
    return redirect("/")

@app.route("/update")
def update ():
    id=request.values.get("_id")
    task=todos.find({"_id":ObjectId(id)})
    return render_template('update.html',tasks=task,h=heading,t=title)

@app.route("/action3", methods=['POST'])
def action3 ():
    #Updating a Task with various references
    name=request.values.get("name")
    desc=request.values.get("desc")
    date=request.values.get("date")
    pr=request.values.get("pr")
    id=request.values.get("_id")
    todos.update({"_id":ObjectId(id)}, {'$set':{ "name":name, "desc":desc, "date":date, "pr":pr }})
    return redirect("/")

@app.route("/search", methods=['GET'])
def search():
    #Searching a Task with various references
    key=request.values.get("key")
    refer=request.values.get("refer")
    if(key=="_id"):
        todos_l = todos.find({refer:ObjectId(key)})
    else:
        todos_l = todos.find({refer:key})
    return render_template('searchlist.html',todos=todos_l,t=title,h=heading)

if __name__ == "__main__":
    app.run()

We must add the below three HTML files in the templates folder (index.htmlsearchlist.html and update.html).

All these three files used the features of jinja2 framework to render the model values from app.py.

In addition, we must add emoji.cssemoji.jsstyle.css and twemoji.min.js files in the static\assets folder.

There are two images, no.png and yes.png in static\images folder.

We are ready to run our sample application.

Please start our mongodb instance with the below command:

"C:\Program Files\MongoDB\Server73499.0\bin\mongod.exe" --dbpath="C:\mongo-data"

Please note that mongodb now runs with data folder, C:\mongo-data.

Image 7

By default, it is listening to the port 27017.

Please open another command prompt window in the same Python application folder and run python with below command.

For example:

D:\Python\FlaskWithMongo>python app.py

Our local web server is running in port 5000 by default.

Image 8

Application is now running successfully.

Image 9

You can now add a sample task as task name “Test task for mongo with flask application”, description “Sample description”, date “05-08-2018" and priority “High

After clicking Create button, we can immediately view the task details in the grid.

Image 10

Please note that there is a new database named mymongodb and collection todo is created now. Using this application, you can edit and remove the existing documents easily.

You can check the document details in the MongoDB Compass Community too.

Image 11

Happy coding with Flask and MongoDB!!!

The source code is available at Github.

 

[출처] https://www.codeproject.com/Articles/1255416/Simple-Python-Flask-Program-with-MongoDB

 

 

본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
번호 제목 글쓴이 날짜 조회 수
57 [python 인공지능] Deploy ML models with FastAPI, Docker, and Heroku | Tutorial 졸리운_곰 2025.07.08 467
56 [python 인공지능] [VSCode] VSCode에서 ipynb 파일을 HTML(PDF 등..)로 졸리운_곰 2025.05.27 289
55 [Python 인공지능] [파이썬을 이용한 한글 NLP] 03. 간단한 키워드 추출기 졸리운_곰 2025.01.29 459
54 [Python 인공지능] [ 한글 키워드 시각화 ] 파이썬 python 텍스트 마이닝 한글 ( 워드 클라우드 WordCloud, squrify 트리맵으로 빅데이터 마스터) file 졸리운_곰 2025.01.29 398
53 [Python 인공지능] 기계 학습의 A to Z : IPython notebook과 scikit-learn을 활용한 기계 학습 file 졸리운_곰 2024.08.10 523
52 [python] 인공지능 python : 한글 문서 자동 요약 - lexrank 졸리운_곰 2023.07.06 404
51 [python] 인공지능 katiehouse / django-scikit-learn-tutorial file 졸리운_곰 2023.06.03 664
50 [python] [Anaconda]가상환경 설치,삭제 file 졸리운_곰 2022.12.03 405
49 [python][머신러닝] Scikit-learn Tutorial: Machine Learning in Python file 졸리운_곰 2022.11.29 497
48 [python] 파이썬(sklearn) 사이킷런(sklearn) 기초 졸리운_곰 2022.08.20 321
47 [python] scikit-learn이란 file 졸리운_곰 2022.08.20 455
46 [anaconde3][python] Create environment for tensorflow 1.4 in Anaconda 3 졸리운_곰 2022.07.02 563
45 [python][인공지능] [TensorFlow] Anaconda 가상환경 이용하여 TensorFlow GPU 설치 졸리운_곰 2022.01.20 438
44 [Python 인공지능] TextRank 를 이용한 키워드 추출과 핵심 문장 추출 (구현과 실험) file 졸리운_곰 2021.11.22 597
43 [python][인공지능] FLASK를 이용하여 PYTHON에서 PYTORCH를 REST API로 배포하기 졸리운_곰 2021.03.20 364
42 [python 파이썬] Creating REST API for TensorFlow models file 졸리운_곰 2021.02.01 488
41 [python 파이썬 인공지능] Keras 모델을 REST API로 배포해보기 file 졸리운_곰 2021.02.01 411
40 [파이썬 머신러닝] Scikit-learn 기초 졸리운_곰 2020.01.31 579
39 파이썬으로 간단한 뉴럴 네트워크 만들기 How to Create a Simple Neural Network in Python file 졸리운_곰 2020.01.29 22636
38 Keras를 활용한 주식 가격 예측 file 졸리운_곰 2019.02.25 983
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED