[英]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? 如何让App Engine生成当前正在运行的服务器的URL?
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 如果该应用程序正在Google的服务器上运行,则应返回
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) 您可以通过
self.request.url
从Webapp处理程序中获取用于发出当前请求的URL,也可以使用self.request.environ
字典将其组合在一起(您可以在WebOb文档中阅读-请求从webob继承)
You can't "get the url for the server" itself, as many urls could be used to point to the same instance. 您不能“获取服务器的URL”本身,因为可以使用许多URL指向同一实例。
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
本地主机:8080
and on appengine 并在appengine上
your_app_id.appspot.com
your_app_id.appspot.com
If you're using webapp2 as framework chances are that you already using URI routing in you web application. 如果您使用webapp2作为框架,则很可能已经在Web应用程序中使用了URI路由。
http://webapp2.readthedocs.io/en/latest/guide/routing.html 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. 使用
webapp2.uri_for()
构建URI时,只需传递_full=True
属性即可根据当前运行时环境生成包括当前域,端口和协议的绝对URI。
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. 此函数可以在您的Python代码中使用,也可以直接从模板引擎中使用(如果您注册了它)-非常方便。
Check webapp2.Router.build() in the API reference for a complete explanation of the parameters used to build URIs. 检查API参考中的webapp2.Router.build() ,以获取有关用于构建URI的参数的完整说明。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.