我正在尝试使用Python Flask创建一个REST API,该API通过POST接收XML文件。
我希望API读取XML的内容,并寻找一个参数/键(“目录”),以决定将其发送到何处,就像切换到其他Web应用程序一样。

主要问题是,在使用Flask request.data或request.form时,我不断收到500个错误-根据其他类似文章,这些方法之一应与XML一起使用。

常见的500错误解释是“ TypeError:视图函数未返回有效响应。该函数返回None或在没有return语句的情况下结束。”

我已经尝试过基于其他StackOverflow线程的命令行cURL请求来一次发送一个XML,但是与我编写的发送XML(使用请求库)的客户端python程序相比没有什么不同。

我一直使用的XML格式来卷曲到API


<?xml version="1.0" encoding="UTF-8" ?>
<xml>
<Directory>Directory 2</Directory>
<ID>2</ID>
<Name>Jane</Name>
</xml>



Python Flask API代码:

from flask import Flask, request
import xmltodict
import requests

app = Flask(__name__)

@app.route("/XMLhandling", methods=["POST"])
def handleXML():
    #for debugging..
    if True:
        print("HEADERS", request.headers)
        print("REQ_path", request.path)
        print("ARGS", request.args)
        print("DATA", request.data)
        print("FORM",request.form)
    #parse the XML
    datacache = xmltodict.parse(request.form)
    print(datacache)
    print(datacache['xml']['Directory'])
    if datacache['xml']['Directory'] == "Directory 1":
        requests.post("http://localhost:25565/XML",data = xml)
    elif datacache['xml']['Directory'] == "Directory 2":
        requests.post("http://localhost:50001/XML",data = xml)
    else:
        return 400

if __name__ == '__main__':
    app.run(debug = True, port = 5000)


如果需要,很高兴提供额外的信息。

最佳答案

发生错误是因为视图未返回有效响应。

如果成功处理了请求,则不会指定任何响应,因此该函数将返回None,这不是有效的响应。

如果未成功处理请求,则该函数将返回整数400,该整数也不是有效的响应。

对于一个API来说,仅返回一个HTTP状态代码就足够了,因此该函数可以返回一个空字符串以获取成功-这将导致200 OK响应-或一个空字符串和状态码用于不成功的请求。您可以了解有关烧瓶响应here的更多信息。

此代码应工作:

@app.route("/XMLhandling", methods=["POST"])
def handleXML():
    #for debugging..
    if True:
        print("HEADERS", request.headers)
        print("REQ_path", request.path)
        print("ARGS", request.args)
        print("DATA", request.data)
        print("FORM",request.form)
    #parse the XML
    datacache = xmltodict.parse(request.form)
    print(datacache)
    print(datacache['xml']['Directory'])
    if datacache['xml']['Directory'] == "Directory 1":
        requests.post("http://localhost:25565/XML",data = xml)
    elif datacache['xml']['Directory'] == "Directory 2":
        requests.post("http://localhost:50001/XML",data = xml)
    else:
        # Return empty response body and status code.
        return '', 400
    # Return empty body (Flask will default to 200 status code)
    return ''

关于python - Flask引发TypeError: View 函数未返回有效响应,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54101449/

10-15 01:24
查看更多