我无法通过 flask 调用 pandoc(ResponseTimeOut 错误)到达 URL

I cannot reach a URL with flask calling pandoc (ResponseTimeOut error)

只需 return flask 中的一些(markdown)字符串:

@app.route("/raw/", methods=['GET'])
def sometext():
    return "This is an **example**"

## Main procedure
if __name__ == "__main__":
    app.run(debug=True, port=8000) 

如果您直接调用 pandoc (pandoc http://localhost:8000/raw) 或使用 subprocess,您不会遇到问题:

import subprocess, os

url = "http://localhost:8000/raw"
pbody = subprocess.run(["pandoc", url], check=True, stdout=subprocess.PIPE)
print(pbody.stdout.decode())

但是如果你在 flask 方法中调用 pandoc:

@app.route("/get", methods=['GET'])
def index():
    url = "{}".format(url_for('sometext', _external=True))
    pbody = subprocess.run(["pandoc", url], check=True, stdout=subprocess.PIPE, universal_newlines=True)
    print("***Error: ", pbody.stderr)
    return pbody.stdout

然后当您访问 http://localhost:8000/get 时,您会收到来自 pandoc 的 Responsetimeout 错误:

pandoc: HttpExceptionRequest Request {
  host                 = "localhost"
  port                 = 8000
  secure               = False
  requestHeaders       = []
  path                 = "/raw/"
  queryString          = ""
  method               = "GET"
  proxy                = Nothing
  rawBody              = False
  redirectCount        = 10
  responseTimeout      = ResponseTimeoutDefault
  requestVersion       = HTTP/1.1
}
 ResponseTimeout

参考文献:url_for in flask API

我记得 Flask http 服务器是单线程的,因此当它仍在处理“/get”请求时无法处理“/raw”请求。

Answer to another SO question 建议使用 app.run(threaded=True) 这可能足以满足个人使用。对于生产用途,您应该考虑使用真正的 Web 服务器,例如 nginx 或 apache。

即便如此,假设 pandoc 支持它(我不知道),您可能需要考虑将 markdown 输入发送到 pandoc stdin 并完全避免额外的 HTTP 请求,例如(未测试)

markdown = StringIO("This is an **example**")
pbody = subprocess.run(["pandoc"], check=True, stdin=markdown, stdout=subprocess.PIPE, universal_newlines=True)