crud-operations flask-tutorial web-application-development python-web-app postgresql-database sqlalchemy-orm flask-postgresql-integration web-development-with-flask deploy-flask-app flask-sqlalchemy
Tutorial: Build a Web Application with Flask and PostgreSQL
In this tutorial, you'll learn how to build a web application using the Flask framework and PostgreSQL as the database. We'll cover the entire process, from setting up your environment to deploying your application.
---
Prerequisites
- Python Installed: Ensure Python 3.x is installed on your system.
- Pip Package Manager: Ensure pip is installed for managing Python packages.
- PostgreSQL: Install PostgreSQL and set up a database for your application.
- Basic Python and SQL Knowledge: Familiarity with Python and SQL basics will be helpful.
Step 1: Set Up Your Development Environment
- Create a Virtual Environment: It's a good practice to use a virtual environment for your project to manage dependencies.
python -m venv venv
- Activate the Virtual Environment:
- Windows:
.\venv\Scripts\activate
- macOS/Linux:
source venv/bin/activate
- Install Required Packages: Install Flask, SQLAlchemy, and
psycopg2
for PostgreSQL integration.
pip install Flask SQLAlchemy psycopg2-binary
Step 2: Create a Basic Flask Application
- Create the Project Structure:
mkdir flask_app
cd flask_app
- Create the Flask Application: Create a file named
app.py
and add the following code.
from flask import Flask, render_template, request, redirect, url_for
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://username:password@localhost:5432/mydatabase'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), nullable=False)
email = db.Column(db.String(120), unique=True, nullable=False)
def __repr__(self):
return f'<User {self.username}>'
@app.route('/')
def index():
users = User.query.all()
return render_template('index.html', users=users)
@app.route('/add', methods=['POST'])
def add_user():
username = request.form['username']
email = request.form['email']
new_user = User(username=username, email=email)
db.session.add(new_user)
db.session.commit()
return redirect(url_for('index'))
if __name__ == '__main__':
app.run(debug=True)
- Create HTML Template: Create a directory named
templates
and add a file namedindex.html
with the following content:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Flask App</title>
</head>
<body>
<h1>User List</h1>
<ul>
{% for user in users %}
<li>{{ user.username }} - {{ user.email }}</li>
{% endfor %}
</ul>
<h2>Add User</h2>
<form action="{{ url_for('add_user') }}" method="post">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<button type="submit">Add User</button>
</form>
</body>
</html>
Step 3: Set Up PostgreSQL
- Create a Database: Log in to your PostgreSQL instance and create a new database.
CREATE DATABASE mydatabase;
- Create a Database User: Create a new user with privileges on the database.
CREATE USER myuser WITH PASSWORD 'mypassword';
GRANT ALL PRIVILEGES ON DATABASE mydatabase TO myuser;
- Update Database URI: In
app.py
, replace'username:password@localhost:5432/mydatabase'
with your actual database username, password, host, port, and database name.
Step 4: Initialize the Database
- Create the Database Tables: Run the following commands in a Python shell to create the database tables.
from app import db
db.create_all()
- Start the Flask Application: Run the application.
python app.py
- Access the Application: Open your web browser and go to
http://127.0.0.1:5000/
. You should see the user list and a form to add new users.
Step 5: Perform CRUD Operations
- Create: Add new users using the form on the homepage.
- Read: View the list of users on the homepage.
- Update and Delete: You can extend the application to include update and delete functionality by adding new routes and templates.
Step 6: Deploy the Application
- Choose a Hosting Platform: Select a platform such as Heroku, AWS, or Google Cloud to host your Flask application.
- Prepare for Deployment: Create a
Procfile
andrequirements.txt
to specify dependencies and deployment instructions.
- Procfile:
web: python app.py
- requirements.txt: List your dependencies.
Flask
SQLAlchemy
psycopg2-binary
gunicorn
- Deploy: Follow the hosting platform's instructions to deploy your application.
Conclusion
In this tutorial, you built a basic web application using Flask and PostgreSQL. You learned how to set up your environment, create and interact with a PostgreSQL database using SQLAlchemy, and perform basic CRUD operations. You also prepared your application for deployment on a hosting platform.
For further improvements, consider adding authentication, user input validation, and advanced database queries. You can also explore deploying your app with Docker for a more portable deployment solution.
Comments
Please log in to leave a comment.