简体   繁体   English

Flask MongoDB错误:“在应用程序上下文之外工作”

[英]Flask MongoDB error: “working outside of application context”

I've been trying to test my Flask application that uses PyMongo. 我一直在尝试测试使用PyMongo的Flask应用程序。 The application works fine, but when I execute unit tests, I constantly get an error message saying "working outside of application context". 该应用程序工作正常,但是当我执行单元测试时,我不断收到一条错误消息,指出“在应用程序上下文之外工作”。 This message is thrown every time I run any unit test that requires access to the Mongo database. 每当我运行任何需要访问Mongo数据库的单元测试时,都会引发此消息。

I've been following this guide for unit testing: http://flask.pocoo.org/docs/testing/ 我一直在遵循该指南进行单元测试: http : //flask.pocoo.org/docs/testing/

My application's design is straight forward, similar to the standard Flask tutorial. 我的应用程序的设计很简单,类似于标准的Flask教程。

Did anyone already have the same issue? 有人有同样的问题吗?

class BonjourlaVilleTestCase(unittest.TestCase):
    container = {}
    def register(self, nickname, password, email, agerange):
        """Helper function to register a user"""
        return self.app.post('/doregister', data={
            'nickname' :    nickname,
            'agerange' :    agerange,
            'password':     password,
            'email':        email
        }, follow_redirects=True)


    def setUp(self):        
        app.config.from_envvar('app_settings_unittests', silent=True)

        for x in app.config.iterkeys():
            print "Conf Key=%s, Value=%s" % (x, app.config[x])


        self.app = app.test_client()

        self.container["mongo"] = PyMongo(app)
        self.container["mailer"] = Mailer(app)
        self.container["mongo"].safe = True

        app.container = self.container

    def tearDown(self):
        self.container["mongo"].db.drop()
        pass    

    def test_register(self):
        nickname = "test_nick"
        password = "test_password"
        email    = "test@email.com"
        agerange = "1"
        rv = self.register(nickname, password, email, agerange)

        assert "feed" in rv.data


if __name__ == '__main__':    
    unittest.main()

I've finally fixed the issue, which was due to the application context. 我终于解决了该问题,这是由于应用程序上下文引起的。 It seems that when using PyMongo, as it manages the connection for you, the connection object must be used within the same context which initialized the PyMongo instance. 似乎在使用PyMongo时,由于它为您管理连接,因此必须在初始化PyMongo实例的同一上下文中使用连接对象。

I had to modify the code, thus the PyMongo instance is initialized in the testable object. 我必须修改代码,因此PyMongo实例在可测试对象中初始化。 Later, this instance is returned via a public method. 稍后,该实例通过公共方法返回。

Thus, to resolve the issue, all my DB requests in the unit tests must be executed under the with statement. 因此,要解决此问题,必须在with语句下执行我在单元测试中的所有数据库请求。 Example follows 示例如下

with testable.app.app_context():
    # within this block, current_app points to app.
    testable.dbinstance.find_one({"user": user})

查看Context Locals和test_request_context(): http : //flask.pocoo.org/docs/quickstart/#context-locals

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM