About example code from google

2019-09-20 11:11发布

Why is this done

uri = urlparse(self.request.uri)
if uri.query:
    query = parse_qs(uri.query)
    try:
        query = query['query'][0]
    except KeyError, err:
        query = ''

And not simply this

query = self.request.get('query')

? What will the difference be between to two code blocks?

Source. https://code.google.com/p/google-app-engine-samples/source/browse/trunk/search/python/search_demo.py?r=157

1条回答
神经病院院长
2楼-- · 2019-09-20 11:57

There's a few differences. The biggest is if the key query appears multiple times in the uri, the first version will return the first instance while the second version will return the last instance.

Also, in the second version, if the key doesn't exist you'll get None instead of ''

Potentially the author of v1 just didn't trust webob to parse his query string properly.

查看更多
登录 后发表回答