在googleappengine本地开发中使用请求

2024-06-09 21:38:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个web服务的SDK,它通过PyPI作为Python库分发。我的库使用requests与使用典型REST-like请求的后端通信。在

我希望我的库与谷歌应用引擎(GAE)上托管的应用程序兼容。根据the GAE documentation on HTTP requests

To use requests, you'll need to install both requests and requests-toolbelt using the vendoring instructions.

Once installed, use the requests_toolbelt.adapters.appengine module to configure requests to use URLFetch:

因此,我遵循这里给出的示例,并在我的库的主模块中包含以下内容:

  if os.getenv('SERVER_SOFTWARE', '').startswith('Google App Engine/'):
        import requests_toolbelt.adapters.appengine
        requests_toolbelt.adapters.appengine.monkeypatch()

当使用我的库的客户端应用程序实际运行在appengine实例上时,这似乎起到了作用。在

但是,当客户端应用程序使用development web server (dev_appserver.py)在本地运行时,os.getenv('SERVER_SOFTWARE')返回{},因此monkeypatch不会执行。我随后在尝试发出请求时会出现以下错误:

^{pr2}$

我如何检测到我的库的主机应用程序正在Google App Engine中运行,或者在development web服务器内运行?检查“Development/2.0”似乎没有足够的辨别力。在

或者,在发布需要支持“典型”网络请求的共享Python库时,是否有更好的通用模式?在


Tags: thetoweb应用程序serverosusesoftware
1条回答
网友
1楼 · 发布于 2024-06-09 21:38:57

通过googlecloudsdk的研究,似乎Google自己确定我们是在生产还是开发(dev_appserver.py)Google App Engine环境中运行的方法实际上是寻找SERVER_SOFTWARE的其中一个值。来自apitools/base/py/util.py

def DetectGae():
    """Determine whether or not we're running on GAE.

    This is based on:
      https://developers.google.com/appengine/docs/python/#The_Environment

    Returns:
      True iff we're running on GAE.
    """
    server_software = os.environ.get('SERVER_SOFTWARE', '')
    return (server_software.startswith('Development/') or
            server_software.startswith('Google App Engine/'))

相关问题 更多 >