Python Web App Using Flask

Written by

in

Looking to turn your Python skills into a dynamic web application? Flask, the lightweight yet powerful micro‑framework, makes it easy to build scalable, production‑ready sites without the overhead of heavyweight frameworks. In this guide we’ll walk you through the essential steps of creating a Python web app using Flask, from setting up the development environment to deploying a fully functional project. Whether you’re a beginner eager to launch your first site or an experienced developer seeking a quick prototype, this tutorial covers everything you need to know.

Why Choose Flask for Your Python Web App?

Flask has become a favorite among developers for several compelling reasons:

  • Minimalistic core: Flask provides only the essentials, allowing you to add extensions only when you need them.
  • Flexibility: You can structure your project any way you like, making it ideal for both small scripts and large applications.
  • Extensive ecosystem: A rich collection of extensions (e.g., Flask‑SQLAlchemy, Flask‑Login, Flask‑RESTful) simplifies common tasks.
  • Excellent documentation: Clear, example‑driven docs help you get up and running quickly.

Setting Up Your Development Environment

1. Install Python and Virtualenv

First, ensure you have Python 3.8+ installed. Then create an isolated environment to keep dependencies tidy:

python3 -m venv venv
source venv/bin/activate   # On Windows use: venv\Scripts\activate

2. Install Flask and Essential Extensions

With the virtual environment active, install Flask and a few common extensions:

pip install Flask Flask‑SQLAlchemy Flask‑Migrate Flask‑Login

3. Verify the Installation

Run a quick sanity check to confirm Flask is available:

python -c "import flask; print(flask.__version__)"

Creating Your First Flask Application

Project Structure

A clean layout helps maintainability. Here’s a recommended structure for a simple app:

my_flask_app/
│
├── app/
│   ├── __init__.py
│   ├── routes.py
│   ├── models.py
│   └── templates/
│       └── index.html
│
├── migrations/
│
├── venv/
│
├── config.py
└── run.py

Initializing the App (app/__init__.py)

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_login import LoginManager

db = SQLAlchemy()
migrate = Migrate()
login_manager = LoginManager()

def create_app():
    app = Flask(__name__)
    app.config.from_object('config.Config')

    db.init_app(app)
    migrate.init_app(app, db)
    login_manager.init_app(app)

    from . import routes
    app.register_blueprint(routes.main)

    return app

Defining a Simple Route (app/routes.py)

from flask import Blueprint, render_template

main = Blueprint('main', __name__)

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

Creating a Template (app/templates/index.html)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Flask Starter App</title>
</head>
<body>
    <h1>Welcome to Your Flask Web App!</h1>
    <p>This page is rendered using Flask's template engine.</p>
</body>
</html>

Running the Application (run.py)

from app import create_app

app = create_app()

if __name__ == '__main__':
    app.run(debug=True)

Start the server with python run.py and visit http://127.0.0.1:5000 to see your first Flask page.

Adding Core Features to Your Flask Web App

Database Integration with Flask‑SQLAlchemy

Define your data models in app/models.py:

from . import db
from flask_login import UserMixin

class User(db.Model, UserMixin):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(150), unique=True, nullable=False)
    email = db.Column(db.String(150), unique=True, nullable=False)
    password_hash = db.Column(db.String(128), nullable=False)

    def __repr__(self):
        return f'<User {self.username}>'

Initialize the database with Flask‑Migrate:

flask db init
flask db migrate -m "Initial migration."
flask db upgrade

User Authentication with Flask‑Login

Set up login management in app/__init__.py (already imported). Then add routes for login and logout:

from flask import Blueprint, render_template, redirect, url_for, flash, request
from flask_login import login_user, logout_user, login_required, current_user
from .models import User
from . import db, login_manager

@login_manager.user_loader
def load_user(user_id):
    return User.query.get(int(user_id))

auth = Blueprint('auth', __name__)

@auth.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        user = User.query.filter_by(username=request.form['username']).first()
        if user and user.check_password(request.form['password']):
            login_user(user)
            return redirect(url_for('main.index'))
        flash('Invalid credentials')
    return render_template('login.html')
    
@auth.route('/logout')
@login_required
def logout():
    logout_user()
    return redirect(url_for('main.index'))

Building a RESTful API with Flask‑RESTful

For modern front‑end frameworks, expose JSON endpoints:

from flask_restful import Resource, Api
from .models import User

api_bp = Blueprint('api', __name__)
api = Api(api_bp)

class UserList(Resource):
    def get(self):
        users = User.query.all()
        return [{'id': u.id, 'username': u.username} for u in users], 200

api.add_resource(UserList, '/api/users')

Best Practices for a Production‑Ready Flask App

  • Configuration Management: Store secrets (e.g., SECRET_KEY) in environment variables or a .env file using python‑dotenv.
  • Application Factory Pattern: Use the create_app function (as shown) to enable testing and multiple instances.
  • Error Handling: Implement custom error pages for 404, 500, etc., to improve user experience.
  • Logging: Configure logging to capture stack traces and request details.
  • Static Files: Serve CSS/JS via Flask‑Static‑Compress or a dedicated CDN for faster load times.
  • Testing: Write unit tests with pytest and use Flask’s test client to simulate requests.

Deploying Your Flask Application

Choosing a Hosting Platform

Popular options include:

  1. Heroku: Simple Git‑based deployment with a free tier.
  2. Render.com: Offers automatic HTTPS and background workers.
  3. AWS Elastic Beanstalk: Scalable, but requires more configuration.
  4. Docker + Kubernetes: Ideal for micro‑service architectures.

Deploying to Heroku – Step by Step

  1. Create a Procfile in the project root:
    web: gunicorn run:app
    
  2. Add gunicorn to your dependencies:
    pip install gunicorn
    pip freeze > requirements.txt
    
  3. Initialize a Git repository, commit your code, then push to Heroku:
    heroku create my-flask-app
    git push heroku main
    
  4. Set environment variables on Heroku:
    heroku config:set SECRET_KEY='your-secret-key'
    heroku config:set FLASK_ENV=production
    
  5. Run database migrations:
    heroku run flask db upgrade
    

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *