2

I have a module that uses lxml. Since this cannot be imported on GAE, I'd like to use a suitable substitute by default. Something along the lines of:

if not ON_GAE:
    import lxml
else:
    import beautifulsoup

How can I determine that I'm on GAE? Is there a OS variable of some sorts?

Update: There are certain modules that will not run on GAE (like sockets). Rather than having multiple blocks of try ... except ImportError, I'd like to know from the start which code blocks needs an alternative implementation.

Sebastian
  • 1,055
  • 9
  • 27

2 Answers2

4

You can use this:

on_app_engine = os.environ.get('SERVER_SOFTWARE', '').startswith('Google')

Then something like:

if on_app_engine:
  import lxml
else:
  import bla
Andz
  • 2,228
  • 19
  • 13
  • This will fail on the development server, which returns a string starting with 'Development'. – Nick Johnson Jul 10 '11 at 03:28
  • This answer is related: http://stackoverflow.com/questions/1916579/in-python-how-can-i-test-if-im-in-google-app-engine-sdk/1916594#1916594 – Sebastian Jul 11 '11 at 09:03
2

You can simply try and see if an import throws an exception and use the other import only if it's necessary.

try:
    import lxml
except ImportError:
    import beautifulsoup
Tugrul Ates
  • 9,451
  • 2
  • 33
  • 59
  • That is an alternative. However, I'd prefer a solution where I knew from the start that some imports just won't work. – Sebastian Jul 09 '11 at 08:40
  • 1
    `try:`, `import lxml`, `catch`---WHAT!? – Chris Morgan Jul 09 '11 at 17:08
  • @basti Personally, I think this is preferable to relying on specific external factors such as the server environment. If App Engine adds support for some of the modules you need, you'll transparently start using them, and it makes your code available on a wider variety of restricted platforms. You could always write a function to make these tests easier, though. – Nick Johnson Jul 10 '11 at 03:29
  • @Nick Johnson: In general I agree with you. In this specific case, however, GAE does not allow you to use ``socket.settimeout(...)``. – Sebastian Jul 10 '11 at 18:38
  • @basti Perhaps you should ask a question about that, then - the one you posted is about lxml and imports. – Nick Johnson Jul 10 '11 at 23:35