5

TL;博士

哪些库/调用可用于处理包含与 parse_qs 不同的分号的查询字符串?

>>> urlparse.parse_qs("tagged=python;ruby")
>>> {'tagged': ['python']}

完整背景

我正在使用 StackExchange API 来搜索标记的问题。

搜索的布局是这样的,标签用分号分隔:

/2.1/search?order=desc&sort=activity&tagged=python;ruby&site=stackoverflow

与 API 交互就好了。当我想测试调用时,问题就出现了,特别是在使用httpretty模拟 HTTP 时。

在引擎盖下,httpretty使用urlparse.parse_qspython 标准库来解析查询字符串。

>>> urlparse.parse_qs("tagged=python;ruby")
{'tagged': ['python']}

显然这并不好。这是一个小例子,这里是 httpretty 的一个片段(在测试上下文之外)。

import requests
import httpretty

httpretty.enable()

httpretty.register_uri(httpretty.GET, "https://api.stackexchange.com/2.1/search", body='{"items":[]}')
resp = requests.get("https://api.stackexchange.com/2.1/search", params={"tagged":"python;ruby"})
httpretty_request = httpretty.last_request()
print(httpretty_request.querystring)

httpretty.disable()
httpretty.reset()

我想使用 httpretty 的机器,但需要一个解决方法parse_qs。我现在可以修补 httpretty,但很想看看还能做什么。

4

1 回答 1

1

为了解决这个问题,我暂时修补了httpretty.core.unquote_utf8(技术上httpretty.compat.unquote_utf8)。

#
# To get around how parse_qs works (urlparse, under the hood of
# httpretty), we'll leave the semi colon quoted.
# 
# See https://github.com/gabrielfalcao/HTTPretty/issues/134
orig_unquote = httpretty.core.unquote_utf8
httpretty.core.unquote_utf8 = (lambda x: x)

# It should handle tags as a list
httpretty.register_uri(httpretty.GET,
                       "https://api.stackexchange.com/2.1/search",
                       body=param_check_callback({'tagged': 'python;dog'}))
search_questions(since=since, tags=["python", "dog"], site="pets")

...

# Back to normal for the rest
httpretty.core.unquote_utf8 = orig_unquote
# Test the test by making sure this is back to normal
assert httpretty.core.unquote_utf8("%3B") == ";"

这假设您不需要任何其他未引用的内容。另一种选择是只在分号到达parse_qs.

于 2014-01-03T21:37:47.670 回答