What are environment variables and secrets?
Environment variables are values supplied to a process from its environment rather than being hard-coded in source files. They are useful for configuration such as an application mode, a service URL, or a feature flag. Secrets are sensitive configuration values — for example, API tokens and database passwords — and should be handled with stricter access controls.
Gradio applications are ordinary Python processes: read configuration with os.environ or os.getenv(), validate required values at startup, and pass only the necessary configuration to the functions that need it.
1. Environment variable basics
Use os.getenv() to read a variable. Supply a default for optional settings and validate required settings explicitly.
import os
APP_ENV = os.getenv("APP_ENV", "development")
LOG_LEVEL = os.getenv("LOG_LEVEL", "INFO")
API_BASE_URL = os.getenv("API_BASE_URL", "https://api.example.com")
print("Environment:", APP_ENV)
print("Log level:", LOG_LEVEL)Live example: read a configuration value
2. Set variables before launching Gradio
Set variables in the shell or deployment environment. The Python process inherits them when it starts.
macOS / Linux
export APP_ENV=production
export LOG_LEVEL=INFO
python app.pyWindows PowerShell
$env:APP_ENV = "production"
$env:LOG_LEVEL = "INFO"
python app.pyimport os
import gradio as gr
environment = os.getenv("APP_ENV", "development")
def greet(name):
return f"Hello, {name}! Running in {environment} mode."
demo = gr.Interface(
fn=greet,
inputs=gr.Textbox(label="Your name"),
outputs=gr.Textbox(label="Greeting"),
title="Environment-aware Gradio app"
)
if __name__ == "__main__":
demo.launch()3. Use a .env file for local development
A .env file is a convenient local-development option. The python-dotenv package loads its entries into the process environment.
APP_ENV=development
APP_TITLE=Knowledge Assistant
API_TOKEN=replace-with-your-local-tokenpip install python-dotenv gradioimport os
import gradio as gr
from dotenv import load_dotenv
load_dotenv() # Loads .env for local development
app_title = os.getenv("APP_TITLE", "My Gradio App")
app_env = os.getenv("APP_ENV", "development")
def status():
return f"{app_title} is running in {app_env} mode."
demo = gr.Interface(fn=status, inputs=None, outputs="text", title=app_title)
demo.launch().env to .gitignore. Do not commit it. Use your hosting platform's secret manager for deployed applications.Live example: .env parser (illustrative)
4. Keep API keys secret
Read a key on the server side and use it inside the function that calls the external service. Do not return the key from a Gradio callback or place it in a component's value.
import os
import gradio as gr
API_KEY = os.getenv("MY_SERVICE_API_KEY")
if not API_KEY:
raise RuntimeError("MY_SERVICE_API_KEY is not configured")
def call_service(prompt):
# Use API_KEY in a server-side SDK/client request.
# Never return or print the key.
return f"Request prepared for: {prompt}"
demo = gr.Interface(
fn=call_service,
inputs=gr.Textbox(label="Prompt"),
outputs=gr.Textbox(label="Status")
)
demo.launch()MY_SERVICE_API_KEY in your hosting provider's secret/environment settings. Limit who can view or edit it, rotate it if exposed, and avoid logging request headers.Live example: secret safety check
5. Validate required configuration at startup
Fail early with a clear message if a required setting is missing. Avoid printing the secret itself.
import os
def required_env(name: str) -> str:
value = os.getenv(name)
if not value:
raise RuntimeError(f"Missing required environment variable: {name}")
return value
# Validate at application startup
service_key = required_env("MY_SERVICE_API_KEY")
database_url = required_env("DATABASE_URL")
print("Required configuration is present.")Live example: configuration validator
6. Gradio app with environment-based settings
This example changes the title and greeting based on server-side configuration while keeping sensitive values out of the interface.
import os
import gradio as gr
APP_TITLE = os.getenv("APP_TITLE", "Environment Demo")
APP_ENV = os.getenv("APP_ENV", "development")
def respond(message):
if not message.strip():
return "Please enter a message."
return f"[{APP_ENV}] You said: {message}"
with gr.Blocks(title=APP_TITLE) as demo:
gr.Markdown(f"# {APP_TITLE}")
gr.Markdown("Configuration is loaded on the server.")
chat_input = gr.Textbox(label="Message", placeholder="Type something...")
output = gr.Textbox(label="Response")
submit = gr.Button("Submit")
submit.click(respond, inputs=chat_input, outputs=output)
if __name__ == "__main__":
demo.launch()7. Real-world configuration workflow
APP_ENV, API_BASE_URL, and MY_SERVICE_API_KEY.| Setting | Example | Secret? | Recommended handling |
|---|---|---|---|
APP_ENV | production | No | Environment variable with a safe default where appropriate |
APP_TITLE | Support Assistant | No | Environment variable or app configuration |
API_BASE_URL | https://api.example.com | Usually no | Environment variable; validate trusted destinations |
MY_SERVICE_API_KEY | •••••••• | Yes | Deployment secret manager; never commit or display |
DATABASE_URL | •••••••• | Often yes | Secret manager; restrict access and redact logs |
8. Common mistakes and fixes
Variable is None
Check the exact variable name, whether it was exported, and whether the process was restarted after changing it.
.env is not loading
Install python-dotenv, call load_dotenv(), and check the working directory or explicit .env path.
Secret appears in logs
Remove debug prints, redact headers and configuration dumps, rotate the exposed credential, and review access logs.
Works locally, fails in deployment
Set the variable in the deployment environment/secret settings. A local .env file is not automatically deployed.
9. Quick knowledge check
Which is the safest place for a production API token?
10. Useful references
- Gradio documentation
- Gradio Quickstart
- Python os.getenv documentation
- python-dotenv package
- The Twelve-Factor App: Config
Examples are educational templates. Adapt validation, permissions, and secret storage to your deployment platform and security requirements.