简体   繁体   English

烧瓶测试数据库应用程序上下文

[英]Flask testing database application context

How can I structure my flask project such that my models can be aware of if TESTING is enabled (and thereby use a testing database), without having them deal with or have any knowledge of app context. 如何构造我的flask项目,以便我的模型可以知道是否启用了TESTING (从而使用了测试数据库),而无需让他们处理或不了解应用程序上下文。

I'm developing this as an open source project so the source might shed some light on this: https://github.com/nficano/jotonce.com/blob/master/jotonce/messages/models.py#L33 我正在将其开发为一个开源项目,因此源可能对此有所启发: https : //github.com/nficano/jotonce.com/blob/master/jotonce/messages/models.py#L33

I think you're running into this problem because you don't provide a way for users to specify configuration at run-time. 我认为您遇到了这个问题,因为您没有为用户提供一种在运行时指定配置的方法。 Instead, managers.py grabs whatever settings that are specified in your settings.py file without consulting what settings the end-user might have specified. 相反, managers.py会获取settings.py文件中指定的任何设置,而无需咨询最终用户可能已指定的设置。

Since you do have factory.py , you could potentially import current_app from Flask (assuming that your db functions are called within an app context) and use the settings value there. 由于您确实具有factory.py ,因此可以从Flask导入current_app (假设在应用程序上下文中调用了db函数)并在其中使用设置值。 If that's an option for you, Flask has some good suggestions for configuration handling . 如果您愿意这样做,Flask会为配置处理提供一些好的建议。

If you're running this outside of your application context, I don't think how factory.py is currently structured is going to work for you. 如果您是在应用程序上下文之外运行此程序,则我认为factory.py当前的结构方式对您不起作用。 You'll need to handle your own configuration manually. 您需要手动处理自己的配置。

You can take a look at https://github.com/Robpol86/Flask-Large-Application-Example/blob/master/pypi_portal/application.py for an example of a large flask project that uses the app factory with different configuration values well. 您可以查看https://github.com/Robpol86/Flask-Large-Application-Example/blob/master/pypi_portal/application.py ,以获取使用带有不同配置值的app工厂的大型flask项目的示例好。

Good luck, and happy holidays! 祝你好运,节日快乐!

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

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