Flask引发类型错误:视图函数没有返回有效的响应

2024-07-03 07:11:09 发布

您现在位置:Python中文网/ 问答频道 /正文

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

主要的问题是,我在使用烧瓶的时候总是出错500次请求数据或者请求.窗体-根据其他类似的帖子,这些方法中的一种应该与XML一起工作。在

常见的500错误解释是“TypeError:view函数没有返回有效的响应。该函数要么未返回任何值,要么在没有返回语句的情况下结束。“

我尝试过基于其他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烧瓶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) 

乐意提供额外的信息,如果需要。在


Tags: importapiappflaskdataif烧瓶request
1条回答
网友
1楼 · 发布于 2024-07-03 07:11:09

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

如果请求处理成功,则没有指定响应,因此函数将返回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 ''

相关问题 更多 >