gil9red Asked:2022-08-02 17:29:36 +0000 UTC2022-08-02 17:29:36 +0000 UTC 2022-08-02 17:29:36 +0000 UTC 以flask为例,在web服务器中实现一个API来返回不同类型的数据 772 比如让服务器返回客户端的IP 以html形式返回,如何以json和xml形式返回? import logging from flask import Flask, request app = Flask(__name__) logging.basicConfig(level=logging.DEBUG) @app.route('/') def index(): return request.remote_addr if __name__ == '__main__': app.run( host='0.0.0.0', port=5000 ) python 1 个回答 Voted Best Answer gil9red 2022-08-02T17:29:36Z2022-08-02T17:29:36Z 要flask返回数据json就足够了,例如返回一个字典,让它成为{'ip': request.remote_addr} 并根据flask需要xml返回字符串/字节并指定类型,例如,text/xml以便客户端了解来自服务器的数据类型。为此,您需要返回一个Response对象。xml您也可以自己生成字符串(类型为<ip>127.0.0.1</ip>),但我更喜欢通过库来生成,例如xml.etree.ElementTree 例子: import logging import xml.etree.ElementTree as ET from flask import Flask, request, Response app = Flask(__name__) logging.basicConfig(level=logging.DEBUG) @app.route('/') def index(): return request.remote_addr @app.route('/json') def get_json(): return { 'ip': request.remote_addr, } @app.route('/xml') def get_xml(): root = ET.Element('ip') root.text = request.remote_addr xml_bytes = ET.tostring(root, encoding="utf-8", xml_declaration=True) return Response(xml_bytes, mimetype='text/xml') if __name__ == '__main__': app.run( host='0.0.0.0', port=5000 ) 结果 让 ip 为 10.10.10.10),注意响应头Content-Type: http://10.10.10.10:5000/ (Content-Type: text/html; charset=utf-8): 10.7.8.31 http://10.10.10.10:5000/xml (Content-Type: text/xml; charset=utf-8): <?xml version='1.0' encoding='utf-8'?> <ip>10.7.8.31</ip> http://10.10.10.10:5000/json (Content-Type: application/json): {"ip":"10.7.8.31"}
要
flask返回数据json就足够了,例如返回一个字典,让它成为{'ip': request.remote_addr}并根据
flask需要xml返回字符串/字节并指定类型,例如,text/xml以便客户端了解来自服务器的数据类型。为此,您需要返回一个Response对象。xml您也可以自己生成字符串(类型为<ip>127.0.0.1</ip>),但我更喜欢通过库来生成,例如xml.etree.ElementTree例子:
结果
让 ip 为 10.10.10.10),注意响应头
Content-Type:http://10.10.10.10:5000/ (
Content-Type: text/html; charset=utf-8):http://10.10.10.10:5000/xml (
Content-Type: text/xml; charset=utf-8):http://10.10.10.10:5000/json (
Content-Type: application/json):