在 Flask Restful API 中使用 Python 脚本

Using a Python script in Flask Restful API

这是我的 Flask 代码。虽然它没有正确实施并且无法正常工作,但它至少让您了解我正在尝试做什么。

@app.route('/runid', methods=['GET','POST'])
def execCmdLocal(cmd):
    proc = subprocess.Popen(cmd, stdout=subprocess.PIPE,
                                stderr=subprocess.PIPE,
                                shell=True )
    stdout, stderr = proc.communicate()
    status = proc.poll()
    if status != 0:
         print("Failed to execute command %s" % cmd)
    return status, stdout, stderr
 def runid()
 time.sleep(1)
 cmdStr = 'cd /root/Dart/log; ls -rt DartRunner*.log | tail -1 '
 ret = execCmdLocal(cmdStr)
 logName = ret[1].strip()
 print('The DartRunner Log generated is: %s'%logName)
 with open('/root/Dart/log/' + logName, "r") as fd:
    for line in fd:
        if 'runId' in line:
            runId = line.split()[-1]
            print('Run Id: %s'%runId)
            break
 print runID
 return runId

我原来的Python脚本是:

import os
from pprint import pprint
import time
def execCmdLocal(cmd):
    proc = subprocess.Popen(cmd, stdout=subprocess.PIPE,
                                stderr=subprocess.PIPE,
                                shell=True )

    stdout, stderr = proc.communicate()
    status = proc.poll()

    if status != 0:
         print("Failed to execute command %s" % cmd)
    return status, stdout, stderr
time.sleep(1)
cmdStr = 'cd /root/Dart/log; ls -rt DartRunner*.log | tail -1 '
ret = execCmdLocal(cmdStr)
#pprint(ret)
logName = ret[1].strip()
print('The DartRunner Log generated is: %s'%logName)
with open(logName, "r") as fd:
    for line in fd:
        if 'runId' in line:
        runId = line.split()[-1]
        print('Run Id: %s'%runId)
        break;

我的输出是:

The DartRunner Log generated is: DartRunner-2018-06-07-145652.log Run Id: 180607-133

整个程序启动时打印该函数。 但是我只是在调用我的 restAPI 路由时才尝试获取它。

提前致谢。

代码改动应该是这样的。默认Flask请求是GET,希望你只需要执行一个进程。另外,尝试 return a JSON_RESPONSE 来请求烧瓶。尝试学习 Flask 基础知识以更好地理解。

    @app.route('/runid')
    def runid():
        cmdStr = 'cd /root/Dart/log; ls -rt DartRunner*.log | tail -1 '
        ret = execCmdLocal(cmdStr)
        logName = ret[1].strip()
        print('The DartRunner Log generated is: %s'%logName)
        with open('/root/Dart/log/' + logName, "r") as fd:
        for line in fd:
            if 'runId' in line:
                runId = line.split()[-1]
                print('Run Id: %s'%runId)
                break
        return jsonify(runId)

    def execCmdLocal(cmd):
        proc = subprocess.Popen(cmd, stdout=subprocess.PIPE,
                                    stderr=subprocess.PIPE,
                                    shell=True )
        stdout, stderr = proc.communicate()
        status = proc.poll()
        if status != 0:
             print("Failed to execute command %s" % cmd)
        return status, stdout, stderr