我在烧瓶里研究一种小的休息原料药。Api有一个注册请求并生成单独线程以在后台运行的路由。代码如下:
def dostuff(scriptname):
new_thread = threading.Thread(target=executescript,args=(scriptname,))
new_thread.start()
线程启动,但当我试图从executescript函数插入数据库时,它出错了。它抱怨没有在应用程序中注册db对象。
我正在动态创建我的应用程序(以api为蓝图)。
以下是应用程序的结构
-run.py ## runner script
-config
-development.py
-prod.py
-app
-__init__.py
- auth.py
- api_v1
- __init__.py
- routes.py
- models.py
这是我的跑步者脚本run.py
:
from app import create_app, db
if __name__ == '__main__':
app = create_app(os.environ.get('FLASK_CONFIG', 'development'))
with app.app_context():
db.create_all()
app.run()
以下是创建应用程序的app/__init__.py
中的代码:
from flask import Flask, jsonify, g
from flask.ext.sqlalchemy import SQLAlchemy
db = SQLAlchemy()
def create_app(config_name):
"""Create an application instance."""
app = Flask(__name__)
# apply configuration
cfg = os.path.join(os.getcwd(), 'config', config_name + '.py')
app.config.from_pyfile(cfg)
# initialize extensions
db.init_app(app)
# register blueprints
from .api_v1 import api as api_blueprint
app.register_blueprint(api_blueprint, url_prefix='/api/')
return app
我只需要知道如何在routes.py
中扩展应用程序上下文。我不能直接在那里导入app,如果我执行以下操作,我将得到RuntimeError: working outside of application context
def executescript(scriptname):
with current_app.app_context():
test_run = Testrun(pid=989, exit_status=988,comments="Test TestStarted")
db.session.add(test_run)
db.session.commit()
目前没有回答
相关问题 更多 >
编程相关推荐