我的 Web 服务有一个 SDK,它通过 PyPI 作为 Python 库分发。我的图书馆使用 requests用于使用典型的类似 REST 的请求与后端进行通信。
我希望我的库与 Google App Engine (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()
当使用我的库的客户端应用程序实际在 App Engine 实例上运行时,这似乎可以解决问题。
但是,当客户端应用程序使用 development web server (dev_appserver.py) 在本地运行时, os.getenv('SERVER_SOFTWARE')
返回 "Development/2.0"
,因此不执行 Monkeypatch。随后,我在尝试发出请求时收到这些错误:
ConnectionError: ('Connection aborted.', error(13, 'Permission denied'))
如何检测我的库的主机应用程序是在 Google App Engine 本身中运行,还是在开发 Web 服务器中运行??检查“Development/2.0”似乎没有足够的区别。
或者,在发布需要支持“典型”网络请求的共享 Python 库时,是否有更好的通用模式可以遵循?
最佳答案
深入研究Google Cloud SDK,似乎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/'))
关于python - 在 Google App Engine 本地开发服务器中使用请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48014071/