0

I have a small flask API setup as following,

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

What's happening is, say I initiate an API endpoint, /execute with some data as {scriptPath: 'some-file'}, and it runs successfully. However, sometimes, regardless of change in the request body data, the API seems to work with the old data, {scriptPath: 'some-file'}, even if I am initiating the API with something like {scriptPath: 'new-file'}. And it doesn't change until I kill the python process, and restart it.

What could be the reason for this? I am running this as a development server, on a google cloud instance.

It's happening with both the endpoints, and I have a gut feeling that it's got something to do with either the subprocess or the dictionary that contains the boilerplate.

Can anyone help me with this?

relentless-coder
  • 1,478
  • 3
  • 20
  • 39

1 Answers1

1

This is almost certainly because you have defined shellScripts at module level but modify it from your handlers. The changes to the values of that dictionary will persist for the lifetime of the server process.

You should copy the value and modify that instead:

def prepareShellCommand(json_data, scriptKey):
    script = shellScripts[scriptKey].copy()
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895