Python course Β· Module 5: Flask and Web Apps

Deployment - publishing on the internet

7 min read Β·
In this lesson15

Congratulations! Darwin here with the last lesson of Module 5 - deploying a Flask application!

You've built a functioning Safari Database application with forms, authentication and templates. Now it's time to publish it on the internet so the world can use it!

Safari Analogy: Deployment is like opening the park to the public - until now the park only operated internally (localhost), now you're opening the gates for tourists from all over the world (internet)!

Development vs Production

Development (localhost)

app.run(debug=True) - development server Auto-reload after code changes Detailed errors in the browser Localhost only - not accessible from the internet Slow - not optimized

Production (internet)

WSGI server (Gunicorn, uWSGI) No debug=True - security! Environment variables - SECRET_KEY, DATABASE_URL Publicly accessible - anyone can visit Fast - optimized

NEVER use app.run(debug=True) in production!

WSGI Server - Gunicorn

Gunicorn (Green Unicorn) is a popular WSGI server for Flask/Django applications.

WSGI = Web Server Gateway Interface - a standard for communication between a server and a Python application.

Installation

pip install gunicorn

Running

# Basic
gunicorn app:app

# With port and workers specified
gunicorn app:app --bind 0.0.0.0:8000 --workers 4

# With reload (dev only)
gunicorn app:app --reload

Format: gunicorn <module>:<app_variable>

  • app - file name (app.py)
  • app - Flask variable name (app = Flask(name))

Preparing for deployment

1. requirements.txt file

Save all dependencies:

pip freeze > requirements.txt

requirements.txt:

Flask==3.0.0
Flask-WTF==1.2.1
Flask-Login==0.6.3
Werkzeug==3.0.1
gunicorn==21.2.0

2. Environment variables

NEVER commit SECRET_KEY and sensitive data to git!

Use environment variables:

# app.py
import os

app = Flask(__name__)

# Get from environment variables
app.config['SECRET_KEY'] = os.environ.get('SECRET_KEY') or 'dev-fallback-key'
app.config['DATABASE_URL'] = os.environ.get('DATABASE_URL') or 'sqlite:///dev.db'

# Debug only in dev
app.config['DEBUG'] = os.environ.get('FLASK_ENV') == 'development'

3. .gitignore

# .gitignore
venv/
__pycache__/
*.pyc
*.pyo
.env
instance/
.DS_Store

4. Procfile (for platforms like Render/Heroku)

web: gunicorn app:app

Procfile tells the platform how to run your application.

5. runtime.txt (optional)

python-3.11.0

Specifies the Python version.

Deployment on Render (FREE!)

Render is a modern hosting platform with a free plan. A great alternative to Heroku!

Step 1: Prepare the application

Project structure:

safari_web/
β”œβ”€β”€ app.py
β”œβ”€β”€ models.py
β”œβ”€β”€ forms.py
β”œβ”€β”€ requirements.txt
β”œβ”€β”€ Procfile
β”œβ”€β”€ .gitignore
β”œβ”€β”€ templates/
β”‚   └── ...
└── static/
    └── ...

app.py - last lines:

if __name__ == '__main__':
    # Only for local development
    app.run(debug=True)

Render will run via Procfile, so if __name__ won't execute!

Step 2: Push to GitHub

git init
git add .
git commit -m "Initial commit - Safari Database"
git branch -M main
git remote add origin https://github.com/your-username/safari-web.git
git push -u origin main

Step 3: Create Web Service on Render

  1. Go to https://render.com and register (FREE)

  2. Click "New +" β†’ "Web Service"

  3. Connect your GitHub repository

  4. Select the safari-web repository

  5. Configuration:

    • Name: safari-database
    • Environment: Python 3
    • Build Command: pip install -r requirements.txt
    • Start Command: gunicorn app:app
    • Plan: Free
  6. Environment Variables - add:

    • SECRET_KEY = your-random-secret-key-here
    • FLASK_ENV = production
  7. Click "Create Web Service"

Step 4: Deploy!

Render automatically:

  • Installs dependencies (pip install -r requirements.txt)
  • Runs Gunicorn (gunicorn app:app)
  • Assigns a domain (https://safari-database.onrender.com)

Congratulations! Your application is LIVE!

Deployment on Railway (also FREE!)

Railway is another great platform with a simple setup.

Steps:

  1. https://railway.app - register
  2. "New Project" β†’ "Deploy from GitHub repo"
  3. Select the repository
  4. Railway automatically detects Flask!
  5. Add Environment Variables:
    • SECRET_KEY
    • FLASK_ENV=production
  6. Railway automatically deploys!

Domain: https://safari-database.up.railway.app

Deployment checklist

Before deployment make sure:

Security

  • DEBUG = False in production
  • SECRET_KEY as environment variable
  • Passwords hashed (werkzeug.security)
  • CSRF protection enabled (Flask-WTF)
  • .gitignore contains venv/, .env

Files

  • requirements.txt is up to date
  • Procfile created
  • .gitignore created
  • Static files properly configured

Database

  • In dev: SQLite
  • In prod: PostgreSQL (Render/Railway FREE tier!)
  • DATABASE_URL as environment variable

Testing

  • Application works locally
  • All routes work
  • Forms work
  • Login/registration works

Database in production

SQLite (Development)

app.config['DATABASE_URL'] = 'sqlite:///safari.db'

Problems: SQLite is not recommended for production (concurrency issues).

PostgreSQL (Production)

Render/Railway offer FREE PostgreSQL!

Render: Add PostgreSQL Database β†’ copy DATABASE_URL

import os

database_url = os.environ.get('DATABASE_URL')

if database_url and database_url.startswith('postgres://'):
    # Render uses postgres://, but SQLAlchemy needs postgresql://
    database_url = database_url.replace('postgres://', 'postgresql://', 1)

app.config['SQLALCHEMY_DATABASE_URI'] = database_url or 'sqlite:///dev.db'

Static files in production

Flask automatically serves files from static/, but in production it's better to use a CDN or Nginx.

Basic Flask configuration:

# app.py
app = Flask(__name__)

# Flask automatically serves static files from /static/
# http://yourapp.com/static/css/style.css

In templates:

<link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
<script src="{{ url_for('static', filename='js/script.js') }}"></script>

Monitoring and logs

Render Logs

Dashboard β†’ Your Web Service β†’ Logs

Railway Logs

Project β†’ Your Service β†’ Logs

Example logs:

[2024-01-15 10:23:45] INFO: Starting gunicorn 21.2.0
[2024-01-15 10:23:45] INFO: Listening at: http://0.0.0.0:10000
[2024-01-15 10:23:45] INFO: Using worker: sync
[2024-01-15 10:23:45] INFO: Booting worker with pid: 42

Updating the application

Render/Railway

  1. Make code changes locally
  2. Commit to git:
    git add .
    git commit -m "Update: Add new feature"
    git push origin main
  3. Render/Railway automatically deploys the new version!

Auto-deploy = push to GitHub β†’ automatic deploy!

Custom domain (optional)

Instead of safari-database.onrender.com you can use your own domain:

  1. Buy a domain (e.g. safaridatabase.com)
  2. Render/Railway β†’ Settings β†’ Custom Domain
  3. Add a CNAME record at your domain registrar
  4. Done! https://safaridatabase.com β†’ Your application

Alternative platforms

1. Fly.io

  • FREE tier
  • Global deployment
  • Great documentation

2. PythonAnywhere

  • FREE tier for Flask
  • Simple setup
  • Good for beginners

3. DigitalOcean App Platform

  • $5/month
  • More control
  • Scalable

4. AWS/Google Cloud/Azure

  • Advanced
  • More expensive
  • Full control

Example production-ready app.py

# app.py
import os
from flask import Flask, render_template, redirect, url_for, flash
from flask_login import LoginManager, login_user, logout_user, login_required, current_user
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)

# Configuration from environment variables
app.config['SECRET_KEY'] = os.environ.get('SECRET_KEY') or 'dev-key-change-in-production'
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('DATABASE_URL') or 'sqlite:///dev.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

# Fix for Render PostgreSQL URL
if app.config['SQLALCHEMY_DATABASE_URI'].startswith('postgres://'):
    app.config['SQLALCHEMY_DATABASE_URI'] = app.config['SQLALCHEMY_DATABASE_URI'].replace('postgres://', 'postgresql://', 1)

db = SQLAlchemy(app)
login_manager = LoginManager(app)
login_manager.login_view = 'login'

# Models, routes, etc...

if __name__ == '__main__':
    # Only for local development
    port = int(os.environ.get('PORT', 5000))
    app.run(host='0.0.0.0', port=port, debug=os.environ.get('FLASK_ENV') == 'development')

Summary

In this lesson you learned:

  • Difference between development and production
  • WSGI servers (Gunicorn)
  • Preparing applications for deployment
  • Environment variables (SECRET_KEY, DATABASE_URL)
  • Deployment on Render (FREE!)
  • Deployment on Railway (FREE!)
  • Deployment checklist
  • Databases in production (PostgreSQL)
  • Static files in production
  • Monitoring and logs
  • Updating applications (auto-deploy)

Final Safari Analogy: Deployment is like the grand opening of a safari park - you prepared the infrastructure (code), hired staff (WSGI server), secured the park (SECRET_KEY, HTTPS), and opened the gates for tourists from all over the world (internet)! Your Flask application lives and runs 24/7 in the cloud!

Congratulations on Module 5!

You've built a complete web application with:

  • Frontend (HTML, CSS, JavaScript)
  • Backend (Flask)
  • Routing and view functions
  • Jinja2 templates
  • Forms with validation (Flask-WTF)
  • Authentication (Flask-Login)
  • Deployment on the internet (Render/Railway)

Safari Database is now LIVE and accessible to everyone on the internet!

Darwin is proud of you! Get ready for the next modules, where you'll learn advanced Python and AI techniques!

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. What is web application deployment?

  2. 2. What is Gunicorn?

These are 2 of 3 questions for this lesson. Solve the rest in the game.

Hands-on tasks in the game

  • Vertical ordering

    Arrange the typical steps for deploying a Flask application:

  • Click in order

    Arrange the command that generates requirements.txt:

  • Code editor

    Write a Config class with SECRET_KEY retrieved from an environment variable.

  • Horizontal ordering

    Arrange the elements of a route decorator:

  • Vertical ordering

    Arrange the steps for creating a Flask application:

  • Code editor

    Write a '/api/species' route that returns a list of species as JSON.

  • Code editor

    Create a '/' route in Flask that returns 'Welcome to Safari!'.

  • Code editor

    Render the 'index.html' template passing a title variable.

  • Vertical ordering

    Arrange the stages of handling an HTTP request:

  • Code editor

    Define a LoginForm class with username and password fields.

  • Code editor

    Build a Safari Species Portal application with: a species list, adding new ones, user login, and basic CSS styling.

  1. QuestionWhat is deployment?
  2. QuestionGunicorn
  3. Questionrequirements.txt
  4. Put in orderDeployment steps
  5. Click in orderGenerating requirements
  6. Coding taskProduction configuration
  7. Put in orderFlask route decorator
  8. Put in orderCreating a Flask application
  9. Coding taskJSON endpoint in Flask
  10. Coding taskBasic Flask route
  11. Coding taskJinja2 template with data
  12. Put in orderHandling an HTTP request in Flask
  13. Coding taskLogin form
  14. Coding taskProject: Safari Species Portal
  15. Project to submitSubmit your project to a mentor
  16. VideoModule summary

Useful articles