在 Flask 中使用 url_for 获取外部 URL returns werkzeug.routing.BuildError

Using url_for in flask for external URLs returns werkzeug.routing.BuildError

我写了一个 flask 服务器,在某些情况下可以将用户重定向到外部站点。我使用 python unittest 模块编写了一些单元测试。对于其中一些正在测试重定向部分的,我得到 werkzeug.routing.BuildError。这是其中一个测试用例的代码:

with app.app_context(), app.test_request_context():
    response = self.app.get('/{0}'.format(test_url), follow_redirects=False)
    self.assertEqual(response.status_code, 302)
    self.assertEqual(response.location, url_for('https://www.linkedin.com/in/zeinab-abbasimazar-0327aa47', _external=True, _scheme='https'))

这是完整的堆栈跟踪:

Ran 1 test in 3.211s

FAILED (errors=1)

Error
Traceback (most recent call last):
  File "/usr/lib/python3.6/unittest/case.py", line 59, in testPartExecutor
    yield
  File "/usr/lib/python3.6/unittest/case.py", line 605, in run
    testMethod()
  File "/home/zeinab/PycharmProjects/url_shortener/tests.py", line 167, in test_get_long_existing_url
    self.assertEqual(response.location, url_for(long_url, _external=True, _scheme='https'))
  File "/home/zeinab/.local/lib/python3.6/site-packages/flask/helpers.py", line 370, in url_for
    return appctx.app.handle_url_build_error(error, endpoint, values)
  File "/home/zeinab/.local/lib/python3.6/site-packages/flask/app.py", line 2215, in handle_url_build_error
    reraise(exc_type, exc_value, tb)
  File "/home/zeinab/.local/lib/python3.6/site-packages/flask/_compat.py", line 39, in reraise
    raise value
  File "/home/zeinab/.local/lib/python3.6/site-packages/flask/helpers.py", line 358, in url_for
    endpoint, values, method=method, force_external=external
  File "/home/zeinab/.local/lib/python3.6/site-packages/werkzeug/routing.py", line 2020, in build
    raise BuildError(endpoint, values, method, self)
werkzeug.routing.BuildError: Could not build url for endpoint 'https://www.linkedin.com/in/zeinab-abbasimazar-0327aa47'. Did you mean 'static' instead?


Assertion failed

我在 setUp 方法中也有以下行:

app.config['PREFERRED_URL_SCHEME'] = 'https'

我尝试按照 this question 中所述修补 url_for 方法;但它并没有改变我的结果。

我也尝试了 _force_https 解释的方法 here 并没有发现任何变化。

我读this page时打印出app.config['wsgi.url_scheme'],结果是https

我在 Ubuntu 系统上使用 python 3.6。谁能帮我解决这个错误?

直接使用带 url 的字符串而不带 url_for()

self.assertEqual(response.location, 'https://www.linkedin.com/in/zeinab-abbasimazar-0327aa47')

通常 url_for() 也使用 url 创建字符串,但它只对代码中的函数名称执行此操作 - url_for(function_name) - 不适用于 urls.