简体   繁体   中英

Getting the Server URL in Google App Engine using python

How do I get App Engine to generate the URL of the server it is currently running on?

If the application is running on development server it should return

http://localhost:8080/

and if the application is running on Google's servers it should return

http://application-name.appspot.com

You can get the URL that was used to make the current request from within your webapp handler via self.request.url or you could piece it together using the self.request.environ dict (which you can read about on the WebOb docs - request inherits from webob)

You can't "get the url for the server" itself, as many urls could be used to point to the same instance.

If your aim is really to just discover wether you are in development or production then use:

'Development' in os.environ['SERVER_SOFTWARE']

Here is an alternative answer.

from google.appengine.api import app_identity
server_url = app_identity.get_default_version_hostname()

On the dev appserver this would show:

localhost:8080

and on appengine

your_app_id.appspot.com

If you're using webapp2 as framework chances are that you already using URI routing in you web application.
http://webapp2.readthedocs.io/en/latest/guide/routing.html

app = webapp2.WSGIApplication([
    webapp2.Route('/', handler=HomeHandler, name='home'),
])

When building URIs with webapp2.uri_for() just pass _full=True attribute to generate absolute URI including current domain, port and protocol according to current runtime environment.

uri = uri_for('home')
# /

uri = uri_for('home', _full=True)
# http://localhost:8080/
# http://application-name.appspot.com/
# https://application-name.appspot.com/
# http://your-custom-domain.com/

This function can be used in your Python code or directly from templating engine (if you register it) - very handy.

Check webapp2.Router.build() in the API reference for a complete explanation of the parameters used to build URIs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM