How to build a CRUD application using Flask (Python Framework)

How to build a CRUD application using Flask (Python Framework)




Here's a simple example of how to create a CRUD application using Flask and SQLAlchemy (a popular Python ORM library):

    1. First, you'll need to set up a new Flask project and install the required packages (Flask, Flask-SQLAlchemy, and a database driver).

Copy code 
# create a new directory for your project and navigate to it
mkdir myproject
cd myproject

# create a virtual environment and activate it
python3 -m venv venv
source venv/bin/activate

# install the required packages
pip install flask flask-sqlalchemy


    2. Next, create a new file app.py in your project directory and import the necessary 
       modules:
Copy code 
from flask import Flask, render_template, request, redirect
from flask_sqlalchemy import SQLAlchemy


    3. Initialize your Flask application and configure the database:
Copy code
app = Flask(name)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///mydatabase.db'
db = SQLAlchemy(app)


    4. Create a model for your database:
Copy code
class Person(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100), nullable=False)
    age = db.Column(db.Integer, nullable=False)

    def init(self, name, age):
        self.name = name
        self.age = age


    5. Create a route for the home page that displays a list of people from the database:
Copy code
@app.route('/')
def home():
    people = Person.query.all()
    return render_template('home.html', people=people)


    6. Create routes for the create, read, update, and delete operations:
Copy code
@app.route('/create', methods=['GET', 'POST'])
def create():
    if request.method == 'POST':
        name = request.form['name']
        age = request.form['age']

        new_person = Person(name, age)
        db.session.add(new_person)
        db.session.commit()

        return redirect('/')

    return render_template('create.html')

@app.route('/update/<int:id>', methods=['GET', 'POST'])
def update(id):
    person = Person.query.get(id)

    if request.method == 'POST':
        person.name = request.form['name']
        person.age = request.form['age']

        db.session.commit()

        return redirect('/')

    return render_template('update.html', person=person)

@app.route('/delete/<int:id>')
def delete(id):
    person = Person.query.get(id)
    db.session.delete(person)
    db.session.commit()

    return redirect('/')


    7. Create the template files for the home page, create page, and update page.

    8. Finally, create the database and run the application:
       if name == 'main':
        db.create_all()
        app.run(debug=True)


This will create the database and start the application in debug mode. You can then visit http://localhost:5000/ in your web browser to see the application in action. Please note that this is just a basic example and there are many additional features and best practices you should consider when building a real-world application, such as form validation, error handling, and user authentication. Also, in production environments, it is a best practice to use a more robust database like PostgreSQL or MySQL instead of SQLite.

Comments

Popular posts from this blog

Convert PDF Files to PPT Files in Python.

Compress PDF using python step by step

Shark Tank India: Focusing on the Innovative Technology Startups

Contact Form

Name

Email *

Message *