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
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>
