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
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.
A more general solution
A more general solution, which does not imply to be on a Google server, detects if the code is running on your local machine.
I am using the code below regardless the hosting server:
import socket
if socket.gethostname() == "your local computer name":
DEBUG = True
ALLOWED_HOSTS = ["127.0.0.1", "localhost", ]
...
else:
DEBUG = False
ALLOWED_HOSTS = [".your_site.com",]
...
If you use macOS you could write a more generic code:
if socket.gethostname().endswith(".local"): # True in your local computer
...
Django developers must put this sample code in the file settings.py
of the project.
EDIT:
According to Jeff O'Neill in macOS High Sierra socket.gethostname()
returns a string ending in ".lan".
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:
www.example.com
www.lexample.com
I just check the httplib (which is a wrapper around appengine fetch)
def _is_gae():
import httplib
return 'appengine' in str(httplib.HTTP)
See: https://cloud.google.com/appengine/docs/python/how-requests-are-handled#Python_The_environment
The following environment variables are part of the CGI standard, with special behavior in App Engine:
SERVER_SOFTWARE
:In the development web server, this value is "
Development/X.Y
" where "X.Y
" is the version of the runtime.When running on App Engine, this value is "
Google App Engine/X.Y.Z
".
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")