App Engine Import Detection Inside App Engine

What I want to do is fix the existing Python module that uses urllib2 to run in App Engine, but I don't want to break it so that it can be used elsewhere. Therefore, I am looking for a quick test solution if the module is imported into the App Engine environment or not. Dexterity ImportError on urllib2 may not be the best solution.

+4
source share
2 answers

You can simply use sys.modules to check if a module has been imported (I use unicodedata as an example):

>>> import sys >>> 'unicodedata' in sys.modules False >>> import unicodedata >>> 'unicodedata' in sys.modules True 
+11
source

You can do a simple check against key environment variables. However, it is not known exactly how possible this is.

 import os, logging try: os.environ['APPENGINE_RUNTIME'] except KeyError: logging.warn('We are not in App Engine environment') else: logging.info('We are in the App Engine environment') 

You can also define your own environment variable in the App Engine configuration file and which will be displayed with os.environ in any module. So, enter something like this in the app.yaml file:

 env_variables: MY_APP_ENGINE_ENVIRONMENT: '982844ed9cbd6ce42318d2804386be29cbc7c35a' 

... will give you a unique identifier for the link.

From the development server, here are the environment variables that I get:

 {'USER_EMAIL': '', 'DATACENTER': 'us1', 'wsgi.version': (1, 0), 'REQUEST_ID_HASH': 'E2C19D51', 'SERVER_NAME': 'mydesktop', 'QUERY_STRING': '', 'HTTP_ACCEPT': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'APPENGINE_RUNTIME': 'python27', 'wsgi.input': <cStringIO.StringI object at 0x2f145d0>, 'SERVER_PROTOCOL': 'HTTP/1.1', 'HTTPS': 'off', 'USER_IS_ADMIN': '0', 'TZ': 'UTC', 'REMOTE_ADDR': '192.168.0.2', 'HTTP_X_APPENGINE_COUNTRY': 'ZZ', 'HTTP_USER_AGENT': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.110 Safari/537.36', 'SERVER_SOFTWARE': 'Development/2.0', 'HTTP_CACHE_CONTROL': 'max-age=0', 'DEFAULT_VERSION_HOSTNAME': 'mydesktop:8080', 'SERVER_PORT': '8080', 'wsgi.run_once': False, 'REQUEST_METHOD': 'GET', 'USER_ID': '', 'AUTH_DOMAIN': 'gmail.com', 'USER_NICKNAME': '', 'USER_ORGANIZATION': '', 'wsgi.multiprocess': True, 'INSTANCE_ID': '8a8e02e6efa8d195346ae0c90cfeafce8aa2', 'PATH_INFO': '/', 'HTTP_ACCEPT_LANGUAGE': 'en-US,en;q=0.8', 'HTTP_HOST': 'mydesktop:8080', 'wsgi.errors': <google.appengine.api.logservice.logservice.LogsBuffer object at 0x2f09c30>, 'APPLICATION_ID': 'dev~myapp', 'wsgi.multithread': True, 'CURRENT_VERSION_ID': 'version-1', 'SCRIPT_NAME': '', 'REQUEST_LOG_ID': '4eafbc91ca4ebd5fee53f19eeab2eb26d243d9ddc92b6b9bc0a063eabdc84cfff', 'wsgi.url_scheme': 'http'} 

Hope this helps.

0
source