0

_GETURI のクエリ フィールドのクエリ キーと値のペアを含む辞書を生成して返す関数があります。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'
4

2 に答える 2

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'}

これが役立つことを願っています。

于 2011-10-19T16:39:59.060 に答える
0

query_parse() の代わりに、Python 独自のクエリ パーサーを使用します。

>>> 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 ステートメントを挿入することで簡単に確認できます。

于 2011-10-19T16:53:44.380 に答える