[英]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'
我嘗試按照這個問題中的描述修補url_for
方法; 但這並沒有改變我的結果。
我也試過_force_https
方法解釋這里並沒有看到變化。
當我閱讀此頁面時,我打印了app.config['wsgi.url_scheme']
,它是https
。
我在 Ubuntu 系統上使用 python 3.6。 誰能幫我解決這個錯誤?
不使用url_for()
直接使用帶有 url 的字符串
self.assertEqual(response.location, 'https://www.linkedin.com/in/zeinab-abbasimazar-0327aa47')
通常url_for()
也會創建帶有 url 的字符串,但它只對代碼中的函數名稱執行此操作 - url_for(function_name)
- 不適用於 url。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.