在Flask Restful API中使用Python脚本

时间:2018-06-08 05:11:16

标签: python flask flask-restful

这是我的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;

我的输出是:

  

生成的DartRunner日志是:DartRunner-2018-06-07-145652.log   运行ID:180607-133

启动整个程序时会打印此功能。 但是我只是在我调用restAPI路线时尝试获取它。

提前致谢。

1 个答案:

答案 0 :(得分:0)

代码更改应该是这样的。默认Flask请求是GET,我希望你只需要执行一个进程。此外,尝试为烧瓶请求返回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