首页 > 解决方案 > 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'}. 在我终止 python 进程并重新启动它之前它不会改变。

这可能是什么原因?我在谷歌云实例上将其作为开发服务器运行。

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

谁能帮我这个?

标签: pythonflask

解决方案


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

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

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

推荐阅读