🐍 Python Tutorial: Deployment and Distribution
Deploying and distributing your Python application means making it available to others to run or install. This includes creating packages, uploading to PyPI, containerizing with Docker, and deploying to the cloud.
1. Packaging Your Code
Python uses the setuptools package to create installable packages.
# setup.py
from setuptools import setup, find_packages
setup(
name="myapp",
version="0.1",
packages=find_packages(),
install_requires=["requests"]
)Then build the package with:
python setup.py sdist bdist_wheel2. Uploading to PyPI
Use twine to securely upload your package to the Python Package Index:
pip install twine
twine upload dist/*3. Creating Executables
You can create standalone executables using pyinstaller:
pip install pyinstaller
pyinstaller my_script.pyThis will create a dist/ folder containing the executable.
4. Docker for Distribution
Use Docker to containerize your application, making it easy to deploy anywhere.
# Dockerfile
FROM python:3.11
WORKDIR /app
COPY . .
RUN pip install -r requirements.txt
CMD ["python", "app.py"]Then build and run your image:
docker build -t myapp .
docker run -p 5000:5000 myapp5. Cloud Deployment
Common platforms for Python app deployment:
- Heroku: Easy deployment from Git, integrates with Flask and Django
- Render: Simpler alternative to Heroku
- AWS: For scalable apps using EC2, Lambda, or Elastic Beanstalk
- Google Cloud: Includes App Engine for Python apps