从python“ operation_timeout”中的松弛斜杠命令增加超时

时间:2020-03-13 08:01:25

标签: python shell kubernetes slack slack-api

我在python脚本下运行,该脚本最终运行shell脚本,该脚本为我提供了k8s命名空间中正在运行的版本的列表。得到结果,但是花费时间> 3sec。因此,这会导致“ operation_timeout”松弛。我是python的新手,提供了有关延迟的各种文档,但由于这些文档非常复杂,所以没有帮助。

from subprocess import Popen, PIPE
from subprocess import check_output
from flask import Flask

def get_shell_script_output_using_communicate():
    session = subprocess.Popen(['./version.sh'], stdout=PIPE, stderr=PIPE)
    stdout, stderr = session.communicate()
    if stderr:
        raise Exception("Error "+str(stderr))
    return stdout.decode('utf-8')

def get_shell_script_output_using_check_output():
    stdout = check_output(['./version.sh']).decode('utf-8')
    return stdout

app = Flask(__name__)

@app.route('/test',methods=['POST'])
def home():
    return '`Version List` ```'+get_shell_script_output_using_check_output()+'```'

app.run(host='0.0.0.0', port=5002, debug=True)

即使命令花费的时间超过10秒,有没有办法获得响应?谢谢!

1 个答案:

答案 0 :(得分:3)

不可能将默认超时从Slack增加到斜杠命令。总是3秒。但是有可能最多发送30分钟的延迟响应。

为此,您需要在3秒内首先通过发送回HTTP 200 OK来确认初始请求。由于这需要您完成当前请求并终止您的主脚本,因此您需要并行运行延迟响应的功能。这可以在进程,线程中,可以通过调用celery任务或任何其他允许您产生并行运行的python函数的方式进行。

然后并行函数可以通过将消息发送到Slack请求中的response_url中提供的URL来响应Slack。

这是使用线程的示例实现:

import threading
from time import sleep
from flask import Flask, json, request
import requests

app = Flask(__name__) #create the Flask app

@app.route('/slash', methods=['POST'])
def slash_response():                
    """endpoint for receiving all slash command requests from Slack"""

    # get the full request from Slack
    slack_request = request.form

    # starting a new thread for doing the actual processing    
    x = threading.Thread(
            target=some_processing,
            args=(slack_request,)
        )
    x.start()

    ## respond to Slack with quick message
    # and end the main thread for this request
    return "Processing information.... please wait"


def some_processing(slack_request):
    """function for doing the actual work in a thread"""

    # lets simulate heavy processing by waiting 7 seconds
    sleep(7)

    # response to Slack after processing is finished
    response_url = slack_request["response_url"]    
    message = {        
        "text": "We found a result!"
    }
    res = requests.post(response_url, json=message)

if __name__ == '__main__':
    app.run(debug=True, port=8000) #run app in debug mode on port 8000