Python: Preparing Python and Flask for production deployment

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

👋 Welcome to the Stackhero documentation!

Stackhero provides a ready-to-use Python cloud solution designed to streamline your deployment process:

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

Save time and simplify your workflow: you can have your code running with Stackhero's Python cloud hosting in just 5 minutes.

Flask's built-in server is great for development. For production, you will want a robust WSGI server such as Gunicorn. Here is how you can prepare:

  1. Install Gunicorn:

    pip install gunicorn
    pip freeze > requirements.txt
    
  2. Start your app 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 switch between development and production modes easily:

    .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.