访问返回的dict密钥,同时按预期解析为值,会触发KeyError?

时间:2011-10-19 16:30:20

标签: python basehttprequesthandler

我有一个生成并返回_GET字典的函数,该字典包含URI查询字段的查询键/值对。假设URI为http://127.0.0.1/path/to/query?foo=bar&bar=foo,则在带有标记为BaseHTTPServer.BaseHTTPRequestHandler的派生KeyError内使用此函数:

class HTTPHandler(BaseHTTPServer.BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200)
        self.send_header("Content-Type", "text/plain")
        self.end_headers()

        _GET = query_parse(urlparse.urlparse(self.path).query)

        # No KeyError here..
        print "foo: %s\r\nbar: %s" % (GET["foo"], _GET["bar"])

        # KeyError on _GET["foo"]..
        self.wfile.write("foo: %s\r\nbar: %s\r\n" % (_GET["foo"], _GET["bar"]))

        # Still KeyError on _GET["foo"] even if commenting above line
        # and uncommenting below one!
        #self.wfile.write("bar: %s\r\nfoo: %s\r\n" % (_GET["bar"], _GET["foo"]))

回溯:

localhost - - [19/Oct/2011 18:21:18] "GET /path/to/query?foo=bar&bar=foo HTTP/1.1" 200 -
localhost - - [19/Oct/2011 18:21:18] "GET /favicon.ico HTTP/1.1" 200 -
Traceback (most recent call last):
  File "E:\Program\Python27\lib\SocketServer.py", line 284, in _handle_request_noblock
    self.process_request(request, client_address)
  File "E:\Program\Python27\lib\SocketServer.py", line 310, in process_request
    self.finish_request(request, client_address)
  File "E:\Program\Python27\lib\SocketServer.py", line 323, in finish_request
    self.RequestHandlerClass(request, client_address, self)
  File "E:\Program\Python27\lib\SocketServer.py", line 639, in __init__
    self.handle()
  File "E:\Program\Python27\lib\BaseHTTPServer.py", line 337, in handle
    self.handle_one_request()
  File "E:\Program\Python27\lib\BaseHTTPServer.py", line 325, in handle_one_request
    method()
  File "http-test.py", line 40, in do_GET
    print "foo: %s" % _GET["foo"]
KeyError: 'foo'

2 个答案:

答案 0 :(得分:1)

我不知道你的query_parse函数做了什么,但是已经有一个函数执行urlparse.parse_qs

>>> query = urlparse.urlparse('http://127.0.0.1/path/to/query?foo=bar&bar=foo').query
>>> urlparse.parse_qs(query)
{'bar': ['foo'], 'foo': ['bar']}

或者,如果你不喜欢字典的值列表,你可以这样做:

>>> dict(urlparse.parse_qsl(query))
{'bar': 'foo', 'foo': 'bar'}

希望这可以提供帮助。

答案 1 :(得分:0)

使用Python自己的查询解析器而不是query_parse():

>>> s = 'http://127.0.0.1/path/to/query?foo=bar&bar=foo'
>>> t = urlparse.urlparse(s)
>>> urlparse.parse_qs(t.query)
{'foo': ['bar'], 'bar': ['foo']}

使用pdb或插入print语句以帮助调试很容易看到。