在flask应用中,使用了threadPool模块,需要异步执行一些任务,这个任务主要是用于更新java代码后编译打包,耗时较长,也不想在应用中加入celery或redis异步执行,所以放在了threadpool里执行。
报错如下:
application not registered on db instance and no application bound to current context
在视图函数中
@main.route('/<branch>/<project_name>/update',methods = ['POST'])
def update_code(branch,project_name):
version = request.form.get('version','last')
db_url = db.session.query(svn_branch).filter_by(branch_name=branch).first()
url = db_url.branch_url
if url.endswith('/'):
project_url = url + project_name
else:
project_url = url + '/' + project_name
if version == 'last':
cmd = ['svn','--non-interactive','--username',current_app.config['SVN_USER'],
'--password',current_app.config['SVN_PASSWORD'],'info','--xml']
cmd += [project_url]
p = subprocess.Popen(cmd,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
stdout = p.stdout.read()
r = p.wait()
if r != 0:
return jsonify(code=500,
data='获取最新版本号失败')
else:
root = xml.etree.ElementTree.fromstring(stdout)
list_ = root.findall('entry/commit')
revision = list_[0].get('revision')
print revision
try:
int(revision)
except ValueError:
return jsonify(code=500,
data='获取的最新版本号存在异常')
version = revision
data={
'branch':branch,
'project':project_name,
'svn_path':project_url,
'version':version,
'jid':taskJid(),
'source_code_dir':os.path.join(current_app.config['CODE_DIR'],project_name),
}
current_app.ThreadPool.apply_async(taskFunction)
return jsonify(data=data)
taskFunction是来执行的函数,需要在任务开始前插入任务,设置为运行状态,在执行成功或者失败的后要修改任务状态,但是问题也就出来这里了,也自己尝试了解决但还未找到解决方法....
taskFunction函数执行任务
def taskFunction(**kwargs):
try:
db.session.query(svn_branch).first()
except Exception as e:
print e.message
此时报错
application not registered on db instance and no application bound to current context
希望各位大神帮忙解决,看了文档跟程序上下文有关,但还是未找到解决方法....
高洛峰2017-04-17 17:26:47
我覺得要當把上下文壓下去,所以taskFunction應修改為
def taskFunction(**kwargs):
ctx = main.app_context()
try:
ctx.push()
db.session.query(svn_branch).first()
except Exception as e:
print e.message
finally:
ctx.pop()