如何读取CSV文件数据并生成指定结构的键值对列表作为接口返回值
解决方案
代码修改点
- 移除全局
output变量,将其移入路由函数内部,避免多次请求时数据重复累加 - 匹配到符合邮编的行时,直接构造
suburb和services为键的字典存入列表,符合键值对格式要求 - 新增响应头设置,指定返回格式为JSON,方便接口调用方解析
- 同时提供类表格文本格式的返回方案,可按需选择
修改后的完整代码
from bottle import html_quote, route, run, template, response, request import petl as etl from json import dumps import csv # 服务启动时预读取CSV文件,仅加载一次 reading_file = etl.fromcsv('vet_service_locations.csv') @route('/getServices') def details(): postcode = request.query.postcode output = [] # 遍历匹配对应邮编的数据 for row in reading_file: if row[2] == postcode: # 构造指定键的键值对 output.append({ "suburb": row[1], "services": row[4] }) # 以下两种返回逻辑二选一即可 # 方案1:返回标准JSON格式(键值对格式) response.content_type = 'application/json' return dumps(output, ensure_ascii=False) # 方案2:返回类表格文本格式 # response.content_type = 'text/plain; charset=utf-8' # table_header = "suburb, services\n" # table_content = "\n".join([f"{item['suburb']}, {item['services']}" for item in output]) # return table_header + table_content run(host='localhost', port=3000, debug=True)
输出效果
方案1 JSON格式输出
[ {"suburb": "Adelaide", "services": "Small_Animal"}, {"suburb": "Adelaide", "services": "Oncology"}, {"suburb": "Adelaide", "services": "Surgery"}, {"suburb": "Adelaide", "services": "Annual_Checkup"}, {"suburb": "Adelaide", "services": "Wildlife"} ]
方案2 类表格文本格式输出
suburb, services Adelaide, Small_Animal Adelaide, Oncology Adelaide, Surgery Adelaide, Annual_Checkup Adelaide, Wildlife
内容的提问来源于stack exchange,提问作者Sharanjeet Singh
相关产品推荐
相关产品推荐

