如何使用 SQLAlchemy 设置 Flask 应用程序进行测试? [英] How do you set up a Flask application with SQLAlchemy for testing?

查看:25
本文介绍了如何使用 SQLAlchemy 设置 Flask 应用程序进行测试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Flask 中这样开始似乎很常见:

It seems common practice in Flask to start like this:

from flask import Flask
from flaskext.sqlalchemy import SQLAlchemy
app = Flask(__name__)
SQLALCHEMY_DATABASE_URI = 'something'
app.config.from_object(__name__)
db = SQLAlchemy(app)

然后在任何地方导入并使用appdb.但是当您像这样创建 db 时,它会从应用程序中获取配置,并且一旦发生此配置似乎永远无法覆盖.Flask 的网站上有一些关于创建应用程序工厂的页面,但不清楚如果我这样做了,我如何仍然能够在任何地方使用 appdb.

And then import and use app and db everywhere. But when you create db like this, it grabs configuration from the app, and it seems that this configuration can't ever be overridden once it happens. There are some pages on Flask's website about making application factories, but it's not clear how I would be able to still use app and db everywhere if I did that.

如何编写脚本来使用不同的数据库测试我的 Flask 应用程序?我应该如何构建我的应用程序以使其成为可能?我必须使用 modules 吗?

How do I write a script to test my Flask application with a different database? How should I structure my application to make this possible? Do I have to use modules ?

推荐答案

您使用环境变量的直觉是正确的.但是,使用错误的数据库运行单元测试存在一些危险.此外,您可能不希望在每个请求和任何您想使用 db 的地方都使用 connect_db.您可以使用您明确设置的配置目录和环境变量.这是迄今为止我想出的最好的.

Your instinct to use environment variables is correct. However, there is some danger of running unit tests with the wrong db. Also, you may not want to connect_db with every request and everywhere you want to use db. You can use a config directory and environment variables which you set explicitly. This is the best I've come up with so far.

run.py
shell.py

config/__init__.py
config/test.py
config/postgres.py
...

main/__init__.py
main/someapp/__init__.py
main/someapp/models.py

...
main/tests/__init__.py
main/tests/testutils.py

所以,配置文件可能是:

so, the config files may be:

# config/test.py
SQLALCHEMY_DATABASE_URI = "sqlite://"

# config/postgres.py
SQLALCHEMY_DATABASE_URI = 'postgresql://user:pw@localhost/somedb'

所以,我可以在我的基本 TestCase 中显式设置数据库:

So, I can explicitly set the db in my base TestCase:

import os
from flask.ext.testing import TestCase

os.environ["DIAG_CONFIG_MODULE"] = "config.test"
from main import app, db


class SQLAlchemyTest(TestCase):

    def create_app(self):
        return app

    def setUp(self):
        db.create_all()

    def tearDown(self):
        db.session.remove()
        db.drop_all()

然后,main/__init__.py,对我来说:

import os

from flask import Flask, render_template, g
from flask.ext.sqlalchemy import SQLAlchemy

# by default, let's use a DB we don't care about
# but, we can override if we want
config_obj = os.environ.get("DIAG_CONFIG_MODULE", "config.test")
app = Flask(__name__)
app.config.from_object(config_obj)
db = SQLAlchemy(app)

@app.before_request
def before_request():
    g.db = db
    g.app = app

# ...
@app.route('/', methods=['GET'])
def get():
    return render_template('home.html')
# ...    
from main.someapp.api import mod as someappmod
app.register_blueprint(someappmod)

然后,在其他文件中,我可能知道要运行什么配置:

Then, in the other files, where I know what config I want to run, potentially:

# run.py
import os
os.environ["DIAG_CONFIG_MODULE"] = "config.postgres"
from main import app
app.run(debug=True)

# shell.py
import os
os.environ["DIAG_CONFIG_MODULE"] = "config.postgres"

from main import app, db
from main.symdiag.models import *
from main.auth.models import *
print sorted(k for k in locals().keys() if not k.startswith("_"))
import IPython
IPython.embed()

也许……到目前为止最好的:P.

Maybe .. best so far :P.

这篇关于如何使用 SQLAlchemy 设置 Flask 应用程序进行测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆