Flask returns 404 次浏览

Flask returns 404 in views

我在 Flask 应用程序中进行 运行 单元测试,当 views.py 文件未被导入时我一直收到 404,即使它没有被使用。我有这样的 tests.py 包裹:

import unittest

from presence_analyzer import main, utils
from presence_analyzer import views

class PresenceAnalyzerViewsTestCase(unittest.TestCase):

    def setUp(self):
        self.client = main.app.test_client()

    def test_mainpage(self):
        resp = self.client.get('/')
        self.assertEqual(resp.status_code, 302)

当我删除视图导入时,出现了所描述的问题。视图的组织方式与此类似:

from presence_analyzer.main import app

@app.route('/')
def mainpage():

    return redirect('/static/presence_weekday.html')

main.py 文件:

import os.path
from flask import Flask


app = Flask(__name__)  # pylint: disable=invalid-name
app.config.update(
    DEBUG=True,
)

我想这与发生的事情类似 , so I'm trying to change the application so that I don't have to make this dumb imports while testing. I've been trying to make use of the answer from above, but still can't make it work and these docs 似乎没有帮助。我究竟做错了什么? main.py:

from flask.blueprints import Blueprint

PROJECT_NAME = 'presence_analyzer'

blue_print = Blueprint(PROJECT_NAME, __name__)

def create_app():
    app_to_create = Flask(__name__)  # pylint: disable=invalid-name
    app_to_create.register_blueprint(blue_print)
    return app_to_create

app = create_app()

views.py:

from presence_analyzer.main import app, blue_print

@blue_print.route('/')
def mainpage():

    return redirect('/static/presence_weekday.html')

tests.py保持不变。

您必须导入 views,否则该路由将不会被注册。不,您不是直接执行视图,而是导入执行所有模块级代码的代码。执行代码调用 routeroute 注册视图函数。您无法避免需要导入模块才能使用该模块。