How to Deploy Staging Then Production in Python
Walk through a staged deployment mock that promotes from staging to production in sequence with Python.
Python code
17 linesimport time
def deploy_environment(name: str) -> None:
print(f"Deploying to {name}...")
time.sleep(0.1)
print(f"Deployed to {name} ✔")
def deploy_staging_then_prod() -> None:
environments = ["staging", "production"]
for env in environments:
deploy_environment(env)
if env == "staging":
print("Staging passed smoke tests, promoting to prod...")
print("All environments deployed successfully.")
if __name__ == "__main__":
deploy_staging_then_prod()
Output
Deploying to staging...
Deployed to staging ✔
Staging passed smoke tests, promoting to prod...
Deploying to production...
Deployed to production ✔
All environments deployed successfully.
How it works
The deploy_staging_then_prod function iterates over a list of environment names, calling deploy_environment for each. A conditional checks whether the current environment is staging and prints a promotion message after staging completes. This sequential loop guarantees staging is fully deployed before production begins, mimicking a safe roll-forward strategy. The time.sleep(0.1) simulates the duration of a real deployment so you can observe the ordering in action.
Common mistakes
- Forgetting to promote only after staging passes — adding the conditional catches that.
- Hardcoding environment lists instead of passing them as parameters or reading from config.
- Assuming `time.sleep` is needed in production — it's only a mock; real deploys use API calls.
- Placing production before staging in the list, which breaks the safe order.
Variations
- Use a `for env in ("staging", "production")` tuple instead of a list for immutability.
- Replace `print` statements with actual deployment SDK calls, e.g., `heroku.deploy(env)`.
Real-world use cases
- Automating a CI/CD pipeline that promotes a build to staging for testing before prod.
- Rolling out a feature flag or migration to a canary environment before general production.
- Wrapping blue-green deployment logic where staging serves as the pre-switch validation step.
Sponsored
More from Production deployment patterns
- Auto Rollback on Error Rate Exceeded in Python medium
- Automate Semantic Versioning with Conventional Commits in Python medium
- Design a Data Helper for Beginners in Python easy
- Docker healthcheck CMD mock in Python easy
- Generate a Mock Artifact Version Tag in Python easy
- Generate a docker-compose.yml with mock services in Python easy
Keep learning
Related tutorials and quizzes for this topic.