Python: Preparing Python and Flask for production deployment

This documentation is part of the Creating a REST API guide. You can view the complete guide here: Step-by-step guide to building a REST API with Flask in Python.

👋 Welcome to the Stackhero documentation!

Stackhero offers a ready-to-use Python cloud solution designed to simplify your deployments:

  • Deploy your application to production in just seconds with a simple git push.
  • Use your own domain name, with automatic HTTPS certificate setup for secure connections managed for you.
  • Take advantage of automatic backups, one-click updates, and predictable pricing, so you can focus on your code instead of infrastructure management.
  • Benefit from high performance and security on a private, dedicated infrastructure. Your environment is isolated and protected.

Save time and streamline your workflow: your code can be up and running with Stackhero's Python cloud hosting in just 5 minutes.

Flask's built-in server is ideal for development. In production, you should use a robust WSGI server such as Gunicorn. Here is how to prepare:

  1. Install Gunicorn:

    pip install gunicorn
    pip freeze > requirements.txt
    
  2. Start your application with Gunicorn:

    ENV=production gunicorn app:app \
      --error-logfile - \
      -b 0.0.0.0:8080
    

    Here, app:app refers to your file (app.py) and the Flask application instance (app).

  3. You can add a Makefile to easily switch between development and production modes:

    .DEFAULT_GOAL := dev
    
    # Stackhero for Python runs the "run" rule by default. We override it to run 'prod'.
    run: prod
    
    prod:
    	ENV=production gunicorn app:app \
    	  --error-logfile - \
    	  -b 0.0.0.0:8080
    
    dev:
    	python app.py
    

You can start the server in development mode with make dev (or just make), or in production mode with make prod.