dev_appserver.py 无法发出 SSL 请求的解决方法

Workaround for dev_appserver.py inability to make SSL requests

运行 尝试从 Google App Engine 应用调用 braintree.ClientToken.generate() 时遇到此问题,运行 Flask on dev_appserver.pydev_appserver.py 目前无法进行传出 SSL 连接。进行上述 braintree 调用会产生

ConnectionError: ('Connection aborted.', error(13, 'Permission denied'))

调用在真实的 GAE 环境中进行。它在我的一个视图中使用过,所以当它失败时,它会破坏我的整个网站流程并显示上述 500 错误。我该如何解决这个问题,以便我可以在本地环境中继续开发?

如果您的应用程序有一些全局变量与您在 dev_appserver.py 中 运行 时对应,您可以创建一个以该变量为条件的失败方法的模拟。

在我的例子中,该变量称为 env_conf.FLASK_CONF。我使用以下代码来模拟 braintree 生成调用。

# Imports
import braintree
import env_conf
from flask import render_template

# Mock Braintree in DEV environment
if env_conf.FLASK_CONF == 'DEV':
    from functools import partial
    def mock_generate(self):
        return 'foobarbaz123'
    braintree.ClientToken.generate = partial(mock_generate, braintree.ClientToken())

# Add payment handler
def add_payment():
    token = braintree.ClientToken.generate()
    return render_template('add-payment.html',
                           braintree_client_token=token)

一般的想法是:

import problem_function
if DEV_ENVIRONMENT:
    def mock_problem_fcn():
        return 'expected response'
    problem_function = mock_problem_function

problem_function()

我在布伦特里工作。如果有更多问题,可以随时contact our support team

有关 GAE 上 Braintree Python 库的帮助,请参阅 this example on my GitHub. To answer your question, you can force the dev server to use the real Python socket library,因此 SSL 连接有效:

try:
    # This is needed to make local development work with SSL.
    # This must be done *before* you import the Braintree Python library.
    # See 
    # and https://code.google.com/p/googleappengine/issues/detail?id=9246 for more information.
    from google.appengine.tools.devappserver2.python import sandbox
    sandbox._WHITE_LIST_C_MODULES += ['_ssl', '_socket']

    import sys
    # this is socket.py copied from a standard python install
    import stdlib_socket
    sys.modules['socket'] = stdlib_socket
except ImportError as e:
    print(e)