How to Create a Web Application in Python: Super easy

Hi! Tech Geeks…

Today we are going to create a web application in Python

Before beginning the discussion Let’s talk a little bit about Python.

What is Python?

Python is a high-level, interpreted programming language that is popular for its readability and simplicity. Guido van Rossum created it, and it was initially published in 1991. Python is intended to be simple to learn and use, making it a good choice for both new and experienced developers.

With the help of Python, we can,

  • Web Development: Python is used in web development to create websites, web apps, and APIs using frameworks such as Django and Flask.
  • Data Analysis and Visualization: Python is commonly used for data analysis, manipulation, and visualization, together with libraries such as NumPy, pandas, and Matplotlib.
  • Machine Learning and Artificial Intelligence: Python is the major language for machine learning and artificial intelligence (AI), featuring packages such as TensorFlow, PyTorch, scikit-learn, and Keras.
  • Scientific Computing: Python is used for simulations, data analysis, and research in a variety of scientific domains.
  • Automation and Scripting: Python is frequently used for automating monotonous operations and writing system management routines.
  • Game Development: Python is utilized in game creation with libraries such as Pygame.
  • Desktop Applications: Python modules such as PyQt and Tkinter may be used to create cross-platform desktop applications.
  • Internet of Things (IoT): Python is used in IoT projects to program devices and gather data.
  • Cybersecurity: Python is commonly used for activities such as penetration testing, network security, and forensic investigation.
  • Education: Python’s beginner-friendliness makes it popular in computer science classes and coding boot camps.

OK. Now I think you have some brief idea about Python if you are a beginner to Python. Now Let’s talk about how to create a web application in Python.

To create a web application in Python we need to follow these

  1. Choose a web framework – There are many web frameworks available for Python like Flask, Django, Pyramid. In this tutorial, I will be using Flask for the development.
  2. Install necessary dependencies – After selecting the framework you need to install necessary dependencies. for that, you need to have a package manager. Using the package manager you can install necessary dependencies as you wish. You can use popular package managers like Pip or Poetry. I will use pip.
  3. Create a new Project – After installation of the dependencies, you can create the project. This can done by creating a new directory and you can initialize a new project with the chosen web framework which is flask.
  4. Write the code – After creating the project, you can simply start coding!

1. Choose a Web Framework – How to create a Web Application in Python

As I mentioned there are Flask, Django and Pyramid web frameworks. I”ll explain briefly about each and every framework for your additional knowledge.

  • Flask: Flask is a lightweight and easy-to-use web framework. It is an excellent option for small and medium-sized web applications.
  • Django: Django is a more feature-rich and complicated web framework. It is an excellent solution for large, complicated web applications.
  • Pyramid: Pyramid is a web framework that is both adaptable and scalable. It is an excellent solution for web applications that must manage a high volume of traffic.

In our development, we will use the Flask web framework.

2. Install Necessary Dependencies – How to create a Web Application in Python

Once you have chosen a web framework, you will need to install the necessary dependencies. This can be done using a package manager such as pip or Poetry.

For example, to install the Flask web framework, you would use the following command:

pip install flask

3. Create a New Project – How to create a Web Application in Python

You can start a new project after installing the required prerequisites. This may be accomplished by establishing a new directory and launching a new project using your preferred web framework.

To start a new Flask project, for example, execute the following command:

flask init

This will create a new directory called hello-app with a number of files and directories in it

4. Write the code – How to create a Web Application in Python

After you’ve started a new project, you may begin writing code. This will entail developing routes, views, and templates.

Routes are the many URLs to which your application can react. Views are the functions that are invoked when a user accesses a certain URL. Templates are HTML files that are used to produce your application’s output.

For instance, the Flask code below establishes a primary route that produces a hello world message:

from flask import Flask, render_template

app = Flask(__name__)

@app.route("/")

def
 
hello_world():

    
return render_template("index.html")

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

The index.html template would contain the following HTML code:

<h1>Hello, world!</h1>

After you’ve developed your code, you should test it to ensure that it works as planned. You may accomplish this by executing your program locally and accessing it using a web browser.

You would use the following command to launch your Flask application locally:

flask run

This will start a development server on your local machine. You can then visit your application in a web browser by navigating to http://localhost:5000 your address bar.

You will see Hello World! text on browser

OK.. Cool! Now you have a simple idea. Let’s Develop the Products CRUD app with Python and Flask

Let’s learn a real example of our topic, which is How to create a Web Application in Python

How to Develop CRUD App with Python and Flask

To write a Products CRUD app with Python and Flask, you will need to:

  1. Install the necessary dependencies.
  2. Create a new Flask project.
  3. Create a database model for your products.
  4. Create routes for each CRUD operation.
  5. Write the code for each CRUD operation.
  6. Test your application.
  7. Deploy your application.

1. Install the necessary dependencies

You must install the Flask web framework and a database connection for your selected database. If you’re using PostgreSQL, for example, you’ll need to install the following dependencies:

pip install flask psycopg2

2. Create a new Flask project

To create a new Flask project, navigate to the directory where you want to create your project and run the following command:

flask init

This will create a new directory called hello-app with a number of files and directories in it.

3. Create a database model for your products

Next, you need to create a database model for your products. This model will define the structure of your product data.

The following Flask-SQLAlchemy model defines a simple product model:

from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()

class Product(db.Model):
    __tablename__ = 'products'

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100), nullable=False)
    price = db.Column(db.Float, nullable=False)

4. Create routes for each CRUD operation

You must then create routes for each CRUD action. Routes are the many URLs that your application may react to.

The Flask routes shown below define a route for each CRUD operation:

@app.route("/")
def index():
    products = Product.query.all()
    return render_template("index.html", products=products)

@app.route("/product/create")
def create_product():
    return render_template("create_product.html")

@app.route("/product/store", methods=["POST"])
def store_product():
    name = request.form["name"]
    price = request.form["price"]

    product = Product(name=name, price=price)
    db.session.add(product)
    db.session.commit()

    return redirect("/")

@app.route("/product/<int:id>/edit")
def edit_product(id):
    product = Product.query.get_or_404(id)
    return render_template("edit_product.html", product=product)

@app.route("/product/<int:id>/update", methods=["POST"])
def update_product(id):
    product = Product.query.get_or_404(id)

    product.name = request.form["name"]
    product.price = request.form["price"]

    db.session.commit()

    return redirect("/")

@app.route("/product/<int:id>/delete")
def delete_product(id):
    product = Product.query.get_or_404(id)

    db.session.delete(product)
    db.session.commit()

    return redirect("/")

5. Write the code for each CRUD Operation

Next, you need to write the code for each CRUD operation. This code will use the database model to perform the necessary operations.

For example, the following Flask code implements the store_product() function:

def store_product():
    name = request.form["name"]
    price = request.form["price"]

    product = Product(name=name, price=price)
    db.session.add(product)
    db.session.commit()

    return redirect("/")

This method generates a new Product object based on the request data and stores it in the database. The modifications are subsequently committed to the database, and the user is sent to the index page.

Full Code for the Product CRUD app in Python and Flask

from flask import Flask, render_template, redirect, request
from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()

class Product(db.Model):
    __tablename__ = 'products'

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100), nullable=False)
    price = db.Column(db.Float, nullable=False)

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///products.db'
db.init_app(app)

# Create
@app.route("/product/create")
def create_product():
    return render_template("create_product.html")

@app.route("/product/store", methods=["POST"])
def store_product():
    name = request.form["name"]
    price = request.form["price"]

    product = Product(name=name, price=price)
    db.session.add(product)
    db.session.commit()

    return redirect("/")

# Read
@app.route("/")
def index():
    products = Product.query.all()
    return render_template("index.html", products=products)

@app.route("/product/<int:id>")
def show_product(id):
    product = Product.query.get_or_404(id)
    return render_template("show_product.html", product=product)

# Update
@app.route("/product/<int:id>/edit")
def edit_product(id):
    product = Product.query.get_or_404(id)
    return render_template("edit_product.html", product=product)

@app.route("/product/<int:id>/update", methods=["POST"])
def update_product(id):
    product = Product.query.get_or_404(id)

    product.name = request.form["name"]
    product.price = request.form["price"]

    db.session.commit()

    return redirect("/")

# Delete
@app.route("/product/<int:id>/delete")
def delete_product(id):
    product = Product.query.get_or_404(id)

    db.session.delete(product)
    db.session.commit()

    return redirect("/")

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

If you are planning to copy this code and run here are the steps

  1. Install the necessary dependencies: pip install flask flask-sqlalchemy sqlalchemy
  2. Create a database file called products.db
  3. Run the application: flask run
  4. Open a web browser and navigate to http://localhost:5000

You should be able to create, read, update, and remove products at this point.

That’s it, Guys…

I hope this is helpful. Please let me know if you have any questions or feedback in the comment section.

Leave a Comment