Yoav Reisler

1579234482

Flask CRUD Application Full Course With SQLAlchemy

In this article we are going to learn Flask CRUD Application with SQLAlchemy, we are going to build web application that you can create employee, read employee data from mysql database, update employee data and also delete employee. also we are using SQLAlchemy for this tutorial

What is Flask ?

Flask is a web framework. This means flask provides you with tools, libraries and technologies that allow you to build a web application. This web application can be some web pages, a blog, a wiki or go as big as a web-based calendar application or a commercial website.

Flask is part of the categories of the micro-framework. Micro-framework are normally framework with little to no dependencies to external libraries. This has pros and cons. Pros would be that the framework is light, there are little dependency to update and watch for security bugs, cons is that some time you will have to do more work by yourself or increase yourself the list of dependencies by adding plugins.

What is SQLAlchemy ?

SQLAlchemy is the Python SQL toolkit and Object Relational Mapper that gives application developers the full power and flexibility of SQL.

It provides a full suite of well known enterprise-level persistence patterns, designed for efficient and high-performing database access, adapted into a simple and Pythonic domain language.

What is Flask-SQLAlchemy ?

Flask-SQLAlchemy is an extension for Flask that adds support for SQLAlchemy to your application. It aims to simplify using SQLAlchemy with Flask by providing useful defaults and extra helpers that make it easier to accomplish common tasks.

See the SQLAlchemy documentation to learn how to work with the ORM in depth. The following documentation is a brief overview of the most common tasks, as well as the features specific to Flask-SQLAlchemy.

Installation

For this article first you need to install flask, and after that you need to install flask-sqlalchemy.

pip install Flask


pip install Flask-SQLAlchemy

OK after the installation first you need to create a database, iam using Wamp Server for this tutorial and my database name is crud. after that you need to open your Pycharm IDE and create two folders one for your static files and the second for your templates, in the video i have used bootstrap and jquery static files, but in here i have changed that to BootstrapCDN. in your templates you need to create some html files.

This is image title

So you can see i have static folder, but because iam using BootstrapCDN, iam not going to add bootstrap and jquery files in their. in the templates folder i have the HTML files that i need for this tutorial.

So this is index.html


{% extends 'base.html' %}
{% include 'header.html' %}



{% block title %} Home {% endblock %}



{% block body %}

<div class="container">
    <div class="row">
        <div class="col md-12">

            <div class="jumbotron p-3">

                <h2>Manage <b>Employees </b>  <button type="button"  class="btn btn-success float-right"
                data-toggle="modal" data-target="#mymodal">Add New Employees</button> </h2>


                {% with messages = get_flashed_messages() %}

                {% if messages %}

                {% for message in messages %}

                <div class="alert alert-success alert-dismissable" role="alert">

                    <button type="button" class="close" data-dismiss="alert" aria-label="close">

                        <span aria-hidden="true">x</span>

                    </button>


                {{message}}


                </div>


                {% endfor %}

                {% endif %}
                {% endwith %}


                <table class="table table-hover table-dark">

                    <tr>

                        <th>ID</th>
                        <th>Name</th>
                        <th>Email</th>
                        <th>Phone</th>
                        <th>Action</th>

                    </tr>


                   {% for row in employees %}
                    <tr>
                        <td>{{row.id}}</td>
                        <td>{{row.name}}</td>
                        <td>{{row.email}}</td>
                        <td>{{row.phone}}</td>

                        <td>
                            <a href="/update/{{row.id}}" class="btn btn-warning btn-xs" data-toggle="modal" data-target="#modaledit{{row.id}}">Edit</a>
                            <a href="/delete/{{row.id}}" class="btn btn-danger btn-xs" onclick="return confirm('Are You Sure To Delete ?')">Delete</a>


                        </td>

                    </tr>


                  <!-- Modal Edit Employee-->
<div id="modaledit{{row.id}}" class="modal fade" role="dialog">
   <div class="modal-dialog">


      <div class="modal-content">


         <div class="modal-header">


            <h4 class="modal-title">Update Information</h4>


         </div>


         <div class="modal-body">


            <form action="{{url_for('update')}}" method="POST">


               <div class="form-group">


                  <label>Name:</label>
                   <input type="hidden"  name="id" value="{{row.id}}">

                  <input type="text" class="form-control" name="name" value="{{row.name}}">


               </div>



               <div class="form-group">


                  <label>Email:</label>

                  <input type="text" class="form-control" name="email" value="{{row.email}}">


               </div>


               <div class="form-group">


                  <label>Phone:</label>

                  <input type="text" class="form-control" name="phone" value="{{row.phone}}">


               </div>


               <div class="form-group">


                  <button class="btn btn-primary" type="submit">Update</button>


               </div>


            </form>


         </div>


         <div class="modal-footer">


            <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>


         </div>


      </div>


   </div>

</div>


                    {% endfor %}


                </table>


            </div>



                  <!-- Modal Add Employee-->


<div id="mymodal" class="modal fade" role="dialog">
   <div class="modal-dialog">
      <div class="modal-content">
         <div class="modal-header">

            <h4 class="modal-title">Add Employee</h4>
         </div>
         <div class="modal-body">

            <form action="{{url_for('insert')}}" method="POST">


               <div class="form-group">

                  <label>Name:</label>
                  <input type="text" class="form-control" name="name" required="1">


               </div>


                <div class="form-group">


                  <label>Email:</label>
                  <input type="email" class="form-control" name="email" required="1">


               </div>


                <div class="form-group">


                  <label>Phone:</label>
                  <input type="number" class="form-control" name="phone" required="1">


               </div>



               <div class="form-group">


                  <button class="btn btn-primary" type="submit">Add Employee</button>


               </div>


            </form>


         </div>


         <div class="modal-footer">


            <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>


         </div>


      </div>


   </div>


</div>





        </div>

    </div>


</div>


{% endblock %}

This is our base.html


<!DOCTYPE html>
<html lang="en">
<head>


    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">

    <meta charset="UTF-8">
    <title>{% block title %} {% endblock %} </title>
</head>
<body>

{% block body %} {% endblock %}


<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>

</body>
</html>

you can see that i have added the BootstrapCDN in my base.html, you need to add the css files at the top, for jquery and javascript add those files in the below.

This is header.html file


{% extends 'base.html' %}



{% block title %} Flask CRUD {% endblock %}



{% block body %}

<div class="jumbotron p-3">
    <div class="well text-center">

        <h1>Python Flask CRUD Web Application Development </h1>

    </div>


</div>


{% endblock %}

and now this is our App.py



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




app = Flask(__name__)
app.secret_key = "Secret Key"

#SqlAlchemy Database Configuration With Mysql
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:''@localhost/crud'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

db = SQLAlchemy(app)


#Creating model table for our CRUD database
class Data(db.Model):
    id = db.Column(db.Integer, primary_key = True)
    name = db.Column(db.String(100))
    email = db.Column(db.String(100))
    phone = db.Column(db.String(100))


    def __init__(self, name, email, phone):

        self.name = name
        self.email = email
        self.phone = phone





#This is the index route where we are going to
#query on all our employee data
@app.route('/')
def Index():
    all_data = Data.query.all()

    return render_template("index.html", employees = all_data)



#this route is for inserting data to mysql database via html forms
@app.route('/insert', methods = ['POST'])
def insert():

    if request.method == 'POST':

        name = request.form['name']
        email = request.form['email']
        phone = request.form['phone']


        my_data = Data(name, email, phone)
        db.session.add(my_data)
        db.session.commit()

        flash("Employee Inserted Successfully")

        return redirect(url_for('Index'))


#this is our update route where we are going to update our employee
@app.route('/update', methods = ['GET', 'POST'])
def update():

    if request.method == 'POST':
        my_data = Data.query.get(request.form.get('id'))

        my_data.name = request.form['name']
        my_data.email = request.form['email']
        my_data.phone = request.form['phone']

        db.session.commit()
        flash("Employee Updated Successfully")

        return redirect(url_for('Index'))




#This route is for deleting our employee
@app.route('/delete/<id>/', methods = ['GET', 'POST'])
def delete(id):
    my_data = Data.query.get(id)
    db.session.delete(my_data)
    db.session.commit()
    flash("Employee Deleted Successfully")

    return redirect(url_for('Index'))






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

Also before runing your application, you need to create tables in database, because we are using SQLAlchemy, first you need to run python in Pycharm IDE and after that use these commands.

from App import db


db.create_all()

After runing the project this will be the result

This is image title

#Flask #SQLAlchemy #Python

What is GEEK

Buddha Community

Flask CRUD Application Full Course With SQLAlchemy

Tiebob Huang

1625472778

Thank you. It’s helpful for me to learn flask.

Yoav Reisler

1579234482

Flask CRUD Application Full Course With SQLAlchemy

In this article we are going to learn Flask CRUD Application with SQLAlchemy, we are going to build web application that you can create employee, read employee data from mysql database, update employee data and also delete employee. also we are using SQLAlchemy for this tutorial

What is Flask ?

Flask is a web framework. This means flask provides you with tools, libraries and technologies that allow you to build a web application. This web application can be some web pages, a blog, a wiki or go as big as a web-based calendar application or a commercial website.

Flask is part of the categories of the micro-framework. Micro-framework are normally framework with little to no dependencies to external libraries. This has pros and cons. Pros would be that the framework is light, there are little dependency to update and watch for security bugs, cons is that some time you will have to do more work by yourself or increase yourself the list of dependencies by adding plugins.

What is SQLAlchemy ?

SQLAlchemy is the Python SQL toolkit and Object Relational Mapper that gives application developers the full power and flexibility of SQL.

It provides a full suite of well known enterprise-level persistence patterns, designed for efficient and high-performing database access, adapted into a simple and Pythonic domain language.

What is Flask-SQLAlchemy ?

Flask-SQLAlchemy is an extension for Flask that adds support for SQLAlchemy to your application. It aims to simplify using SQLAlchemy with Flask by providing useful defaults and extra helpers that make it easier to accomplish common tasks.

See the SQLAlchemy documentation to learn how to work with the ORM in depth. The following documentation is a brief overview of the most common tasks, as well as the features specific to Flask-SQLAlchemy.

Installation

For this article first you need to install flask, and after that you need to install flask-sqlalchemy.

pip install Flask


pip install Flask-SQLAlchemy

OK after the installation first you need to create a database, iam using Wamp Server for this tutorial and my database name is crud. after that you need to open your Pycharm IDE and create two folders one for your static files and the second for your templates, in the video i have used bootstrap and jquery static files, but in here i have changed that to BootstrapCDN. in your templates you need to create some html files.

This is image title

So you can see i have static folder, but because iam using BootstrapCDN, iam not going to add bootstrap and jquery files in their. in the templates folder i have the HTML files that i need for this tutorial.

So this is index.html


{% extends 'base.html' %}
{% include 'header.html' %}



{% block title %} Home {% endblock %}



{% block body %}

<div class="container">
    <div class="row">
        <div class="col md-12">

            <div class="jumbotron p-3">

                <h2>Manage <b>Employees </b>  <button type="button"  class="btn btn-success float-right"
                data-toggle="modal" data-target="#mymodal">Add New Employees</button> </h2>


                {% with messages = get_flashed_messages() %}

                {% if messages %}

                {% for message in messages %}

                <div class="alert alert-success alert-dismissable" role="alert">

                    <button type="button" class="close" data-dismiss="alert" aria-label="close">

                        <span aria-hidden="true">x</span>

                    </button>


                {{message}}


                </div>


                {% endfor %}

                {% endif %}
                {% endwith %}


                <table class="table table-hover table-dark">

                    <tr>

                        <th>ID</th>
                        <th>Name</th>
                        <th>Email</th>
                        <th>Phone</th>
                        <th>Action</th>

                    </tr>


                   {% for row in employees %}
                    <tr>
                        <td>{{row.id}}</td>
                        <td>{{row.name}}</td>
                        <td>{{row.email}}</td>
                        <td>{{row.phone}}</td>

                        <td>
                            <a href="/update/{{row.id}}" class="btn btn-warning btn-xs" data-toggle="modal" data-target="#modaledit{{row.id}}">Edit</a>
                            <a href="/delete/{{row.id}}" class="btn btn-danger btn-xs" onclick="return confirm('Are You Sure To Delete ?')">Delete</a>


                        </td>

                    </tr>


                  <!-- Modal Edit Employee-->
<div id="modaledit{{row.id}}" class="modal fade" role="dialog">
   <div class="modal-dialog">


      <div class="modal-content">


         <div class="modal-header">


            <h4 class="modal-title">Update Information</h4>


         </div>


         <div class="modal-body">


            <form action="{{url_for('update')}}" method="POST">


               <div class="form-group">


                  <label>Name:</label>
                   <input type="hidden"  name="id" value="{{row.id}}">

                  <input type="text" class="form-control" name="name" value="{{row.name}}">


               </div>



               <div class="form-group">


                  <label>Email:</label>

                  <input type="text" class="form-control" name="email" value="{{row.email}}">


               </div>


               <div class="form-group">


                  <label>Phone:</label>

                  <input type="text" class="form-control" name="phone" value="{{row.phone}}">


               </div>


               <div class="form-group">


                  <button class="btn btn-primary" type="submit">Update</button>


               </div>


            </form>


         </div>


         <div class="modal-footer">


            <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>


         </div>


      </div>


   </div>

</div>


                    {% endfor %}


                </table>


            </div>



                  <!-- Modal Add Employee-->


<div id="mymodal" class="modal fade" role="dialog">
   <div class="modal-dialog">
      <div class="modal-content">
         <div class="modal-header">

            <h4 class="modal-title">Add Employee</h4>
         </div>
         <div class="modal-body">

            <form action="{{url_for('insert')}}" method="POST">


               <div class="form-group">

                  <label>Name:</label>
                  <input type="text" class="form-control" name="name" required="1">


               </div>


                <div class="form-group">


                  <label>Email:</label>
                  <input type="email" class="form-control" name="email" required="1">


               </div>


                <div class="form-group">


                  <label>Phone:</label>
                  <input type="number" class="form-control" name="phone" required="1">


               </div>



               <div class="form-group">


                  <button class="btn btn-primary" type="submit">Add Employee</button>


               </div>


            </form>


         </div>


         <div class="modal-footer">


            <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>


         </div>


      </div>


   </div>


</div>





        </div>

    </div>


</div>


{% endblock %}

This is our base.html


<!DOCTYPE html>
<html lang="en">
<head>


    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">

    <meta charset="UTF-8">
    <title>{% block title %} {% endblock %} </title>
</head>
<body>

{% block body %} {% endblock %}


<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>

</body>
</html>

you can see that i have added the BootstrapCDN in my base.html, you need to add the css files at the top, for jquery and javascript add those files in the below.

This is header.html file


{% extends 'base.html' %}



{% block title %} Flask CRUD {% endblock %}



{% block body %}

<div class="jumbotron p-3">
    <div class="well text-center">

        <h1>Python Flask CRUD Web Application Development </h1>

    </div>


</div>


{% endblock %}

and now this is our App.py



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




app = Flask(__name__)
app.secret_key = "Secret Key"

#SqlAlchemy Database Configuration With Mysql
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:''@localhost/crud'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

db = SQLAlchemy(app)


#Creating model table for our CRUD database
class Data(db.Model):
    id = db.Column(db.Integer, primary_key = True)
    name = db.Column(db.String(100))
    email = db.Column(db.String(100))
    phone = db.Column(db.String(100))


    def __init__(self, name, email, phone):

        self.name = name
        self.email = email
        self.phone = phone





#This is the index route where we are going to
#query on all our employee data
@app.route('/')
def Index():
    all_data = Data.query.all()

    return render_template("index.html", employees = all_data)



#this route is for inserting data to mysql database via html forms
@app.route('/insert', methods = ['POST'])
def insert():

    if request.method == 'POST':

        name = request.form['name']
        email = request.form['email']
        phone = request.form['phone']


        my_data = Data(name, email, phone)
        db.session.add(my_data)
        db.session.commit()

        flash("Employee Inserted Successfully")

        return redirect(url_for('Index'))


#this is our update route where we are going to update our employee
@app.route('/update', methods = ['GET', 'POST'])
def update():

    if request.method == 'POST':
        my_data = Data.query.get(request.form.get('id'))

        my_data.name = request.form['name']
        my_data.email = request.form['email']
        my_data.phone = request.form['phone']

        db.session.commit()
        flash("Employee Updated Successfully")

        return redirect(url_for('Index'))




#This route is for deleting our employee
@app.route('/delete/<id>/', methods = ['GET', 'POST'])
def delete(id):
    my_data = Data.query.get(id)
    db.session.delete(my_data)
    db.session.commit()
    flash("Employee Deleted Successfully")

    return redirect(url_for('Index'))






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

Also before runing your application, you need to create tables in database, because we are using SQLAlchemy, first you need to run python in Pycharm IDE and after that use these commands.

from App import db


db.create_all()

After runing the project this will be the result

This is image title

#Flask #SQLAlchemy #Python

navin prakash

1609588950

Advantages of hiring a full stack developer

Full-stack developers can work with various software applications to design a custom code that allows them to proficiently operate the website as well as its features. They have the potential to serve the entire project, from the ideas’ design to the product’s implementation accordingly.
If you are seeking Full Stack Developer Course in Chennai and FITA Academy is the NO.1 Training institute for Full Stack Developer Training in Chennai. We are providing the best advantages of hiring a full stack developer.

  1. Expert knowledge
    Expert & professional web design services are provided by full-stack designers. To attach innovative functionality to the websites or the application that excites the business, they have the experience & qualifications. The specialist player for frontend and backend creation is deemed to be a full-stack designer. This offers the benefit of moving between all parties, client and server-side and vice versa.
    A significant advantage with full-stack developers is that they do not compromise on the success of the work and are updated with the latest technologies. And it’s not everyone’s teacup, and so it just wants to give to the right hands.
  2. Versatility
    As previously mentioned, in backend & frontend creation, full-stack programmers are qualified. Front-end developers create algorithms that monitor the interactivity and the presentation of a webpage in the application (using Javascript, HTML & CSS). For linking the website & other CMS, back-end developers build prototypes. And here comes the full stack developer, who can effectively perform both functions. They concentrate on objectives and, without relying on others, have unique solutions.
  3. Rich Experience
    As the complete stack designers are involved in the different types of Internet programs, they have expertise with in-depth information on software & web development. They will determine the needs of the project and provide solutions out of the bag. And the perspectives offered by them will be useful for the project’s success & price sensitivity. This is something you don’t expect to get from other designers.
  4. Bigger picture of design structure
    One of the key advantages of full-stack developers is that they are useful and provide their contributions as needed in the larger entire design framework. Full Stack Developer Course in Pune is very helpful for your best career in the sector. Not only are their products restricted to web growth, but they go beyond supporting and improving existing structures. They are well versed in switching sides or ending in the production of MVP and are conscious of tackling the UI architecture of the software. So, full-stack developers are all in one package.
  5. Easy up-gradation
    Full-stack developers are recognized to be up to date with the latest developments and advancements in technology. They will also do the same at jobs, allowing customers to have access to the latest up-to-date technology. 94 percent of respondents said that they liked or disliked the websites on the basis of web development, according to a recent analysis. And that they will make your website more user-friendly as the full-stack developers are informed of all the software developments and innovations. Your customers will get a professional app that is interactive and sensitive because some cool & smart features are implemented in the project by full-stack programmers.

#full stack developer #full stack developer course #full stack developer training in chennai #full stack developer course in chennai #full stack

Steve  Kunde

Steve Kunde

1592723950

Download a Flask template ready to plug in your business logic

Let’s assume after lots of hard work you have your machine learning model running the way it should. This model could be one which responds to a user’s request to classify a tweet sentiment or identify objects in an image or recommend a product or some other algorithm unique to your needs. You would now like to quickly deploy this model. The article below is an explanation of the template that I have created to get you up and running quickly.

#flask-framework #flask-python-appengine #flask-sqlalchemy #marshmallow #flask #programming

Sigrid  Farrell

Sigrid Farrell

1624096385

Spring Boot CRUD Operations

In the video in this article, we take a closer look at the Spring Boot CRUD Operations Example alongside Exception Handling!

In the video below, we take a closer look at the Spring Boot CRUD Operations example with exception handling. Let’s get started!

#spring boot #spring boot tutorial for beginners #crud #crud #crud #spring boot crud operations

Trystan  Doyle

Trystan Doyle

1593062760

Python Flask-Mail Library to Send Emails in Browser Using Flask Full Project For Beginners

Python Flask-Mail Library to Send Emails in Browser Using Flask Full Project For Beginners

#python #flask #flaskmail

Welcome Folks My name is Gautam and Welcome to Coding Shiksha a Place for All Programmers. You can learn Web Development and Programming Tutorials.

#python flask-mail #flask full project #programming #flask