How to add data from Flask to PostgreSQL in Windows 2
By: Dul S Blog
Tags: Postgres, Flask, Python, HTML, Flask Sqlalchemy

The code in the IDE , my IDE is sublime text. Here the difference from the first tutorial in sending data is that here I m not defining the data in flask app and sending to PostgreSQL but simply the user gets to enter data from the form and that data gets send to the PostgreSQL db.

app.py

from flask import Flask, render_template, request

from models import db, User app = Flask(__name__) POSTGRES = {

'user': 'postgres',

'pw': 'silverTip',

'db': 'flaskmovie',

'host': 'localhost',

'port': '5432',

}

app.config['DEBUG'] = True

app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://%(user)s:\

%(pw)s@%(host)s:%(port)s/%(db)s' % POSTGRES

db.init_app(app)

def index():

return render_template('addU.html') @app .route('/')def index():return render_template('addU.html')

def postU():



if request.form:

user = User(id=request.form.get("id"), username=request.form.get("username"),email=request.form.get("email"))



db.session.add(user)

db.session.commit()

return render_template('addU.html') @app .route('/postU', methods=['POST', 'GET'])def postU():if request.form:user = User(id=request.form.get("id"), username=request.form.get("username"),email=request.form.get("email"))db.session.add(user)db.session.commit()return render_template('addU.html') if __name__ == '__main__':

app.run()

models.py

from flask_sqlalchemy import SQLAlchemy

import datetime db = SQLAlchemy() class BaseModel(db.Model):

"""Base data model for all objects"""

__abstract__ = True

def __init__(self, *args):

super().__init__(*args)

def __repr__(self):

"""Define a base way to print models"""

return '%s(%s)' % (self.__class__.__name__, {

column: value

for column, value in self._to_dict().items()

})

def json(self):

"""

Define a base way to jsonify models, dealing with datetime objects

"""

return {

column: value if not isinstance(value, datetime.date) else value.strftime('%Y-%m-%d')

for column, value in self._to_dict().items()

} class User(db.Model):

__tablename__ = 'user'

id = db.Column(db.Integer, primary_key=True)

username = db.Column(db.String(80), unique=True)

email = db.Column(db.String(80), unique=True) def __init__(self,id, username, email):

self.id = id

self.username = username

self.email = email

manage.py

from flask_script import Manager

from flask_migrate import Migrate, MigrateCommand

from app import app, db

migrate = Migrate(app, db)

manager = Manager(app)

manager.add_command('db', MigrateCommand)

if __name__ == '__main__':

manager.run()

addU.html

<!DOCTYPE html>

<html>

<head>

<title></title>

</head> <body>

<form method="post" action="/postU">

<label>id:</label>

<input id="id" type="text" name="id">

<label>Username:</label>

<input type="text" name="username">

<label>Email:</label>

<input type="text" name="email">

<input type="submit" />

</form> </body>

</html>

File structure of ada folder of mine

addU.html is inside templates folder

Now in command prompt, create the virtual env and do the following.

>py -m venv env

>env\Scripts\activate

>pip install flask

>pip install Flask-Migrate

>pip install Flask-Scripts

>pip install psycopg2

>python manage.py db init

>python manage.py db migrate

>python manage.py db upgrade

>pip install Flask-SQLAlchemy

>set FLASK_APP=app.py

Remember my main file is app.py, if you named it something else give that name instead of app.py, but its the normal convection and good practise to give the main file the name app.py.

>flask run

Thank you