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

2020-01-25 06:45发布

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?

4条回答
▲ chillily
2楼-- · 2020-01-25 07:14

I just check the httplib (which is a wrapper around appengine fetch)

def _is_gae():
   import httplib
   return 'appengine' in str(httplib.HTTP)
查看更多
一夜七次
3楼-- · 2020-01-25 07:27

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".

查看更多
Explosion°爆炸
4楼-- · 2020-01-25 07:32

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".

查看更多
欢心
5楼-- · 2020-01-25 07:32

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
查看更多
登录 后发表回答