python - Flask应用上下文
PHP中文网
PHP中文网 2017-04-17 17:24:47
0
2
830

在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

希望各位大神帮忙解决,看了文档跟程序上下文有关,但还是未找到解决方法....

PHP中文网
PHP中文网

认证0级讲师

모든 응답(2)
小葫芦

컨텍스트를 억제해야 한다고 생각하므로 taskFunction을

으로 수정해야 합니다. 으아악
Ty80

가라앉을 수 없어요. . .

최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿