如何修改Sanic接口代码以返回无括号的键值对格式订单数据
解决Sanic接口返回指定纯文本格式订单数据的方法
核心思路是:将数据库查询结果逐条格式化为你需要的字符串格式,再用换行符拼接成纯文本内容,最后以text/plain类型返回响应。
具体实现步骤及代码示例
假设你原本的接口代码是类似这样的:
from sanic import Sanic, response import psycopg2 app = Sanic("OrderService") @app.route("/orders") async def get_orders(request): conn = psycopg2.connect("dbname=your_db user=your_user password=your_pass host=your_host") cur = conn.cursor() cur.execute("SELECT id, name, order, status, time FROM orders_view") orders = cur.fetchall() cur.close() conn.close() # 原返回JSON数组 return response.json(orders)
修改后即可得到预期格式:
from sanic import Sanic, response import psycopg2 from psycopg2.extras import DictCursor # 可选,用字典格式更直观 app = Sanic("OrderService") @app.route("/orders") async def get_orders(request): conn = psycopg2.connect("dbname=your_db user=your_user password=your_pass host=your_host") # 使用DictCursor让查询结果返回字典,方便通过字段名取值 cur = conn.cursor(cursor_factory=DictCursor) cur.execute("SELECT id, name, order, status, time FROM orders_view") orders = cur.fetchall() cur.close() conn.close() # 逐条格式化订单数据 formatted_lines = [] for order in orders: # 处理空值(可选,根据实际需求调整) name_val = order["name"] if order["name"] is not None else "无" line = f"id:{order['id']}, name:{name_val}, order:{order['order']}, status:{order['status']}, time:{order['time']}" formatted_lines.append(line) # 用换行符拼接所有行 result_text = "\n".join(formatted_lines) # 返回纯文本响应,指定Content-Type避免被解析为JSON return response.text(result_text)
关键注意点
- 如果不想用
DictCursor,也可以直接用元组索引取值,但要确保SELECT语句的字段顺序和格式化字符串的字段顺序完全对应,避免值错位。 - 若字段可能存在
NULL值,建议添加空值处理逻辑,避免输出异常内容。 - 必须用
response.text()返回,而不是response.json()或response.html(),确保响应头的Content-Type为text/plain,浏览器或客户端会直接按纯文本解析。
内容的提问来源于stack exchange,提问作者N Studio
相关产品推荐
相关产品推荐

