【发布时间】:2020-02-07 10:42:22
【问题描述】:
我有这个曾经可以工作的代码:
import unittest
from flask import url_for
from dm.web import create_app, db
class TestApi(unittest.TestCase):
def setUp(self):
"""Create and configure a new app instance for each test."""
self.app = create_app('test')
self.app_context = self.app.app_context()
self.app_context.push()
db.create_all()
self.client = self.app.test_client(use_cookies=True)
def tearDown(self) -> None:
db.session.remove()
db.drop_all()
self.app_context.pop()
def test_url(self):
self.assertEqual('/', url_for('root.home'))
if __name__ == '__main__':
unittest.main()
但是从今天开始我收到了这个错误:
ERROR: test_url (__main__.TestApi)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/home/joan/.PyCharmCE2019.3/config/scratches/scratch.py", line 17, in test_url
self.assertEqual('/', url_for('root.home'))
File "/home/joan/venvs/dimensigon3.7/lib/python3.7/site-packages/flask/helpers.py", line 333, in url_for
"Application was not able to create a URL adapter for request"
RuntimeError: Application was not able to create a URL adapter for request independent URL generation. You might be able to fix this by setting the SERVER_NAME config variable.
根据我在 url_for 中看到的内容,我在 appctx.url_adapter 上得到 None ,我不知道它何时设置。
谢谢!
【问题讨论】:
-
尝试了一个简单的例子,但同样的错误:
-
是的,我可以设置变量 SERVER_NAME 来运行它。正如@Ramon Medeiros 提到的评论中所说。问题解决了,但我想知道为什么它需要 server_name 或请求上下文来提供一个内部 url,它是从函数到 url 的直接映射?