簡體   English   中英

是否有處理分號的parse_qs的替代方案?

[英]Is there an alternative to parse_qs that handles semi-colons?

TL; DR

哪些庫/調用可用於處理包含分號的查詢字符串與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正在使用python標准庫中的urlparse.parse_qs來解析查詢字符串。

>>> 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,但是很想看看還能做些什么。

為了解決這個問題,我暫時修補了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到達parse_qs之前保留百分比編碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM