【问题标题】:Flask Application was not able to create a URL adapter for requestFlask 应用程序无法为请求创建 URL 适配器
【发布时间】: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 ,我不知道它何时设置。

谢谢!

【问题讨论】:

标签: python flask url-for


【解决方案1】:

根据blog post,您可以尝试这种模式,它为您提供应用上下文临时请求上下文:

    def test_url(self):
        with app.app_context(), app.test_request_context():
            self.assertEqual('/', url_for('root.home'))

【讨论】:

  • 这太好了。谢谢,一直想知道。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-12
  • 1970-01-01
  • 1970-01-01
  • 2019-12-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多