如何使用httpx查询PostgREST?解决URL编码报错问题
使用httpx正确调用PostgREST的Operator Modifiers查询
问题场景
PostgREST官方文档中首个「Operator Modifiers」示例的curl命令如下:
curl "http://localhost:3000/people?last_name=like(any).{O*,P*}"
但使用Python的httpx模块复现时,URL会被自动编码。执行以下代码:
import httpx r = httpx.get("http://localhost:3000/people?last_name=like(any).{O*,P*}") print(r.url)
得到的编码后URL为:
URL('http://localhost:3000/people?last_name=like(any).%7BO*,P*%7D')
此时PostgREST返回错误:
{'code': '22P02', 'details': 'Expected ":", but found "}".', 'hint': None, 'message': 'invalid input syntax for type json'}
解决方案
不要直接将查询参数拼接在URL字符串中,改用httpx的params参数传递查询条件,这样能让PostgREST正确识别未编码的花括号格式:
import httpx params = {"last_name": "like(any).{O*,P*}"} r = httpx.get("http://localhost:3000/people", params=params) print(r.url)
这种方式生成的URL会保留PostgREST所需的语法结构,服务端能正常解析查询条件,不会触发JSON语法错误。
原理说明
使用params参数时,httpx会按照PostgREST的预期规则处理特殊字符,避免不必要的编码破坏查询语句的结构。
内容的提问来源于stack exchange,提问作者bugmenot123
相关产品推荐
相关产品推荐

