增加Python“操作超时”中的松弛斜杠命令的超时

Aay*_*shi 4 python shell slack-api kubernetes slack

我正在 python 脚本下运行,该脚本最终运行 shell 脚本,该脚本为我提供了 k8s 命名空间中正在运行的版本列表。得到结果,但需要时间 > 3 秒。因此,这导致了松弛的“操作超时”。我是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)
Run Code Online (Sandbox Code Playgroud)

即使命令花费超过 10 秒,是否有办法获得响应?谢谢!

Eri*_*ken 7

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

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

response_url然后,并行函数可以通过将消息发送到Slack 请求中提供的 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
Run Code Online (Sandbox Code Playgroud)