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'}
. 在我终止 python 进程并重新启动它之前它不会改变。
这可能是什么原因?我在谷歌云实例上将其作为开发服务器运行。
两个端点都发生了这种情况,我有一种直觉,它与subprocess
包含样板的 the 或字典有关。
谁能帮我这个?
解决方案
这几乎可以肯定是因为您已经shellScripts
在模块级别进行了定义,但是从您的处理程序中对其进行了修改。对该字典值的更改将在服务器进程的整个生命周期内持续存在。
您应该复制该值并对其进行修改:
def prepareShellCommand(json_data, scriptKey):
script = shellScripts[scriptKey].copy()
推荐阅读
- html - Gulp:如何将 filename.pug 构建为 filename/index.html
- python - 如何将多个文件移动和重命名到特定文件夹?
- laravel - 如何以我们可以链接它们的方式将自定义方法添加到 eloquent 模型?
- java - 如何为自定义图像视图的属性设置值?
- python - 如何只画一个,pick_event选择的最新点?
- ios - iOS 共享扩展,configurationItems (tableView)
- java - 英国大陆的 OS UK 网格参考
- json - 在旋转的 D3.Js 地球上隐藏点
- docker - 将 docker 日志消息重定向到不同的 syslog 文件(由 logspout 转发)
- reactjs - 为什么我得到`this.props.onAdd is not a function`?