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
#app.py from flask import Flask, render_template, request from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) #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('/') def index(): return render_template('index.html') @app.route('/submit', methods=['POST']) def submit(): fname= request.form['fname'] lname=request.form['lname'] email=request.form['email'] student=Student(fname,lname,email) db.session.add(student) db.session.commit() #fetch a certain student studentResult=db.session.query(Student).filter(Student.id==1) for result in studentResult: print(result.fname) return render_template('success.html', data=fname) if __name__ == "__main__": app.run(debug=True)templates/index.html
//templates/index.html <!doctype html> <html> <head> <title>Python Flask PostgreSQL simple registration</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" /> </head> <body > <div class="container" > <div class="row" style="padding:50px;"> <p><h1>Python Flask PostgreSQL simple registration</h1></p> <form action="/submit" method="POST"> <div class="mb-3"> <label class="form-label">First name:</label> <input type="text" id="fname" name="fname" class="form-control"> </div> <div class="mb-3"> <label class="form-label">Last name:</label> <input type="text" id="lname" name="lname" class="form-control"> </div> <div class="mb-3"> <label class="form-label">Email:</label> <input type="text" id="email" name="email" class="form-control"> </div> <br/><br/> <button type="submit" class="btn btn-primary">Submit</button> </form> </div> </div> </body> </html>templates/success.html
//templates/success.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> Your data has been added successfully. Hello {{data}}! </body> </html>