views:

63

answers:

2

How can I get the base URI in a Google AppEngine app written in Python? I'm using the webapp framework.

e.g.

http://example.appspot.com/
+3  A: 

The proper way to parse self.request.url is not with a regular expression, but with Python standard library's urlparse module:

import urlparse

...

o = urlparse.urlparse(self.request.url)

Object o will be an instance of the ParseResult class with string-valued fields such as o.scheme (probably http;-) and o.netloc ('example.appspot.com' in your case). You can put some of the strings back together again with the urlparse.urlunparse function from the same module, e.g.

s = urlparse.urlunparse((o.scheme, o.netloc, '', '', '', ''))

which would give you in s the string 'http://example.appspot.com' in this case.

Alex Martelli
Or you could just use, eg, self.request.host_url, self.request.host, etc, which already have these parts split out for you!
Nick Johnson
+3  A: 

If you just want to find your app ID, you can get that from the environment without having to parse the current URL. The environment variable is APPLICATION_ID

You can also use this to find the current version (CURRENT_VERSION_ID), auth domain (which will let you know whether you're running on appspot.com, AUTH_DOMAIN) and whether you're running on the local development server or in production (SERVER_SOFTWARE).

So to get the full base URL, try something like this:

import os

def get_base_url():
    if os.environ[AUTH_DOMAIN] == "gmail.com":
        app_id = os.environ[APPLICATION_ID]
        return "http://" + app_id + ".appspot.com"
    else:
        return "http://" + os.environ[AUTH_DOMAIN]

edit: AUTH_DOMAIN contains the custom domain, no need to include the app ID.

This will return the current version's base URL even if you're not accessing the current version, or if you visit the current version using a URL like http://current-version.latest.app_id.appspot.com (unlike URL-parsing methods)

Jason Hall
This assumes the app is being accessed on appspot, and will fail horribly if your base URL is on a Google Apps domain.
Wooble
@Wooble that's what the `AUTH_DOMAIN` bit is -- if it's not being hosted on appspot.com, the `AUTH_DOMAIN` is the custom domain where it is hosted.
Jason Hall
An app can use Google auth but still be served from another domain name; the AUTH_DOMAIN envvar will still get set to "gmail.com"
Wooble