In Python, how can I test if I'm in Google App Engine SDK?

Viewed 9167

Whilst developing I want to handle some things slight differently than I will when I eventually upload to the Google servers.

Is there a quick test that I can do to find out if I'm in the SDK or live?

7 Answers

Based on the same trick, I use this function in my code:

def isLocal():
    return os.environ["SERVER_NAME"] in ("localhost", "www.lexample.com")

I have customized my /etc/hosts file in order to be able to access the local version by prepending a "l" to my domain name, that way it is really easy to pass from local to production.

Example:

  • production url is www.example.com
  • development url is www.lexample.com

In app.yaml, you can add IS_APP_ENGINE environment variable

env_variables:
  IS_APP_ENGINE: 1

and in your Python code check if it has been set

if os.environ.get("IS_APP_ENGINE"):
    print("The app is being run in App Engine")
else:
    print("The app is being run locally")

The current suggestion from Google Cloud documentation is:

if os.getenv('GAE_ENV', '').startswith('standard'):
  # Production in the standard environment
else:
  # Local execution.

Update on October 2020:
I tried using os.environ["SERVER_SOFTWARE"] and os.environ["APPENGINE_RUNTIME"] but both didn't work so I just logged all keys from the results from os.environ. In these keys, there was GAE_RUNTIME which I used to check if I was in the local environment or cloud environment.
The exact key might change or you could add your own in app.yaml but the point is, log os.environ, perhaps by adding to a list in a test webpage, and use its results to check your environment.

Related