我有一个小的烧瓶API设置如下,
from flask import Flask, request, jsonify, Response
import json
import subprocess
import os
app = Flask(__name__)
shellScripts = {
    'redeploy': ['/bin/bash', 'redeploy.sh'],
    'script-exec': ['/bin/bash', 'script-exec.sh']
}
def prepareShellCommand(json_data, scriptKey):
    script=shellScripts[scriptKey]
    print('script is')
    print(script)
    for key in json_data:
        if scriptKey == 'redeploy':
            script.append("-{0}".format(key[0]))
        script.append(json_data[key])
    return script
@app.route('/redeploy', methods=['POST'])
def setup_redeploy():
    branches_data_json = request.get_json()
    if ('frontendBranch' not in branches_data_json and 'backendBranch' not in branches_data_json):
        return jsonify({'error': 'Need to provide at least one branch'}), 400
    command = prepareShellCommand(branches_data_json, 'redeploy')
    sp = subprocess.Popen(command)
    return jsonify({'message': 'Redeployment under process'}), 201
@app.route('/execute', methods=['POST'])
def execute_script():
    script_data_json = request.get_json()
    if ('scriptPath' not in script_data_json):
        return jsonify({'error': 'Need to provide script path'}), 400
    command = prepareShellCommand(script_data_json, 'script-exec')
    sp = subprocess.Popen(command)
    return jsonify({'message': 'Script execution under process'}), 201现在发生的事情是,假设我启动了一个API端点,/execute将一些数据作为{scriptPath: 'some-file'},它成功地运行了。但是,有时候,不管请求体数据中发生了什么变化,API似乎与旧的数据{scriptPath: 'some-file'}一起工作,即使我是用类似于{scriptPath: 'new-file'}的东西启动API。直到我终止python进程并重新启动它,它才会改变。
这是什么原因?我是作为开发服务器在google云实例上运行的。
这种情况发生在两个端点上,我有一种直觉,认为这与subprocess或包含样板的字典有关。
有人能帮我吗?
发布于 2019-06-24 11:01:13
这几乎可以肯定是因为您已经在模块级别定义了shellScripts,但是从处理程序中修改了它。对该字典值的更改将持续到服务器进程的生存期。
您应该复制该值并修改该值:
def prepareShellCommand(json_data, scriptKey):
    script = shellScripts[scriptKey].copy()https://stackoverflow.com/questions/56734569
复制相似问题