Flask服务器可以缓存请求正文吗?

时间:2019-06-24 10:24:52

标签: python flask

我的小烧瓶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 Cloud实例上将其作为开发服务器运行。

这两个端点都在发生,我有一种直觉,认为它与subprocess或包含样板的字典有关。

有人可以帮我吗?

1 个答案:

答案 0 :(得分:0)

这几乎可以肯定是因为您已经在模块级别定义了shellScripts,但是从处理程序中对其进行了修改。对该字典值的更改将在服务器进程的整个生命周期中持续存在。

您应该复制值并进行修改:

def prepareShellCommand(json_data, scriptKey):
    script = shellScripts[scriptKey].copy()