SQL ALCHEMY: Pharmacy Database Web Application with Flask

SQL ALCHEMY: Pharmacy Database Web Application with Flask


Lets create a web based application with Flask using SQL Achemy as the ORM to help us insert, store and retrieve data from the sql lite database. 

We want to create a web page where we enter our medicine name to  add it to our pharmacy database  and we can also delete from it.

It is highly recommended to work in flask using a virtual envioronment as you can install as you can install dependancies whenever you want.

Type the following command in your terminal one by one:

import flask sqlachemy flask-sqlalchemy

mkdir my_pharmacy_database_app
cd my_pharmacy_database_app

python3 -m venv venv
source venv/bin/activate
import flask-sqlalchemy

Start the python shell:


Create a python3 file called med_manager.py and enter the following code:

import os from flask import Flask from flask import render_template from flask import request from flask_sqlalchemy import SQLAlchemy from flask import redirect project_dir = os.path.dirname(os.path.abspath(__file__)) database_file = "sqlite:///{}".format(os.path.join(project_dir, "medidatabase.db")) app = Flask(__name__) app.config["SQLALCHEMY_DATABASE_URI"] = database_file db = SQLAlchemy(app) class Medicine(db.Model): name = db.Column(db.String(80), unique=True, nullable=False, primary_key=True) def __repr__(self): return "<Name: {}>".format(self.name) @app.route("/", methods=["GET", "POST"]) def home(): if request.form: medicine = Medicine(name=request.form.get("name")) db.session.add(medicine) db.session.commit() medicines = Medicine.query.all() return render_template("home.html", medicines=medicines) @app.route("/delete", methods=["POST"]) def delete(): name=request.form.get("name") medicine = Medicine.query.filter_by(name=name).first() db.session.delete(medicine) db.session.commit() return redirect("/") if __name__ == "__main__": app.run(debug=True)


1.We import the neccessary files, specify our project directory and create the database using the sqllite engine. 
2.We create a new SQLAlchemy object db passing our flask app as parameter. The class medicine has the name column which also acts as the primary key. The __repr__ function returns the name of any specific object of Medicine class.
The first function displays the home page. If the form is not empty, get medicine name from the html form using the form.get() method. Add the medicine onject to the current session with the bd.session.add(object) method and commit() the changes to the database. Pass the home.html file to the render_template() function with the query result of medicines as a return to the home function.

3.The second function is the delete function. It requests the entered medicine name from the form. This name is queried using the filter_by() function. The result of the query gives the object coressponding to that name. This object is delete using the db.session.delete(object) functiona nd then commit() makes the change to the database.

4.The last part represents the runserver. 

Create a folder called templates in the my_pharmacy_database_app directory and create a home.html file inside it. Add the following code:

<head> <style> h1 {text-align:center;} p {text-align:center;} body {background-image: url("https://previews.123rf.com/images/volody10/volody101901/volody10190100268/116355849-scattered-white-pills-on-blue-table-mock-up-for-special-offers-as-advertising-web-background-or-othe.jpg"); </style> <h1> Medicine App </h1> </head> </head> <body> <hr> <b> <h1> Add Medicine </h1> </b> <hr> <form method="POST" action="/"> <p> <input type="text" name="name"> <input type="submit" value="Add"> </p> </form> <p> <form method="POST" action="./delete"> <p> <input type="text" name="name"> <input type="submit" value="Delete"> </p> </form> </p> <hr> <h1> Medicines </h1> {% for medicine in medicines %} <b><p>{{medicine.name}}</p> {% endfor %} <hr> </body> </html>

1. In this html file, we have created a header which is Medicine App.
2. We have created two forms first with two submit buttons beside them. One for adding medicine name and another      for deleting the entered medicine name from the database.
3. We have used horizontal lines to separate out the various sections of our page.
4. We used a jinja loop to print the medicines in our database.
5. We used CSS to align our text centrally and add a suitable background image.

In the python shell, type the following commands:

from my_pharmacy_database_app import db

Now type :

python3 med_manager.py

Now open any webbrowser and type in the address type in localhost:5000. This will display the created webpage on your browser:

In this way, you can create the backend of a web based application using SQL Alchemy ORM with Flask to implement easy input, retrival and querying data from a database.

Here you can enter the name of a medicine and that will be added to our database. I have already added some. Lets add another medicine called Cremica. Type Cremica in the add form and press add.

Now the web page looks like this. It has already added Cremica to the pharmacy medicine database.

Now delete Cremica from the database: Type Cremica in the delete form and press delete.

After deletion, the page gets updated automatically.You can see the updated list doesn't contain Cremica.


Thanks for viewing my article! Please like and subscribe !