31. Deploying Python Applications
Why Deployment Matters
Writing Python code is only half the battle. Deployment is how your application reaches users or production environments. Proper deployment ensures your app runs reliably and efficiently.
Preparing Your Application
Before deploying, organize your code into modules and packages, include a `requirements.txt` for dependencies, and ensure your code is tested and optimized.
# Generate requirements file
pip freeze > requirements.txtUsing Virtual Environments
Virtual environments isolate your project dependencies from the system Python installation, ensuring consistent deployments.
# Create a virtual environment
python -m venv env
# Activate (Windows)
env\Scripts\activate
# Activate (macOS/Linux)
source env/bin/activate
# Install dependencies
pip install -r requirements.txtDeploying to a Local Server
For small projects or testing, you can deploy to a local server using Flask or Django's built-in servers.
# Flask example
export FLASK_APP=app.py
flask run
# Django example
python manage.py runserverDeploying to Cloud Platforms
Popular cloud platforms for Python include Heroku, AWS Elastic Beanstalk, Google Cloud, and Azure. They handle scaling, security, and server management for you.
# Example: Deploying to Heroku
heroku login
heroku create myapp
git push heroku main
heroku openContainerized Deployment with Docker
Docker allows you to package your Python application along with its environment, ensuring it runs consistently across any machine.
# Dockerfile example
FROM python:3.11
WORKDIR /app
COPY . /app
RUN pip install -r requirements.txt
CMD ["python", "app.py"]
# Build and run
Docker build -t myapp .
Docker run -p 5000:5000 myappBest Practices for Deployment
- Keep secrets and API keys out of code; use environment variables.
- Use virtual environments to manage dependencies.
- Test your app in a staging environment before production.
- Monitor logs and performance after deployment.
- Document deployment steps for future reference.
Mini Project Step
Deploy your `Calculator` or any small project to a cloud platform or Docker container. Make sure it runs correctly, dependencies are installed, and you can access it from a browser or API client.