article

Showing posts with label PostgreSQL. Show all posts
Showing posts with label PostgreSQL. Show all posts

Thursday, June 24, 2021

Load content Dynamically in Bootstrap Modal with Jquery AJAX and Python Flask PostgreSQL

Load content Dynamically in Bootstrap Modal with Jquery AJAX and Python Flask PostgreSQL

install psycopg2 https://pypi.org/project/psycopg2/
Psycopg is the most popular PostgreSQL database adapter for the Python programming language.
(venv) PS C:\flaskmyproject> pip install psycopg2

CREATE TABLE employee (
id serial PRIMARY KEY,
name VARCHAR ( 100 ) NOT NULL,
position VARCHAR ( 100 ) NOT NULL,
office VARCHAR ( 100 ) NOT NULL,
age INT NOT NULL,
salary INT NOT NULL,
photo VARCHAR ( 150 ) NOT NULL,
);


INSERT INTO
    employee(name, position, office, age, salary, photo)
VALUES
('Tiger Wood', 'Accountant', 'Tokyo', 36, 5689, '01.jpg'),
('Mark Oto Ednalan', 'Chief Executive Officer (CEO)', 'London', 56, 5648, '02.jpg'),
('Jacob thompson', 'Junior Technical Author', 'San Francisco', 23, 5689, '03.jpg'),
('cylde Ednalan', 'Software Engineer', 'Olongapo', 23, 54654, '04.jpg'),
('Rhona Davidson', 'Software Engineer', 'San Francisco', 26, 5465, '05.jpg'),
('Quinn Flynn', 'Integration Specialist', 'New York', 53, 56465, '06.jpg'),
('Tiger Nixon', 'Software Engineer', 'London', 45, 456, '07.jpg'),
('Airi Satou', 'Pre-Sales Support', 'New York', 25, 4568, '08.jpg'),
('Angelica Ramos', 'Sales Assistant', 'New York', 45, 456, '09.jpg'),
('Ashton updated', 'Senior Javascript Developer', 'Olongapo', 45, 54565, '01.jpg'),
('Bradley Greer', 'Regional Director', 'San Francisco', 27, 5485, '02.jpg'),
('Brenden Wagner', 'Javascript Developer', 'San Francisco', 38, 65468, '03.jpg'),
('Brielle Williamson', 'Personnel Lead', 'Olongapo', 56, 354685, '04.jpg'),
('Bruno Nash', 'Customer Support', 'New York', 36, 65465, '05.jpg'),
('cairocoders', 'Sales Assistant', 'Sydney', 45, 56465, '06.jpg'),
('Zorita Serrano', 'Support Engineer', 'San Francisco', 38, 6548, '07.jpg'),
('Zenaida Frank', 'Chief Operating Officer (COO)', 'San Francisco', 39, 545, '08.jpg'),
('Sakura Yamamoto', 'Support Engineer', 'Tokyo', 48, 5468, '05.jpg'),
('Serge Baldwin', 'Data Coordinator', 'Singapore', 85, 5646, '05.jpg'),
('Shad Decker', 'Regional Director', 'Tokyo', 45, 4545, '05.jpg');
app.py
 
#app.py
from flask import Flask, render_template, request, jsonify
import psycopg2 #pip install psycopg2 
import psycopg2.extras

app = Flask(__name__)

app.secret_key = "caircocoders-ednalan"

DB_HOST = "localhost"
DB_NAME = "sampledb"
DB_USER = "postgres"
DB_PASS = "admin"
    
conn = psycopg2.connect(dbname=DB_NAME, user=DB_USER, password=DB_PASS, host=DB_HOST)  

@app.route('/')
def index():
    cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
    cur.execute("SELECT * FROM employee ORDER BY id ASC")
    employee = cur.fetchall()  
    return render_template('index.html', employee = employee)
 
@app.route("/ajaxfile",methods=["POST","GET"])
def ajaxfile():
    cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
    if request.method == 'POST':
        userid = request.form['userid']
        print(userid)
        cur.execute("SELECT * FROM employee WHERE id = %s", [userid])
        employeelist = cur.fetchall() 
    return jsonify({'htmlresponse': render_template('response.html',employeelist=employeelist)})
 
if __name__ == "__main__":
    app.run(debug=True)
templates/index.html
//templates/index.html
<!DOCTYPE html>
<html>
<head>
<title>Load content Dynamically in Bootstrap Modal with Jquery AJAX and Python Flask PostgreSQL</title>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body >
<div class="container">
   <br />
   <h3 align="center">Load content Dynamically in Bootstrap Modal with Jquery AJAX and Python Flask PostgreSQL</h3>
   <div class="row">
    <div class="col-md-12">
        <div class="panel-body">
            <div class="table-responsive">
                <table class="table table-bordered">
                    <thead>
                        <tr>
                            <th width="60">Photo</th>
                            <th>Name</th>
                            <th>Position</th>
                            <th>Office</th>
                            <th>Age</th>
                            <th>Salary</th>
                            <th>View</th>
                        </tr>
                        </thead> 
                        {% for row in employee %}
                            <tr>
                                <td><img src="/static/images/{{row.photo}}" height="50" width="50"/></td>
                                <td>{{row.name}}</td>
                                <td>{{row.position}}</td>
                                <td>{{row.office}}</td>
                                <td>{{row.age}}</td>
                                <td>{{row.salary}}</td>
                                <td><button data-id='{{row.id}}' class="userinfo btn btn-success">Info</button></td>
                            </tr>
                        {% endfor %}
                </table>
            </div>
        </div>    
    </div>    
    </div>
</div>    
            <script type='text/javascript'>
            $(document).ready(function(){
                $('.userinfo').click(function(){
                    var userid = $(this).data('id');
                    $.ajax({
                        url: '/ajaxfile',
                        type: 'post',
                        data: {userid: userid},
                        success: function(data){ 
                            $('.modal-body').html(data); 
                            $('.modal-body').append(data.htmlresponse);
                            $('#empModal').modal('show'); 
                        }
                    });
                });
            });
            </script>
        </div>
        <div class="modal fade" id="empModal" role="dialog">
                <div class="modal-dialog">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h4 class="modal-title">User Info</h4>
                          <button type="button" class="close" data-dismiss="modal">×</button>
                        </div>
                        <div class="modal-body">
                        </div>
                        <div class="modal-footer">
                          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                        </div>
                    </div>
                </div>
        </div>
    </body>
</html>
templates/response.html
//templates/response.html
{% for row in employeelist %} 
<table border='0' width='100%'>
    <tr>
        <td width="300"><img src="/static/images/{{row.photo}}">
        <td style="padding:20px;">
        <p>Name : {{row.name}}</p>
        <p>Position : {{row.position}}</p>
        <p>Office : {{row.office}}</p>
        <p>Age : {{row.age}}</p>
        <p>Salary : {{row.salary}}</p>
        </td>
    </tr>
</table>
{% endfor %}

Wednesday, June 23, 2021

REST API Query Parameter GET Request using Python Flask and PostgreSQL Database

REST API Query Parameter GET Request using Python Flask and PostgreSQL Database

Create table

CREATE TABLE useraccount (
id serial PRIMARY KEY,
username VARCHAR ( 100 ) NOT NULL,
password VARCHAR ( 100 ) NOT NULL
);

Insert data

INSERT INTO useraccount (username, password) VALUES ('tutorial101', 'pbkdf2:sha256:150000$KxxiGerN$4c37a656baa0034035a6be2cd698b5da8b036ae63eef3ab0b08b9c18b9765648');

Testing Rest API

REST API Testing is open-source web automation testing technique that is used for testing RESTful APIs for web applications. The purpose of rest api testing is to record the response of rest api by sending various HTTP/S requests to check if rest api is working fine or not. Rest api testing is done by GET, POST, PUT and DELETE methods.

Rest stands for Representational State Transfer. It is an architectural style and an approach for communication used in the development of Web Services. REST has become a logical choice for building APIs. It enables users to connect and interact with cloud services efficiently.

An API or Application Programming Interface is a set of programming instructions for accessing a web-based software application.

API is a set of commands used by an individual program to communicate with one another directly and use each other's functions to get information.

Install the Advanced Rest Client
1. Go to Google Chrome's Web Store
2. Search for "Advanced Rest Client" https://chrome.google.com/webstore/detail/advanced-rest-client/hgmloofddffdnphfgcellkdfbfbjeloo and Install the extension

install psycopg2 https://pypi.org/project/psycopg2/
Psycopg is the most popular PostgreSQL database adapter for the Python programming language.
(venv) PS C:\flaskmyproject> pip install psycopg2

app.py
 
#app.py
from flask import Flask, jsonify, request
from werkzeug.security import generate_password_hash, check_password_hash

import psycopg2 #pip install psycopg2 
import psycopg2.extras

app = Flask(__name__)

DB_HOST = "localhost"
DB_NAME = "sampledb"
DB_USER = "postgres"
DB_PASS = "admin"
    
conn = psycopg2.connect(dbname=DB_NAME, user=DB_USER, password=DB_PASS, host=DB_HOST)  

@app.route('/')
def home():
    passhash = generate_password_hash('cairocoders')
    print(passhash)
    return passhash

@app.route('/user') 
def get_user():
    try:
        id = request.args.get('id')
        if id:
            cursor = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
            cursor.execute("SELECT * FROM useraccount WHERE id=%s", id)
            row = cursor.fetchone()
            resp = jsonify(row)
            resp.status_code = 200
            return resp
        else:
            resp = jsonify('User "id" not found in query string')
            resp.status_code = 500
            return resp
    except Exception as e:
        print(e)
    finally:
        cursor.close() 
        conn.close()

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

REST API Login Logout Using Python Flask and PostgreSQL Database

REST API Login Logout Using Python Flask and PostgreSQL Database

Create table

CREATE TABLE useraccount (
id serial PRIMARY KEY,
username VARCHAR ( 100 ) NOT NULL,
password VARCHAR ( 100 ) NOT NULL
);

Insert data

INSERT INTO useraccount (username, password) VALUES ('tutorial101', 'pbkdf2:sha256:150000$KxxiGerN$4c37a656baa0034035a6be2cd698b5da8b036ae63eef3ab0b08b9c18b9765648');

{"username":"tutorial101","password":"cairocoders"}

Username : tutorial101
password : cairocoders

Testing Rest API

REST API Testing is open-source web automation testing technique that is used for testing RESTful APIs for web applications. The purpose of rest api testing is to record the response of rest api by sending various HTTP/S requests to check if rest api is working fine or not. Rest api testing is done by GET, POST, PUT and DELETE methods.

Rest stands for Representational State Transfer. It is an architectural style and an approach for communication used in the development of Web Services. REST has become a logical choice for building APIs. It enables users to connect and interact with cloud services efficiently.

An API or Application Programming Interface is a set of programming instructions for accessing a web-based software application.

API is a set of commands used by an individual program to communicate with one another directly and use each other's functions to get information.

Install the Advanced Rest Client
1. Go to Google Chrome's Web Store
2. Search for "Advanced Rest Client" https://chrome.google.com/webstore/detail/advanced-rest-client/hgmloofddffdnphfgcellkdfbfbjeloo and Install the extension

 
#app.py
from flask import Flask, jsonify, request, session
from werkzeug.security import generate_password_hash, check_password_hash
from flask_cors import CORS #pip install -U flask-cors
from datetime import timedelta

import psycopg2 #pip install psycopg2 
import psycopg2.extras

app = Flask(__name__)
 
app.config['SECRET_KEY'] = 'cairocoders-ednalan'
 
app.config['PERMANENT_SESSION_LIFETIME'] =  timedelta(minutes=10)
CORS(app) 

DB_HOST = "localhost"
DB_NAME = "sampledb"
DB_USER = "postgres"
DB_PASS = "admin"
    
conn = psycopg2.connect(dbname=DB_NAME, user=DB_USER, password=DB_PASS, host=DB_HOST)  

@app.route('/')
def home():
    passhash = generate_password_hash('cairocoders')
    print(passhash)
    if 'username' in session:
        username = session['username']
        return jsonify({'message' : 'You are already logged in', 'username' : username})
    else:
        resp = jsonify({'message' : 'Unauthorized'})
        resp.status_code = 401
        return resp
 
@app.route('/login', methods=['POST'])
def login():
    _json = request.json
    _username = _json['username']
    _password = _json['password']
    print(_password)
    # validate the received values
    if _username and _password:
        #check user exists          
        cursor = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
         
        sql = "SELECT * FROM useraccount WHERE username=%s"
        sql_where = (_username,)
         
        cursor.execute(sql, sql_where)
        row = cursor.fetchone()
        username = row['username']
        password = row['password']
        if row:
            if check_password_hash(password, _password):
                session['username'] = username
                cursor.close()
                return jsonify({'message' : 'You are logged in successfully'})
            else:
                resp = jsonify({'message' : 'Bad Request - invalid password'})
                resp.status_code = 400
                return resp
    else:
        resp = jsonify({'message' : 'Bad Request - invalid credendtials'})
        resp.status_code = 400
        return resp
         
@app.route('/logout')
def logout():
    if 'username' in session:
        session.pop('username', None)
    return jsonify({'message' : 'You successfully logged out'})
         
if __name__ == "__main__":
    app.run()

Monday, June 21, 2021

Generate PDF Report using Python Flask PostgreSQL

Generate PDF Report using Python Flask PostgreSQL

install psycopg2 https://pypi.org/project/psycopg2/
Psycopg is the most popular PostgreSQL database adapter for the Python programming language.
(venv) PS C:\flaskmyproject> pip install psycopg2

CREATE TABLE employee (
id serial PRIMARY KEY,
name VARCHAR ( 100 ) NOT NULL,
position VARCHAR ( 100 ) NOT NULL,
office VARCHAR ( 100 ) NOT NULL,
age INT NOT NULL,
salary INT NOT NULL,
photo VARCHAR ( 150 ) NOT NULL,
);


INSERT INTO
    employee(name, position, office, age, salary, photo)
VALUES
('Tiger Wood', 'Accountant', 'Tokyo', 36, 5689, '01.jpg'),
('Mark Oto Ednalan', 'Chief Executive Officer (CEO)', 'London', 56, 5648, '02.jpg'),
('Jacob thompson', 'Junior Technical Author', 'San Francisco', 23, 5689, '03.jpg'),
('cylde Ednalan', 'Software Engineer', 'Olongapo', 23, 54654, '04.jpg'),
('Rhona Davidson', 'Software Engineer', 'San Francisco', 26, 5465, '05.jpg'),
('Quinn Flynn', 'Integration Specialist', 'New York', 53, 56465, '06.jpg'),
('Tiger Nixon', 'Software Engineer', 'London', 45, 456, '07.jpg'),
('Airi Satou', 'Pre-Sales Support', 'New York', 25, 4568, '08.jpg'),
('Angelica Ramos', 'Sales Assistant', 'New York', 45, 456, '09.jpg'),
('Ashton updated', 'Senior Javascript Developer', 'Olongapo', 45, 54565, '01.jpg'),
('Bradley Greer', 'Regional Director', 'San Francisco', 27, 5485, '02.jpg'),
('Brenden Wagner', 'Javascript Developer', 'San Francisco', 38, 65468, '03.jpg'),
('Brielle Williamson', 'Personnel Lead', 'Olongapo', 56, 354685, '04.jpg'),
('Bruno Nash', 'Customer Support', 'New York', 36, 65465, '05.jpg'),
('cairocoders', 'Sales Assistant', 'Sydney', 45, 56465, '06.jpg'),
('Zorita Serrano', 'Support Engineer', 'San Francisco', 38, 6548, '07.jpg'),
('Zenaida Frank', 'Chief Operating Officer (COO)', 'San Francisco', 39, 545, '08.jpg'),
('Sakura Yamamoto', 'Support Engineer', 'Tokyo', 48, 5468, '05.jpg'),
('Serge Baldwin', 'Data Coordinator', 'Singapore', 85, 5646, '05.jpg'),
('Shad Decker', 'Regional Director', 'Tokyo', 45, 4545, '05.jpg');
app.py
 
#app.py
from flask import Flask, render_template, url_for, Response
from fpdf import FPDF #pip install fpdf 

import psycopg2 #pip install psycopg2 
import psycopg2.extras

app = Flask(__name__)   

DB_HOST = "localhost"
DB_NAME = "sampledb"
DB_USER = "postgres"
DB_PASS = "admin"
    
conn = psycopg2.connect(dbname=DB_NAME, user=DB_USER, password=DB_PASS, host=DB_HOST)

@app.route('/')
def home():
    return render_template('index.html')
 
@app.route('/download/report/pdf')
def download_report():
    try:
        cursor = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
         
        cursor.execute("SELECT * FROM employee")
        result = cursor.fetchall()
 
        pdf = FPDF()
        pdf.add_page()
         
        page_width = pdf.w - 2 * pdf.l_margin
         
        pdf.set_font('Times','B',14.0) 
        pdf.cell(page_width, 0.0, 'Employee Data', align='C')
        pdf.ln(10)
 
        pdf.set_font('Courier', '', 12)
         
        col_width = page_width/4
         
        pdf.ln(1)
         
        th = pdf.font_size
         
        for row in result:
            pdf.cell(col_width, th, str(row['id']), border=1)
            pdf.cell(col_width, th, row['name'], border=1)
            pdf.cell(col_width, th, row['position'], border=1)
            pdf.cell(col_width, th, row['office'], border=1)
            pdf.ln(th)
         
        pdf.ln(10)
         
        pdf.set_font('Times','',10.0) 
        pdf.cell(page_width, 0.0, '- end of report -', align='C')
         
        return Response(pdf.output(dest='S').encode('latin-1'), mimetype='application/pdf', headers={'Content-Disposition':'attachment;filename=employee_report.pdf'})
    except Exception as e:
        print(e)
    finally:
        cursor.close() 
        conn.close()
         
 
if __name__ == "__main__":
    app.run()
templates/index.html
//templates/index.html
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Generate PDF Report using Python Flask PostgreSQL</title>
</head>
<body>
    <div style="margin: 10px 0 0 10px;width: 600px">
    <h2>Generate PDF Report using Python Flask PostgreSQL</h2>
<p>
    <a href="{{ url_for('.download_report') }}">Generate Pdf Report</a>
</p>
    </div>
</body>
</html>

Upload and display image using Python Flask and insert to PostgreSQL

Upload and display image using Python Flask and insert to PostgreSQL

install psycopg2 https://pypi.org/project/psycopg2/
Psycopg is the most popular PostgreSQL database adapter for the Python programming language.
(venv) PS C:\flaskmyproject> pip install psycopg2

CREATE TABLE upload (
id serial PRIMARY KEY,
title VARCHAR ( 100 ) NOT NULL,
);
app.py
 
#app.py
from flask import Flask, flash, request, redirect, url_for, render_template
import urllib.request
import os
from werkzeug.utils import secure_filename
 
import psycopg2 #pip install psycopg2 
import psycopg2.extras
    
app = Flask(__name__)
    
app.secret_key = "cairocoders-ednalan"
    
DB_HOST = "localhost"
DB_NAME = "sampledb"
DB_USER = "postgres"
DB_PASS = "admin"
    
conn = psycopg2.connect(dbname=DB_NAME, user=DB_USER, password=DB_PASS, host=DB_HOST)
 
UPLOAD_FOLDER = 'static/uploads/'
 
app.secret_key = "secret key"
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024
 
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif'])
 
def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
     
 
@app.route('/')
def home():
    return render_template('index.html')
 
@app.route('/', methods=['POST'])
def upload_image():
    cursor = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)

    if 'file' not in request.files:
        flash('No file part')
        return redirect(request.url)
    file = request.files['file']
    if file.filename == '':
        flash('No image selected for uploading')
        return redirect(request.url)
    if file and allowed_file(file.filename):
        filename = secure_filename(file.filename)
        file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
        #print('upload_image filename: ' + filename)

        cursor.execute("INSERT INTO upload (title) VALUES (%s)", (filename,))
        conn.commit()

        flash('Image successfully uploaded and displayed below')
        return render_template('index.html', filename=filename)
    else:
        flash('Allowed image types are - png, jpg, jpeg, gif')
        return redirect(request.url)
 
@app.route('/display/<filename>')
def display_image(filename):
    #print('display_image filename: ' + filename)
    return redirect(url_for('static', filename='uploads/' + filename), code=301)
 
if __name__ == "__main__":
    app.run()
templates/index.html
//templates/index.html
<html>
<head>
<title>Upload and display image using Python Flask and insert to PostgreSQL</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />        
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
</head>
<body>
<p><h1 align="center">Upload and display image using Python Flask and insert to PostgreSQL</h1></p>
<div class="container">
<div class="row">
    <h2>Select a file to upload</h2>
    <p>
        {% with messages = get_flashed_messages() %}
          {% if messages %}
            <ul>
            {% for message in messages %}
              <li>{{ message }}</li>
            {% endfor %}
            </ul>
          {% endif %}
        {% endwith %}
    </p>
    {% if filename %}
        <div>
            <img src="{{ url_for('display_image', filename=filename) }}">
        </div>
    {% endif %}
    <form method="post" action="/" enctype="multipart/form-data">
        <dl>
            <p>
                <input type="file" name="file" class="form-control" autocomplete="off" required>
            </p>
        </dl>
        <p>
            <input type="submit" value="Submit" class="btn btn-info">
        </p>
    </form>
</div>
</div>
</body>
</html>

Sunday, June 6, 2021

Display Loading Image when AJAX call is in Progress using Python Flask PostgreSQL

Display Loading Image when AJAX call is in Progress using Python Flask PostgreSQL

install psycopg2 https://pypi.org/project/psycopg2/
Psycopg is the most popular PostgreSQL database adapter for the Python programming language.
(venv) PS C:\flaskmyproject> pip install psycopg2

CREATE TABLE posts (
id serial PRIMARY KEY,
title VARCHAR ( 100 ) NOT NULL,
content TEXT NOT NULL,
link VARCHAR ( 100 ) NOT NULL,
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);


INSERT INTO
    posts(title, content, link, created_at)
VALUES
('What is AngularJS', 'AngularJS is a JavaScript MVC framework  developed by Google that lets you build well structured, easily testable,  declarative and maintainable front-end applications which provides solutions to  standard infrastructure concerns.', 'link-5', '2021-03-20 16:00:00'),
('What is MongoDB', 'It is a quick tutorial on MongoDB and how you can install it on your Windows OS. We will also learn some basic commands in MongoDB for example, creating and dropping a Database, Creation of a collection and some more operations related to the collection.', 'link-6', '2021-03-21 16:00:00'),
('Python Flask Load content Dynamically in Bootstrap Modal with Jquery AJAX and Mysqldb', 'Python Flask Load content Dynamically in Bootstrap Modal with Jquery AJAX and Mysqldb', 'link-6', '2021-03-20 16:00:00'),
('AutoComplete Textbox with Image using jQuery Ajax PHP Mysql and JqueryUI', 'AutoComplete Textbox with Image using jQuery Ajax PHP Mysql and JqueryUI', 'link-7', '2021-03-14 16:00:00'),
('PHP Mysql Registration Form Validation using jqBootstrapValidation with Jquery Ajax', 'PHP Mysql Registration Form Validation using jqBootstrapValidation with Jquery Ajax', 'link-8', '2021-03-20 16:00:00'),
('Python Flask Registration Form Validation using jqBootstrapValidation with Jquery Ajax and Mysql', 'Python Flask Registration Form Validation using jqBootstrapValidation with Jquery Ajax and Mysql', 'link-9', '2021-03-19 16:00:00'),
('Displaying Popups data on mouse hover using Jquery Ajax and PHP Mysql database', 'Displaying Popups data on mouse hover using Jquery Ajax and PHP Mysql database', 'link-10', '2021-03-15 16:00:00'),
('Displaying Popups data on mouse hover using Jquery Ajax and Python Flask Mysql database', 'Displaying Popups data on mouse hover using Jquery Ajax and Python Flask Mysql database', 'link-11', '2021-03-14 16:00:00');

app.py
 
#app.py
from flask import Flask, request, render_template, jsonify, json
import psycopg2 #pip install psycopg2 
import psycopg2.extras
   
app = Flask(__name__)
   
app.secret_key = "cairocoders-ednalan"
   
DB_HOST = "localhost"
DB_NAME = "sampledb"
DB_USER = "postgres"
DB_PASS = "admin"
   
conn = psycopg2.connect(dbname=DB_NAME, user=DB_USER, password=DB_PASS, host=DB_HOST)

@app.route('/')
def home():
    return render_template('index.html')
 
@app.route("/fetchdeta",methods=["POST","GET"])
def fetchdeta():
    cursor = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
    if request.method == 'POST':
        search = request.form['search']
        print(search)
        query = "SELECT * from posts WHERE title LIKE '%{}%'".format(search,)
        cursor.execute(query)
        postslist = cursor.fetchall() 
        cursor.close()
    return jsonify({'htmlresponse': render_template('response.html',postslist=postslist)})
             
if __name__ == "__main__":
    app.run()
templates.index.html
//templates.index.html
<html>
 <head>
  <title>Display Loading Image when AJAX call is in Progress using Python Flask PostgreSQL</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />        
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
 </head>
 <body>
  <div class="container">
  <div class="row">
   <h3 align="center">Display Loading Image when AJAX call is in Progress using Python Flask PostgreSQL</h3>
    Search : 
    <input type='text' id='search' class="form-control" style="width:40%;"><br/>
    <input type='button' id='but_search' value='Search' class="btn btn-default"><br/>
    <!-- Image loader -->
    <div id='loader' style='display: none;'>
      <img src='/static/img/loader.gif'> <b>Loading..</b>
    </div>
    <br/>
    <!-- Image loader -->
    <div class='response'></div>
   </div>
  </div>
<script type='text/javascript'>
 
$(document).ready(function(){
  
 $("#but_search").click(function(){
  var search = $('#search').val();
 
  $.ajax({
   url: '/fetchdeta',
   type: 'post',
   data: {search:search},
   beforeSend: function(){
    // Show image container
    $("#loader").show();
   },
   success: function(response){
    $('.response').empty();
    $('.response').append(response.htmlresponse);
   },
   complete:function(data){
    // Hide image container
    $("#loader").hide();
   }
  });
  
 });
});
</script>
<style>
.post{
    width: 97%;
    min-height: 200px;
    padding: 5px;
    border: 1px solid gray;
    margin-bottom: 15px;
}
.post h1{
    letter-spacing: 1px;
    font-weight: normal;
    font-family: sans-serif;
}
.post p{
    letter-spacing: 1px;
    text-overflow: ellipsis;
    line-height: 25px;
}
</style>
 </body>
</html>
templates/response.html
//templates/response.html
{% for row in postslist %}
<div class="post" id="post_{{row.id}}">
<h1>{{row.title}}</h1>
<p>{{row.content}}</p>
<a href="{{row.link}}" class="more" target="_blank">More</a>
</div>
{% endfor %}

Friday, June 4, 2021

Filter Records using jQuery UI slider with Jquery Ajax and Python Flask PostgreSQL

Filter Records using jQuery UI slider with Jquery Ajax and Python Flask PostgreSQL

install psycopg2 https://pypi.org/project/psycopg2/
Psycopg is the most popular PostgreSQL database adapter for the Python programming language.
(venv) PS C:\flaskmyproject> pip install psycopg2

CREATE TABLE employee (
id serial PRIMARY KEY,
name VARCHAR ( 100 ) NOT NULL,
position VARCHAR ( 100 ) NOT NULL,
office VARCHAR ( 100 ) NOT NULL,
age INT NOT NULL,
salary INT NOT NULL,
photo VARCHAR ( 150 ) NOT NULL,
);


INSERT INTO
    employee(name, position, office, age, salary, photo)
VALUES
('Tiger Wood', 'Accountant', 'Tokyo', 36, 5689, '01.jpg'),
('Mark Oto Ednalan', 'Chief Executive Officer (CEO)', 'London', 56, 5648, '02.jpg'),
('Jacob thompson', 'Junior Technical Author', 'San Francisco', 23, 5689, '03.jpg'),
('cylde Ednalan', 'Software Engineer', 'Olongapo', 23, 54654, '04.jpg'),
('Rhona Davidson', 'Software Engineer', 'San Francisco', 26, 5465, '05.jpg'),
('Quinn Flynn', 'Integration Specialist', 'New York', 53, 56465, '06.jpg'),
('Tiger Nixon', 'Software Engineer', 'London', 45, 456, '07.jpg'),
('Airi Satou', 'Pre-Sales Support', 'New York', 25, 4568, '08.jpg'),
('Angelica Ramos', 'Sales Assistant', 'New York', 45, 456, '09.jpg'),
('Ashton updated', 'Senior Javascript Developer', 'Olongapo', 45, 54565, '01.jpg'),
('Bradley Greer', 'Regional Director', 'San Francisco', 27, 5485, '02.jpg'),
('Brenden Wagner', 'Javascript Developer', 'San Francisco', 38, 65468, '03.jpg'),
('Brielle Williamson', 'Personnel Lead', 'Olongapo', 56, 354685, '04.jpg'),
('Bruno Nash', 'Customer Support', 'New York', 36, 65465, '05.jpg'),
('cairocoders', 'Sales Assistant', 'Sydney', 45, 56465, '06.jpg'),
('Zorita Serrano', 'Support Engineer', 'San Francisco', 38, 6548, '07.jpg'),
('Zenaida Frank', 'Chief Operating Officer (COO)', 'San Francisco', 39, 545, '08.jpg'),
('Sakura Yamamoto', 'Support Engineer', 'Tokyo', 48, 5468, '05.jpg'),
('Serge Baldwin', 'Data Coordinator', 'Singapore', 85, 5646, '05.jpg'),
('Shad Decker', 'Regional Director', 'Tokyo', 45, 4545, '05.jpg');

JqueryUI Slider https://jqueryui.com/slider/
app.py
 
#app.py
from flask import Flask, request, render_template, jsonify, json
import psycopg2 #pip install psycopg2 
import psycopg2.extras
   
app = Flask(__name__)
   
app.secret_key = "cairocoders-ednalan"
   
DB_HOST = "localhost"
DB_NAME = "sampledb"
DB_USER = "postgres"
DB_PASS = "admin"
   
conn = psycopg2.connect(dbname=DB_NAME, user=DB_USER, password=DB_PASS, host=DB_HOST)

@app.route('/')
def home():
    try:
        cursor = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
        cursor.execute("SELECT * from employee order by name asc")
        employeelist = cursor.fetchall()
        return render_template('index.html',employeelist=employeelist)
    except Exception as e:
        print(e)
    finally:
        cursor.close() 
 
@app.route("/fetchdeta",methods=["POST","GET"])
def fetchdeta():
    try:
        cursor = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
        if request.method == 'POST':
            min = request.form['min']
            max = request.form['max']
            cursor.execute("SELECT * from employee WHERE salary>=(%s) AND salary<=(%s)", [min,max,])
            employeelist = cursor.fetchall()
            return jsonify({'htmlresponse': render_template('response.html',employeelist=employeelist)})
    except Exception as e:
        print(e)
    finally:
        cursor.close() 
 
if __name__ == "__main__":
    app.run()
templates/index.html
//templates/index.html
<!doctype html>
<html>
<head>
<title>Filter Records using jQuery UI slider with Jquery Ajax and Python Flask PostgreSQL</title>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script type='text/javascript'>
        $(document).ready(function(){
 
            // Initializing slider
            $( "#slider" ).slider({
                range: true,
                min: 100,
                max: 360000,
                values: [ 100, 360000 ],
                slide: function( event, ui ) {
                    // Get values
                    var min = ui.values[0];
                    var max = ui.values[1];
                    $('#range').text(min+' - ' + max);
 
                    // AJAX request
                    $.ajax({
                        url: '/fetchdeta',
                        type: 'post',
                        data: {min:min,max:max},
                        success: function(response){
 
                            // Updating table data
                            $('#emp_table tr:not(:first)').remove();
                            $('#emp_table').append(response.htmlresponse);    
                        }      
                    });
                }
            });
        });
        </script>
    </head>
    <body >
        <div class="container" >
        <div class="row" style="padding:50px;">
            <p><h1>Filter Records using jQuery UI slider with Jquery Ajax and Python Flask PostgreSQL</h1></p>
            <!-- slider --> 
            <div id="slider"></div><br/>
            Range: <span id='range'></span>
 
            <table id='emp_table' class="alternate" width='100%'>
                <tr>
                    <th>Name</th>
                    <th>Position</th>
                    <th>Office</th>
                    <th>Salary</th>
                    </tr>
                    {% for row in employeelist %}  
                    <tr>
                      <td>{{row.name}}</td>
                      <td>{{row.position}}</td>
                      <td>{{row.office}}</td>
                      <td>{{row.salary}}</td>
                    </tr>
                    {% endfor %} 
            </table>
        </div>
        </div>
<style>
.alternate tr:nth-child(2n) {
  background-color: silver;
}
.alternate tr {
  background-color: white;
}
.alternate tr td {padding: 8px;}
.alternate tr:nth-child(2n):hover, .alternate tr:hover {
  background-color: grey;
}
</style>  
</body>
</html>
templates/response.html
//templates/response.html
{% for row in employeelist %}
<tr>
    <td>{{row.name}}</td>
    <td>{{row.position}}</td>
    <td>{{row.office}}</td>
    <td>{{row.salary}}</td>
</tr>
{% endfor %} 

Saturday, May 29, 2021

Jquery Ajax Live Editable Table using Python Flask PostgreSQL

Jquery Ajax Live Editable Table using Python Flask PostgreSQL

install psycopg2 https://pypi.org/project/psycopg2/
Psycopg is the most popular PostgreSQL database adapter for the Python programming language.
(venv) PS C:\flaskmyproject> pip install psycopg2

Create TABLE
CREATE TABLE users (
id serial PRIMARY KEY,
fullname VARCHAR ( 100 ) NOT NULL,
username VARCHAR ( 50 ) NOT NULL,
password VARCHAR ( 255 ) NOT NULL,
email VARCHAR ( 50 ) NOT NULL
);

app.py
 
#app.py
from flask import Flask, request, render_template, jsonify
import psycopg2 #pip install psycopg2 
import psycopg2.extras
  
app = Flask(__name__)
  
app.secret_key = "cairocoders-ednalan"
  
DB_HOST = "localhost"
DB_NAME = "sampledb"
DB_USER = "postgres"
DB_PASS = "admin"
  
conn = psycopg2.connect(dbname=DB_NAME, user=DB_USER, password=DB_PASS, host=DB_HOST)
  
@app.route('/')
def home():
    try:
        cursor = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
        cursor.execute("SELECT * from users order by id")
        userslist = cursor.fetchall()
        return render_template('index.html',userslist=userslist)
    except Exception as e:
        print(e)
    finally:
        cursor.close() 
 
@app.route("/update",methods=["POST","GET"])
def update():
    try:
        cursor = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
        if request.method == 'POST':
            field = request.form['field'] 
            value = request.form['value']
            editid = request.form['id']
             
            if field == 'username':
               sql = "UPDATE users SET username=%s WHERE id=%s"
            if field == 'name':        
                sql = "UPDATE users SET fullname=%s WHERE id=%s"
 
            data = (value, editid)
            cursor.execute(sql, data)
            conn.commit()
            success = 1
        return jsonify(success)
    except Exception as e:
        print(e)
    finally:
        cursor.close() 

if __name__ == "__main__":
    app.run()
templates/index.html
//templates/index.html
<!doctype html>
<html>
<head>
<title>Jquery Ajax Live Editable Table using Python Flask PostgreSQL</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />    
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script type='text/javascript'>
$(document).ready(function(){
  
 // Show Input element
 $('.edit').click(function(){
  $('.txtedit').hide();
  $(this).next('.txtedit').show().focus();
  $(this).hide();
 });
 
 // Save data
 $(".txtedit").focusout(function(){
   
  // Get edit id, field name and value
  var id = this.id;
  var split_id = id.split("_");
  var field_name = split_id[0];
  var edit_id = split_id[1];
  var value = $(this).val();
   
  // Hide Input element
  $(this).hide();
 
  // Hide and Change Text of the container with input elmeent
  $(this).prev('.edit').show();
  $(this).prev('.edit').text(value);
 
  $.ajax({
   url: '/update',
   type: 'post',
   data: { field:field_name, value:value, id:edit_id },
   success:function(response){
      if(response == 1){ 
         console.log('Save successfully'); 
      }else{ 
         console.log("Not saved.");  
      }
   }
  });
  
 });
 
});
</script>
</head>
<body >
<div class="container" >
    <div class="row" style="padding:50px;">
        <p><h1>Jquery Ajax Live Editable Table using Python Flask PostgreSQL</h1></p>
        <table width='100%' border='0'>
         <tr>
          <th width='10%'>ID</th>
          <th width='40%'>Username</th>
          <th width='40%'>Name</th>
         </tr>
         {% for row in userslist %}    
         <tr>
          <td>{{row.id}}</td>
          <td> 
            <div class='edit' > {{row.username}}</div> 
            <input type='text' class='txtedit' value='{{row.username}}' id='username_{{row.id}}' >
          </td>
          <td> 
           <div class='edit' >{{row.fullname}} </div> 
           <input type='text' class='txtedit' value='{{row.fullname}}' id='name_{{row.id}}' >
          </td>
         </tr>
         {% endfor %} 
        </table>
   </div>
</div>
<style>
.edit{
 width: 100%;
 height: 25px;
}
.editMode{
 border: 1px solid black;
}
table {
 border:3px solid lavender;
 border-radius:3px;
}
table tr:nth-child(1){
 background-color:#4285f4;
}
table tr:nth-child(1) th{
 color:white;
 padding:10px 0px;
 letter-spacing: 1px;
}
table td{
 padding:10px;
}
table tr:nth-child(even){
 background-color:lavender;
 color:black;
}
.txtedit{
 display: none;
 width: 99%;
 height: 30px;
}
</style>
</body>
</html>

DataTable AJAX using Python Flask PostgreSQL

DataTable AJAX using Python Flask PostgreSQL

Download Datatables from here. https://datatables.net/download/

install psycopg2 https://pypi.org/project/psycopg2/
Psycopg is the most popular PostgreSQL database adapter for the Python programming language.
(venv) PS C:\flaskmyproject> pip install psycopg2

CREATE TABLE employee (
id serial PRIMARY KEY,
name VARCHAR ( 100 ) NOT NULL,
position VARCHAR ( 100 ) NOT NULL,
office VARCHAR ( 100 ) NOT NULL,
age INT NOT NULL,
salary INT NOT NULL,
photo VARCHAR ( 150 ) NOT NULL,
);


INSERT INTO
    employee(name, position, office, age, salary, photo)
VALUES
('Tiger Wood', 'Accountant', 'Tokyo', 36, 5689, '01.jpg'),
('Mark Oto Ednalan', 'Chief Executive Officer (CEO)', 'London', 56, 5648, '02.jpg'),
('Jacob thompson', 'Junior Technical Author', 'San Francisco', 23, 5689, '03.jpg'),
('cylde Ednalan', 'Software Engineer', 'Olongapo', 23, 54654, '04.jpg'),
('Rhona Davidson', 'Software Engineer', 'San Francisco', 26, 5465, '05.jpg'),
('Quinn Flynn', 'Integration Specialist', 'New York', 53, 56465, '06.jpg'),
('Tiger Nixon', 'Software Engineer', 'London', 45, 456, '07.jpg'),
('Airi Satou', 'Pre-Sales Support', 'New York', 25, 4568, '08.jpg'),
('Angelica Ramos', 'Sales Assistant', 'New York', 45, 456, '09.jpg'),
('Ashton updated', 'Senior Javascript Developer', 'Olongapo', 45, 54565, '01.jpg'),
('Bradley Greer', 'Regional Director', 'San Francisco', 27, 5485, '02.jpg'),
('Brenden Wagner', 'Javascript Developer', 'San Francisco', 38, 65468, '03.jpg'),
('Brielle Williamson', 'Personnel Lead', 'Olongapo', 56, 354685, '04.jpg'),
('Bruno Nash', 'Customer Support', 'New York', 36, 65465, '05.jpg'),
('cairocoders', 'Sales Assistant', 'Sydney', 45, 56465, '06.jpg'),
('Zorita Serrano', 'Support Engineer', 'San Francisco', 38, 6548, '07.jpg'),
('Zenaida Frank', 'Chief Operating Officer (COO)', 'San Francisco', 39, 545, '08.jpg'),
('Sakura Yamamoto', 'Support Engineer', 'Tokyo', 48, 5468, '05.jpg'),
('Serge Baldwin', 'Data Coordinator', 'Singapore', 85, 5646, '05.jpg'),
('Shad Decker', 'Regional Director', 'Tokyo', 45, 4545, '05.jpg');
app.py
 
#app.py
from flask import Flask, request, render_template, jsonify, json
import psycopg2 #pip install psycopg2 
import psycopg2.extras
  
app = Flask(__name__)
  
app.secret_key = "cairocoders-ednalan"
  
DB_HOST = "localhost"
DB_NAME = "sampledb"
DB_USER = "postgres"
DB_PASS = "admin"
  
conn = psycopg2.connect(dbname=DB_NAME, user=DB_USER, password=DB_PASS, host=DB_HOST)
  
@app.route('/')
def home():
    return render_template('index.html')
 
@app.route("/ajaxfile",methods=["POST","GET"])
def ajaxfile():
    try:
        cursor = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
        if request.method == 'POST':
            draw = request.form['draw'] 
            row = int(request.form['start'])
            rowperpage = int(request.form['length'])
            searchValue = request.form["search[value]"]
            #print(draw)
            print(row)
            print(rowperpage)
            #print(searchValue)
 
            ## Total number of records without filtering
            cursor.execute("select count(*) as allcount from employee")
            rsallcount = cursor.fetchone()
            totalRecords = rsallcount['allcount']
            print(totalRecords) 
 
            ## Total number of records with filtering
            #likeString = "%" + searchValue + "%"

            likeString = "{}%".format(searchValue)

            print(likeString)
            cursor.execute("SELECT count(*) as allcount from employee WHERE name LIKE %s", (likeString,))
            rsallcount = cursor.fetchone()
            totalRecordwithFilter = rsallcount['allcount']
            print(totalRecordwithFilter) 
 
            ## Fetch records
            if searchValue=='':
                cursor.execute('SELECT * FROM employee LIMIT {limit} OFFSET {offset}'.format(limit=rowperpage, offset=row))
                employeelist = cursor.fetchall()
            else:        
                cursor.execute("SELECT * FROM employee WHERE name LIKE %s LIMIT %s OFFSET %s;", (likeString, rowperpage, row,))

                employeelist = cursor.fetchall()
 
            data = []
            for row in employeelist:
                data.append({
                    'name': row['name'],
                    'position': row['position'],
                    'age': row['age'],
                    'salary': row['salary'],
                    'office': row['office'],
                })
 
            response = {
                'draw': draw,
                'iTotalRecords': totalRecords,
                'iTotalDisplayRecords': totalRecordwithFilter,
                'aaData': data,
            }
            return jsonify(response)
    except Exception as e:
        print(e)
    finally:
        cursor.close() 
 
if __name__ == "__main__":
    app.run()
templates/index.html
//templates/index.html
<!doctype html>
<html>
<head>
<title>DataTable AJAX using Python Flask PostgreSQL</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />    
<link href='https://cdn.datatables.net/1.10.24/css/jquery.dataTables.min.css' rel='stylesheet' type='text/css'>
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script src="https://cdn.datatables.net/1.10.24/js/jquery.dataTables.min.js"></script>
</head>
<body >
<div class="container" >
    <div class="row" style="padding:50px;">
        <p><h1>DataTable AJAX using Python Flask PostgreSQL</h1></p>
        <div >
            <table id='empTable' class='display dataTable' width='100%'>
                <thead>
                <tr>
                    <th>Employee Name</th>
                    <th>Position</th>
                    <th>Age</th>
                    <th>Salary</th>
                    <th>Office</th>
                </tr>
                </thead>
                 
            </table>
        </div>
   </div>
</div>
<script>
$(document).ready(function() {
    var empDataTable = $('#empTable').DataTable({
                'processing': true,
                'serverSide': true,
                'serverMethod': 'post',
                'ajax': {
                    'url':'/ajaxfile'
                },
                'lengthMenu': [[5, 10, 25, 50, -1], [5, 10, 25, 50, "All"]],
                searching: true,
                sort: false,
                "serverSide": true,
                'columns': [
                    { data: 'name' },
                    { data: 'position' },
                    { data: 'age' },
                    { data: 'salary' },
                    { data: 'office' },
                ]
            });
});
</script>
</body>
</html>

Thursday, May 13, 2021

Dynamic Select Box using Python Flask PostgreSQL Flask-WTF, javascript and SQLAlchemy

Dynamic Select Box using Python Flask PostgreSQL Flask-WTF, javascript and SQLAlchemy

install psycopg2 https://pypi.org/project/psycopg2/
Psycopg is the most popular PostgreSQL database adapter for the Python programming language.
(venv) PS C:\flaskmyproject> pip install psycopg2


CREATE TABLE countries (
id serial PRIMARY KEY,
name VARCHAR ( 60 ) NOT NULL
);

INSERT INTO
    countries(id,name)
VALUES
(1, 'Afghanistan'),
(2, 'Aringland Islands'),
(3, 'Albania'),
(4, 'Algeria'),
(5, 'American Samoa'),
(6, 'Andorra');

CREATE TABLE state (
id serial PRIMARY KEY,
name VARCHAR ( 60 ) NOT NULL,
country_id INT NOT NULL
);

INSERT INTO state (id, name, country_id) VALUES (1, 'ARMM', 171);
INSERT INTO state (id, name, country_id) VALUES (2, 'Bicol', 171);
INSERT INTO state (id, name, country_id) VALUES (3, 'Central Luzon', 171);
INSERT INTO state (id, name, country_id) VALUES (4, 'Central Mindanao', 171);
INSERT INTO state (id, name, country_id) VALUES (5, 'Alabama', 227);
INSERT INTO state (id, name, country_id) VALUES (6, 'Alaska', 227);
INSERT INTO state (id, name, country_id) VALUES (7, 'Arizona', 227);
INSERT INTO state (id, name, country_id) VALUES (8, 'California', 227);
INSERT INTO state (id, name, country_id) VALUES (9, 'Florida', 227);

CREATE TABLE city (
id serial PRIMARY KEY,
state VARCHAR ( 60 ) NOT NULL,
name VARCHAR ( 60 ) NOT NULL,
stateid INT NOT NULL
);

INSERT INTO city (id, state, name, stateid) VALUES (1, 'CA', 'Anaheim', 8);
INSERT INTO city (id, state, name, stateid) VALUES (2, 'NV', 'Arden-Arcade', 8);
INSERT INTO city (id, state, name, stateid) VALUES (3, 'CA', 'Bakersfield', 8);
INSERT INTO city (id, state, name, stateid) VALUES (4, 'CA', 'Carson', 8);
INSERT INTO city (id, state, name, stateid) VALUES (5, 'NV', 'Daly City', 8);
INSERT INTO city (id, state, name, stateid) VALUES (6, 'AC', 'Angeles City', 3);
INSERT INTO city (id, state, name, stateid) VALUES (7, 'OC', 'Olongapo', 3);
INSERT INTO city (id, state, name, stateid) VALUES (8, 'SF', 'San Fernando', 3);
INSERT INTO city (id, state, name, stateid) VALUES (9, 'TA', 'Tarlac', 3);
app.py
 
#app.py
from flask import Flask, render_template, request, jsonify
from flask_sqlalchemy import SQLAlchemy  
from wtforms import SelectField
from flask_wtf import FlaskForm #https://flask-wtf.readthedocs.io/en/stable/

app = Flask(__name__)

app.config['SECRET_KEY'] = 'cairocoders-ednalan'

app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
                                                      #password:admin
app.config['SQLALCHEMY_DATABASE_URI']='postgresql://postgres:admin@localhost/sampledb' #install psycopg2 https://pypi.org/project/psycopg2/

db = SQLAlchemy(app)

class Country(db.Model):
    __tablename__ = 'countries'
  
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(60))
  
class State(db.Model):
    __tablename__ = 'state'
  
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(60))
    country_id = db.Column(db.Integer)
  
class City(db.Model):
    __tablename__ = 'city'
    
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(60))
    stateid = db.Column(db.Integer) 
 
class Form(FlaskForm):
    country = SelectField('country', choices=[])
    state = SelectField('state', choices=[])
    city = SelectField('city', choices=[])
         
@app.route('/', methods=['GET', 'POST'])
def index():
    form = Form()
    form.country.choices = [(country.id, country.name) for country in Country.query.all()]
  
    if request.method == 'POST':
        city = City.query.filter_by(id=form.city.data).first()
        country = Country.query.filter_by(id=form.country.data).first()
        state = State.query.filter_by(id=form.state.data).first()
        return '

Country : {}, State: {}, City: {}

'.format(country.name, state.name, city.name) return render_template('index.html', form=form) @app.route('/state/') def statebycountry(get_state): state = State.query.filter_by(country_id=get_state).all() stateArray = [] for city in state: stateObj = {} stateObj['id'] = city.id stateObj['name'] = city.name stateArray.append(stateObj) return jsonify({'statecountry' : stateArray}) @app.route('/city/') def city(get_city): state_data = City.query.filter_by(stateid=get_city).all() cityArray = [] for city in state_data: cityObj = {} cityObj['id'] = city.id cityObj['name'] = city.name cityArray.append(cityObj) return jsonify({'citylist' : cityArray}) if __name__ == '__main__': app.run(debug=True)
templates/index.html
#templates/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Dynamic Select Box using Python Flask PostgreSQL Flask-WTF, javascript and SQLAlchemy</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
</head>
<body>
<div class="container">
    <div class="row">
        <div class="col-md-12">
        <p><h2>Dynamic Select Box using Python Flask PostgreSQL Flask-WTF, javascript and SQLAlchemy</h2></p>
        <form method="POST">
          {{ form.csrf_token}}  
                <div class="form-group">
                <label for="email">Country:</label>
                {{ form.country(class="form-control") }}
            </div>
            <div class="form-group">
                <label for="email">State:</label>
                {{ form.state(class="form-control")}}
            </div>
            <div class="form-group">
                <label for="email">City:</label>
                {{ form.city(class="form-control")}} 
            </div>
                <input type="submit" class="btn btn-success" btn-lg>
        </form> 
        </div>
    </div>
</div> 
<script>
country_select = document.getElementById('country');
state_select = document.getElementById('state');
city_select = document.getElementById('city');
 
country_select.onchange = function(){
    country = country_select.value;
    fetch('state/' + country).then(function(response){
        response.json().then(function(data) {
            optionHTML = '';
            for (state of data.statecountry) {
                optionHTML += '<option value="' + state.id +'">' + state.name + '</option>'
            }
            state_select.innerHTML = optionHTML;
        });
    });
}
state_select.onchange = function(){
    city = state_select.value; 
    fetch('city/' + city).then(function(response){
        response.json().then(function(data) {
            optionHTML = '';
            for (city_rs of data.citylist) {
                optionHTML += '<option value="' + city_rs.id +'">' + city_rs.name + '</option>'
            }
            city_select.innerHTML = optionHTML;
        });
    });
}
</script>
</body>
</html>

Wednesday, May 12, 2021

Autocomplete Jquery Ajax Using Python Flask PostgreSQL and SQLAlchemy database

Autocomplete Jquery Ajax Using Python Flask PostgreSQL and SQLAlchemy database

install psycopg2 https://pypi.org/project/psycopg2/
Psycopg is the most popular PostgreSQL database adapter for the Python programming language.
(venv) PS C:\flaskmyproject> pip install psycopg2

CREATE TABLE countries (
id serial PRIMARY KEY,
name VARCHAR ( 60 ) NOT NULL
);

INSERT INTO
    countries(id,name)
VALUES
(1, 'Afghanistan'),
(2, 'Aringland Islands'),
(3, 'Albania'),
(4, 'Algeria'),
(5, 'American Samoa'),
(6, 'Andorra'),
(7, 'Angola'),
(8, 'Anguilla'),
(9, 'Antarctica'),
(10, 'Antigua and Barbuda'),
(11, 'Argentina'),
(12, 'Armenia'),
(13, 'Aruba'),
(14, 'Australia');
app.py
 
#app.py
from flask import Flask, render_template, request, jsonify
from wtforms import StringField, TextField, Form
from wtforms.validators import DataRequired, Length
from flask_sqlalchemy import SQLAlchemy  
 
app = Flask(__name__)

app.config['SECRET_KEY'] = 'cairocoders-ednalan'

app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
                                                      #password:admin
app.config['SQLALCHEMY_DATABASE_URI']='postgresql://postgres:admin@localhost/sampledb'

db = SQLAlchemy(app) 
  
class SearchForm(Form): #create form
    country = StringField('Country', validators=[DataRequired(),Length(max=40)],render_kw={"placeholder": "country"})
 
class Country(db.Model):
    __tablename__='countries'
    id=db.Column(db.Integer,primary_key=True)
    name = db.Column(db.String(60), unique=True, nullable = False)
 
    def as_dict(self):
        return {'name': self.name}
   
@app.route('/')
def index():
    form = SearchForm(request.form)
    return render_template('index.html', form=form)
 
@app.route('/countries')
def countrydic():
    res = Country.query.all()

    list_countries = [r.as_dict() for r in res]
    return jsonify(list_countries)
  
@app.route('/process', methods=['POST'])
def process():
    country = request.form['country']
    if country:
        return jsonify({'country':country})
    return jsonify({'error': 'missing data..'})

if __name__ == '__main__':
    app.run(debug=True)
templates/index.html
//templates/index.html
<html>
<head>
<meta charset="utf-8">
<title>Autocomplete Jquery Ajax Using Python Flask PostgreSQL and SQLAlchemy database</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
    <h1>Autocomplete Jquery Ajax Using Python Flask PostgreSQL and SQLAlchemy database</h1>
    <form class="form-inline">
    <div class="form-group">
        {{form.country(class="form-control")}}
    </div>
    <button type="submit" class="btn btn-info">Submit</button>
    </form>
    <div id="result"></div>
<script>
$(document).ready(function(){
    var countries=[];
    function loadCountries(){
        $.getJSON('/countries', function(data, status, xhr){
            for (var i = 0; i < data.length; i++ ) {
                countries.push(data[i].name);
            }
        });
    };
    loadCountries();
 
    $('#country').autocomplete({
        source: countries, 
    }); 
 
    $('form').on('submit', function(e){
        $.ajax({
        data: {
            country:$('#country').val()
        },
        type: 'POST',
        url : '/process'
        })
        .done(function(data){ 
            if (data.error){
                $('#result').text(data.error).show();
            }
            else {
                $('#result').html(data.country).show()
            }
        })
        e.preventDefault();
    });
}); 
</script>
<style>
.form-control {
    display: block;
    width:300px;
    padding: .375rem .75rem;
    font-size: 1rem;
    line-height: 1.5;
    color: #495057;
    background-color: #fff;
    background-clip: padding-box;
    border: 1px solid #ced4da;
    border-radius: .25rem;
    transition: border-color .15s ease-in-out,box-shadow .15s ease-in-out;
}
.btn {padding: .375rem .75rem; margin-top:10px;}
</style>
  </body>
</html>

Python Flask PostgreSQL Delete Multiple records using checkbox with getlist

Python Flask PostgreSQL Delete Multiple records using checkbox with getlist

install psycopg2 https://pypi.org/project/psycopg2/
Psycopg is the most popular PostgreSQL database adapter for the Python programming language.
(venv) PS C:\flaskmyproject> pip install psycopg2

Crate database table
CREATE TABLE students (
id serial PRIMARY KEY,
fname VARCHAR ( 40 ) NOT NULL,
lname VARCHAR ( 40 ) NOT NULL,
email VARCHAR ( 40 ) NOT NULL
profile_pic VARCHAR ( 150 ) NULL
);

SELECT * FROM students 

Multiple insert
INSERT INTO
    students(id,fname,lname,email)
VALUES
    ('Quinn','Flynn'', 'Flynn'@gmail.com'),
    ('Tiger','nizon', 'nizon@gmail.com'),
    ('Airi','sato', 'sato@gmail.com');
app.py
 
#app.py
from flask import Flask, render_template, flash, redirect, url_for, request
import psycopg2 #pip install psycopg2 
import psycopg2.extras
 
app = Flask(__name__)
 
app.secret_key = "cairocoders-ednalan"
 
DB_HOST = "localhost"
DB_NAME = "sampledb"
DB_USER = "postgres"
DB_PASS = "admin"
 
conn = psycopg2.connect(dbname=DB_NAME, user=DB_USER, password=DB_PASS, host=DB_HOST)

@app.route('/')
def home():
    cursor = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
 
    cursor.execute("SELECT * FROM students")
    rows = cursor.fetchall()
    return render_template('index.html', students=rows)

@app.route('/delete', methods=['GET', 'POST'])
def index():
    cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)

    if request.method == 'POST': 
        #test = request.form.getlist('mycheckbox')
        for getid in request.form.getlist('mycheckbox'):
            print(getid)
            cur.execute('DELETE FROM students WHERE id = {0}'.format(getid))
            conn.commit()
        flash('Student Removed Successfully')
        return redirect('/')

if __name__ == '__main__':
    app.run(debug=True)
templates/index.html
//templates/index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Python Flask PostgreSQL Delete Multiple records using checkbox with getlist</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
</head>
<body>
<div class="container">
 <div class="row">
        <div class="col-md-12">
        <p><h2>Python Flask PostgreSQL Delete Multiple records using checkbox with getlist</h2></p>
        <div class="table-responsive">
        <form method="POST" action="/delete">        
        <table id="mytable" class="table table-bordred table-striped">
            <thead>
                <th><input type="checkbox" id="checkall" /></th>
                <th>First Name</th>
                <th>Last Name</th>
                <th>Email</th>
                <th width="50">Edit</th>
                <th width="50">Delete</th>
            </thead>
            <tbody>
            {% for rs in students %}
            <tr>
              <td><input type="checkbox" value="{{ rs.id }}" name="mycheckbox" class="checkthis" /></td>
              <td>{{ rs.fname }}</td>
              <td>{{ rs.lname }}</td>
              <td>{{ rs.email }}</td>
              <td><p data-placement="top" data-toggle="tooltip" title="Edit"><button class="btn btn-primary btn-xs" data-title="Edit" data-toggle="modal" data-target="#edit" ><span class="glyphicon glyphicon-pencil"></span></button></p></td>
              <td><p data-placement="top" data-toggle="tooltip" title="Delete"><button class="btn btn-danger btn-xs" data-title="Delete" data-toggle="modal" data-target="#delete" ><span class="glyphicon glyphicon-trash"></span></button></p></td>
            </tr>
            {% endfor %}
            </tbody>
         
      </table><input type="submit" value="Delete All Selected" class="btn btn-primary">  
      <br/>
      <div>
        {% with messages = get_flashed_messages() %}
            {% if messages %}
            {% for message in messages %}
            <div class="alert alert-danger" role="alert">{{ message }}</div>
            {% endfor %}
            {% endif %}
        {% endwith %}
        </div>
        </form>        
            </div>
             
        </div>
 </div>
</div>
<script>
$(document).ready(function(){
$("#mytable #checkall").click(function () {
        if ($("#mytable #checkall").is(':checked')) {
            $("#mytable input[type=checkbox]").each(function () {
                $(this).prop("checked", true);
            });
 
        } else {
            $("#mytable input[type=checkbox]").each(function () {
                $(this).prop("checked", false);
            });
        }
    });
     
    $("[data-toggle=tooltip]").tooltip();
});
</script>  
</body>
</html>

Tuesday, May 11, 2021

Upload File and validate before save to Database using Python Flask PostgreSQL and SQLAlchemy

Upload File and validate before save to Database using Python Flask PostgreSQL and SQLAlchemy

install psycopg2 https://pypi.org/project/psycopg2/
Psycopg is the most popular PostgreSQL database adapter for the Python programming language.
(venv) PS C:\flaskmyproject> pip install psycopg2

Crate database table
CREATE TABLE students (
id serial PRIMARY KEY,
fname VARCHAR ( 40 ) NOT NULL,
lname VARCHAR ( 40 ) NOT NULL,
email VARCHAR ( 40 ) NOT NULL
profile_pic VARCHAR ( 150 ) NULL
);

SELECT * FROM students 
app.py
#app.py
from flask import Flask, render_template, flash, redirect, url_for, request
from flask_sqlalchemy import SQLAlchemy
from werkzeug.utils import secure_filename
import os
#import magic
import urllib.request

app = Flask(__name__)

app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
                                                      #password:admin
app.config['SQLALCHEMY_DATABASE_URI']='postgresql://postgres:admin@localhost/sampledb'
 
db=SQLAlchemy(app)

app.config['SECRET_KEY'] = 'cairocoders-ednalan'
 
UPLOAD_FOLDER = 'static/uploads'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024
  
ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])
  
def allowed_file(filename):
  return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

class Student(db.Model):
  __tablename__='students'
  id=db.Column(db.Integer,primary_key=True)
  fname=db.Column(db.String(40))
  lname=db.Column(db.String(40))
  email=db.Column(db.String(40))
  profile_pic = db.Column(db.String(150))

  def __init__(self,fname,lname,email,profile_pic):
    self.fname=fname
    self.lname=lname
    self.email=email
    self.profile_pic=profile_pic
  
@app.route('/')
def index():
    return render_template('index.html')
 
@app.route('/upload', methods=['POST'])
def upload():
    file = request.files['inputFile']
    fname = request.form['fname']
    lname = request.form['lname']
    filename = secure_filename(file.filename)
  
    if file and allowed_file(file.filename):
       file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
  
       newFile = Student(profile_pic=file.filename, fname=fname, lname=lname, email='cairocoders@gmail.com')
       db.session.add(newFile)
       db.session.commit()
       flash('File successfully uploaded ' + file.filename + ' to the database!')
       return redirect('/')
    else:
       flash('Invalid Uplaod only txt, pdf, png, jpg, jpeg, gif') 
    return redirect('/')    
  
if __name__ == '__main__':
    app.run(debug=True)
//templates/index.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>Upload File and validate before save to Database using Python Flask PostgreSQL and SQLAlchemy </title>
  </head>
  <body>
  <h2>Upload File and validate before save to Database using Python Flask PostgreSQL and SQLAlchemy </h2>
  <h3>Select a file to upload</h3>
        <p>
         {% with messages = get_flashed_messages() %}
           {% if messages %}
          {% for message in messages %}
            <div class="alert alert-primary">
             <strong>{{ message }}</strong>
           </div>
          {% endfor %}
           {% endif %}
         {% endwith %}
        </p>
  <form method="post" action="/upload" enctype="multipart/form-data">
    First Name : <input type="text" name="fname" value="" placeholder="First Name" required>
    Last Name : <input type="text" name="lname" value="" placeholder="Last Name" required>
    <dl>
  <p>
   <input type="file" name="inputFile" autocomplete="off" required>
  </p>
    </dl>
    <p>
  <input type="submit" value="Submit">
 </p>
</form>
<style>
.alert-primary {
    color: #004085;
    background-color: #cce5ff;
    border-color: #b8daff;
}
.alert {
    position: relative;
    padding: .75rem 1.25rem;
    margin-bottom: 1rem;
    border: 1px solid transparent;
    border-radius: .25rem;
}
</style>
    </body>
</html>

Pagination using Python Flask PostgreSQL and SQLAlchemy

Pagination using Python Flask PostgreSQL and SQLAlchemy

install psycopg2 https://pypi.org/project/psycopg2/
Psycopg is the most popular PostgreSQL database adapter for the Python programming language.
(venv) PS C:\flaskmyproject> pip install psycopg2

Crate database table
CREATE TABLE students (
id serial PRIMARY KEY,
fname VARCHAR ( 40 ) NOT NULL,
lname VARCHAR ( 40 ) NOT NULL,
email VARCHAR ( 40 ) NOT NULL
);

SELECT * FROM students 

INSERT INTO students (fname, lname, email)
VALUES('cairocoders','ednalan', 'cairocoders@gmail.com');

Multiple insert
INSERT INTO
    students(id,fname,lname,email)
VALUES
    ('Quinn','Flynn'', 'Flynn'@gmail.com'),
    ('Tiger','nizon', 'nizon@gmail.com'),
    ('Airi','sato', 'sato@gmail.com');
 
#app.py
from flask import Flask, render_template
from flask_sqlalchemy import SQLAlchemy
 
app = Flask(__name__)
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
                                                      #password:admin
app.config['SQLALCHEMY_DATABASE_URI']='postgresql://postgres:admin@localhost/sampledb'
 
db=SQLAlchemy(app)
 
class Student(db.Model):
  __tablename__='students'
  id=db.Column(db.Integer,primary_key=True)
  fname=db.Column(db.String(40))
  lname=db.Column(db.String(40))
  email=db.Column(db.String(40))
 
  def __init__(self,fname,lname,email):
    self.fname=fname
    self.lname=lname
    self.email=email
  
@app.route('/student/')
def student(page_num):
    student = Student.query.paginate(per_page=5, page=page_num, error_out=True)
    return render_template('index.html', student=student)
  
if __name__ == '__main__':
    app.run(debug=True)
templates/index.html
//templates/index.html
<html>
<head>
<title>Python Flask SQLAlchemy Pagination</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>   
</head>
<body>
<div class="container">
 <div class="row" style="padding: 20px;">
 <p><h2>Pagination using Python Flask PostgreSQL and SQLAlchemy</h2>  </p>
 <table id="example" class="table table-striped table-bordered" style="width:100%">
        <thead>
            <tr>
                <th><input type="checkbox" onclick="checkAll(this)"></th>
                <th>First Name</th>
                <th>Last Name</th>
                <th>Email</th>
            </tr>
        </thead>
        <tbody>
   {% for rs in student.items %}
   <tr>
                <td><input type="checkbox" name=""></td>
                <td>{{ rs.fname}}</td>
                <td>{{ rs.lname}}</td>
                <td>{{ rs.email}}</td>
            {% endfor %}
    </tr>        
        </tbody>
        <tfoot>
            <tr>
                <th></th>
                <th>First Name</th>
                <th>Last Name</th>
                <th>Email</th>
            </tr>
        </tfoot>
    </table>
 </div>
  
   <ul class="pagination">
  {% if student.has_prev %}
   <li class="page-item"><a class="page-link" href="{{ url_for('student', page_num=student.prev_num) }}">Previous</a></li>
  {% else %}
   <li class="page-item disabled"><span class="page-link">Previous</span>
  {% endif %}
   </li>
    
  {% for page in student.iter_pages(left_edge=3, right_edge=3) %}
  {% if page %}
   <li class="page-item"><a class="page-link" href="{{ url_for('student', page_num=page) }}">{{ page }}</a></li>
  {% else %}
   <li class="page-item disabled" id="example_ellipsis"><a href="#" class="page-link">…</a></li> 
  {% endif %}
  {% endfor %}
  
  {% if student.has_next %}
   <li class="page-item"><a class="page-link" href="{{ url_for('student', page_num=student.next_num) }}">Next</a></li>
  {% else %}
   <li class="page-item disabled"><span class="page-link">Next</span>
  {% endif %}
   </ul>
 
</div>
<style>
table{
    width:100%;
}
#example_filter{
    float:right;
}
#example_paginate{
    float:right;
}
label {
    display: inline-flex;
    margin-bottom: .5rem;
    margin-top: .5rem;
    
}
.page-item.disabled .page-link {
    color: #6c757d;
    pointer-events: none;
    cursor: auto;
    background-color: #fff;
    border-color: #dee2e6;
}
</style>
<script>
function checkAll(bx) {
  var cbs = document.getElementsByTagName('input');
  for(var i=0; i < cbs.length; i++) {
    if(cbs[i].type == 'checkbox') {
      cbs[i].checked = bx.checked;
    }
  }
}
</script>  
</body>
</html>

Monday, May 10, 2021

Shopping Cart using Python Flask PostgreSQL

Shopping Cart using Python Flask PostgreSQL

install psycopg2 https://pypi.org/project/psycopg2/
Psycopg is the most popular PostgreSQL database adapter for the Python programming language.
(venv) PS C:\flaskmyproject> pip install psycopg2

CREATE TABLE product (
pid serial PRIMARY KEY,
code VARCHAR ( 100 ) NOT NULL,
name VARCHAR ( 100 ) NOT NULL,
image VARCHAR ( 100 ) NOT NULL,
category VARCHAR ( 50 ) NOT NULL,
price INT NOT NULL,
discount INT NOT NULL
);

Multiple insert
INSERT INTO
    product(code,name,image,category,price,discount)
VALUES
    ('00001','Samsung Galaxy A10S','2.jpg', 'Mobile', 520, 100),
    ('00002',, 'Samsung Galaxy Win Duos', '3.jpg', 'Mobile', 1600, 500),
    ('00003', 'Women Summer Spaghetti Strap Down', '4.jpg', 'Woman Dresess', 2020, 1250);

This shopping cart have no checkout option and payment option this is about to display product and add item to cart remove item from cart remove all items from cart

app.py
 
#app.py
from flask import Flask, session, render_template, request, redirect, url_for
import psycopg2 #pip install psycopg2 
import psycopg2.extras

app = Flask(__name__)

app.secret_key = "cairocoders-ednalan"

DB_HOST = "localhost"
DB_NAME = "sampledb"
DB_USER = "postgres"
DB_PASS = "admin"

conn = psycopg2.connect(dbname=DB_NAME, user=DB_USER, password=DB_PASS, host=DB_HOST)

@app.route('/')
def products():
    cursor = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)

    cursor.execute("SELECT * FROM product")
    rows = cursor.fetchall()
    return render_template('products.html', products=rows)

@app.route('/add', methods=['POST'])
def add_product_to_cart():
    _quantity = int(request.form['quantity'])
    _code = request.form['code']
    # validate the received values
    if _quantity and _code and request.method == 'POST':

        cursor = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)

        cursor.execute('SELECT * FROM product WHERE code = %s', (_code,))
        row = cursor.fetchone()
                
        itemArray = { row['code'] : {'name' : row['name'], 'code' : row['code'], 'quantity' : _quantity, 'price' : row['price'], 'image' : row['image'], 'total_price': _quantity * row['price']}}
                
        all_total_price = 0
        all_total_quantity = 0
                
        session.modified = True
        if 'cart_item' in session:
            if row['code'] in session['cart_item']:
                for key, value in session['cart_item'].items():
                    if row['code'] == key:
                        old_quantity = session['cart_item'][key]['quantity']
                        total_quantity = old_quantity + _quantity
                        session['cart_item'][key]['quantity'] = total_quantity
                        session['cart_item'][key]['total_price'] = total_quantity * row['price']
            else:
                session['cart_item'] = array_merge(session['cart_item'], itemArray)
        
            for key, value in session['cart_item'].items():
                individual_quantity = int(session['cart_item'][key]['quantity'])
                individual_price = float(session['cart_item'][key]['total_price'])
                all_total_quantity = all_total_quantity + individual_quantity
                all_total_price = all_total_price + individual_price
        else:
            session['cart_item'] = itemArray
            all_total_quantity = all_total_quantity + _quantity
            all_total_price = all_total_price + _quantity * row['price']
            
        session['all_total_quantity'] = all_total_quantity
        session['all_total_price'] = all_total_price
                
        return redirect(url_for('products'))
    else:
        return 'Error while adding item to cart'

@app.route('/empty')
def empty_cart():
    try:
        session.clear()
        return redirect(url_for('.products'))
    except Exception as e:
        print(e)

@app.route('/delete/')
def delete_product(code):
    try:
        all_total_price = 0
        all_total_quantity = 0
        session.modified = True
        
        for item in session['cart_item'].items():
            if item[0] == code:    
                session['cart_item'].pop(item[0], None)
                if 'cart_item' in session:
                    for key, value in session['cart_item'].items():
                        individual_quantity = int(session['cart_item'][key]['quantity'])
                        individual_price = float(session['cart_item'][key]['total_price'])
                        all_total_quantity = all_total_quantity + individual_quantity
                        all_total_price = all_total_price + individual_price
                break
        
        if all_total_quantity == 0:
            session.clear()
        else:
            session['all_total_quantity'] = all_total_quantity
            session['all_total_price'] = all_total_price
            
        return redirect(url_for('.products'))
    except Exception as e:
        print(e)

def array_merge( first_array , second_array ):
    if isinstance( first_array , list ) and isinstance( second_array , list ):
        return first_array + second_array
    elif isinstance( first_array , dict ) and isinstance( second_array , dict ):
        return dict( list( first_array.items() ) + list( second_array.items() ) )
    elif isinstance( first_array , set ) and isinstance( second_array , set ):
        return first_array.union( second_array )
    return False

if __name__ == "__main__":
    app.run(debug=True)
templates/product.html
//templates/product.html
<!DOCTYPE html>
<html>
<head>
 <title>Shopping Cart using Python Flask PostgreSQL</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> 
<div class="container">
    <div class="row">
  <p><h2>Shopping Cart using Python Flask PostgreSQL</h2></p>
   <div class="col-sm-12">
        <div>
        {% with messages = get_flashed_messages() %}
            {% if messages %}
            <ul class=flashes>
            {% for message in messages %}
            <li>{{ message }}</li>
            {% endfor %}
            </ul>
            {% endif %}
        {% endwith %}
        </div>
  {% if 'cart_item' in session %}
   <p><a id="btnEmpty" href="{{ url_for('.empty_cart') }}" class="btn btn-danger">Empty Cart</a></p>
            <table class="table table-hover">
                <thead>
                    <tr>
                        <th>Product</th>
                        <th>Quantity</th>
                        <th class="text-center">Unit Price</th>
                        <th class="text-center">Price</th>
                        <th> </th>
                    </tr>
                </thead>
                <tbody>
    {% for key, val in session['cart_item'].items() %}
        {% set quantity = session['cart_item'][key]['quantity'] %}
        {% set price = session['cart_item'][key]['price'] %}
        {% set item_price = session['cart_item'][key]['total_price'] %} 
                    <tr>
                        <td class="col-sm-8 col-md-6">
                        <div class="media">
                            <a class="thumbnail pull-left" href="#"> <img class="media-object" src="/static/images/{{ session['cart_item'][key]['image'] }}" style="width: 72px; height: 72px;"> </a>
                            <div class="media-body" style="padding-left:10px;">
                                <h4 class="media-heading"> <a href="#">{{ session['cart_item'][key]['name'] }}</a></h4>
                                <h5 class="media-heading"> by <a href="#">Brand name</a></h5>
                                <span>Status: </span><span class="text-success"><strong>In Stock</strong></span>
                            </div>
                        </div></td>
                        <td class="col-sm-1 col-md-1" style="text-align: center">
                        <input type="email" class="form-control" value="{{ quantity }}">
                        </td>
                        <td class="col-sm-1 col-md-1 text-center"><strong>${{ price }} </strong></td>
                        <td class="col-sm-1 col-md-1 text-center"><strong>${{ item_price }} </strong></td>
                        <td class="col-sm-1 col-md-1">
                        <a href="{{ url_for('.delete_product', code=session['cart_item'][key]['code']) }}" class="btn btn-danger">
                            <span class="glyphicon glyphicon-remove"></span> Remove
                        </a></td>
                    </tr>
    {% endfor %}
                    <tr>
                        <td colspan="4"><h5>Total Quantity</h5></td>
                        <td class="text-right"><h5><strong>{{ session['all_total_quantity'] }}</strong></h5></td>
                    </tr>
                    <tr>
                        <td colspan="3"><h3>Total</h3></td>
                        <td colspan="2" class="text-right"><h3><strong>$ {{ session['all_total_price'] }}</strong></h3></td>
                    </tr>
                    <tr>
                        <td colspan="4">
                        <button type="button" class="btn btn-default">
                            <span class="glyphicon glyphicon-shopping-cart"></span> Continue Shopping
                        </button></td>
                        <td>
                        <button type="button" class="btn btn-success">
                            Checkout <span class="glyphicon glyphicon-play"></span>
                        </button></td>
                    </tr>
                </tbody>
            </table>
  {% else: %}
   <div class="no-records">Your Cart is Empty</div>
  {% endif %}
        </div>
    </div>
</div>
               
<section class="our-publication pt-100 pb-70">
            <div class="container">
                <div class="section-header">
                    <i class="fa fa-book"></i>
                    <h2>Our Product</h2>
                    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod  labore et dolore magna aliqua.</p>
                </div>
                 
                <div class="row">
    {% for product in products %}
                    <div class="col-sm-6 col-lg-3"> 
      <form method="post" action="/add">
                        <div class="single-publication">
                            <figure style="width:263px;">
                                <a href="#">
                                    <img src="/static/images/{{ product.image }}">
                                </a>
                                <ul>
                                    <li><a href="#" title="Add to Favorite"><i class="fa fa-heart"></i></a></li>
                                    <li><a href="#" title="Add to Compare"><i class="fa fa-refresh"></i></a></li>
                                    <li><a href="#" title="Quick View"><i class="fa fa-search"></i></a></li>
                                </ul>
                            </figure>
 
                            <div class="publication-content">
                                <span class="category">{{ product.category }}</span>
                                <h3><a href="#">{{ product.name }}</a></h3>
                                <ul>
                                    <li><i class="icofont-star"></i></li>
                                    <li><i class="icofont-star"></i></li>
                                    <li><i class="icofont-star"></i></li>
                                    <li><i class="icofont-star"></i></li>
                                    <li><i class="icofont-star"></i></li>
                                </ul>
                                <h4 class="price">$ {{ product.price }}</h4>
                            </div>
 
                            <div class="add-to-cart">
        <input type="hidden" name="code" value="{{ product.code }}"/>
        <input type="text" class="product-quantity" name="quantity" value="1" size="2" />
        <input type="submit" value="Add to Cart" class="default-btn" />
                            </div>
                        </div>
      </form>
                    </div>
                {% endfor %}    
                     
                </div>
            </div>
        </section>
<style>
.pt-100 {
                padding-top: 100px;
            }
            .pb-70 {
                padding-bottom: 70px;
            }
            .section-header {
                margin-bottom: 60px;
                text-align: center;
            }
            .section-header i {
                color: #ff007d;
                font-size: 50px;
                display: inline-block;
                margin-bottom: 10px;
            }
            .section-header h2 {
                font-weight: bold;
                font-size: 34px;
                margin: 0;
            }
            .section-header p {
                max-width: 500px;
                margin: 20px auto 0;
            }
            .single-publication {
                border: 1px solid #f2eee2;
                margin-bottom: 30px;
                position: relative;
                overflow: hidden;
            }
            .single-publication figure {
                position: relative;
                margin: 0;
                text-align: center;
            }
            .single-publication figure > a {
                background-color: #fafafa;
                display: block;
            }
            .single-publication figure ul {
                list-style-type: none;
                padding: 0;
                margin: 0;
                position: absolute;
                right: -50px;
                top: 20px;
                transition: .6s;
                -webkit-transition: .6s;
            }
            .single-publication:hover figure ul {
                right: 15px;
            }
            .single-publication figure ul li a {
                display: inline-block;
                width: 35px;
                height: 35px;
                text-align: center;
                font-size: 15px;
                background: #ff007d;
                margin-bottom: 7px;
                border-radius: 50%;
                line-height: 35px;
                color: #fff;
            }
            .single-publication figure ul li a:hover {
                color: #fff;
                background: #e50663;
            }
            .single-publication .publication-content {
                text-align: center;
                padding: 20px;
            }
            .single-publication .publication-content .category {
                display: inline-block;
                font-family: 'Open Sans', sans-serif;
                font-size: 14px;
                color: #ff007d;
                font-weight: 600;
            }
            .single-publication .publication-content h3 {
                font-weight: 600;
                margin: 8px 0 10px;
                font-size: 20px;
            }
            .single-publication .publication-content h3 a {
                color: #1f2d30;
            }
            .single-publication .publication-content h3 a:hover {
                color: #ff007d;
            }
            .single-publication .publication-content ul {
                list-style-type: none;
                padding: 0;
                margin: 0;
                margin-bottom: 15px;
            }
            .single-publication .publication-content ul li {
                display: inline-block;
                font-size: 18px;
                color: #fec42d;
            }
            .single-publication .publication-content .price {
                font-size: 18px;
                color: #ff007d;
            }
            .single-publication .publication-content .price span {
                color: #6f6f6f;
                text-decoration: line-through;
                padding-left: 5px;
                font-weight: 300;
            }
            .single-publication .add-to-cart {
                position: absolute;
                right: 0;
                bottom: 0;
                left: 0;
                background: #fff;
                opacity: 0;
                visibility: hidden;
                text-align: center;
                -webkit-transform: scale(.7);
                transform: scale(.7);
                height: 105px;
                -moz-transition: .4s;
                -webkit-transition: .4s;
                transition: .4s;
            }
            .single-publication:hover .add-to-cart {
                visibility: visible;
                transform: scale(1);
                -webkit-transform: scale(1);
                opacity: 1;
            }
            .single-publication .add-to-cart .default-btn {
                margin-top: 28px;
                padding: 8px 25px;
                font-size: 14px;
            }
            .single-publication .category {
                margin: 0;
            }
            .single-publication .add-to-cart .default-btn {
                margin-top: 28px;
                padding: 8px 25px;
                font-size: 14px;
            }
            .default-btn {
                background-color: #ff007d;
                color: #fff;
                border: 1px solid #ff007d;
                display: inline-block;
                padding: 10px 30px;
                border-radius: 30px;
                text-transform: uppercase;
                font-weight: 600;
                font-family: 'Open Sans', sans-serif;
            }
            .default-btn:hover {
                color: #fff;
                text-decoration: none;
            }
</style>  
</body>
</html>
<//html>

Related Post