Search code examples
google-app-enginepython-2.xgoogle-app-engine-pythonurlparseurl-parsing

return value is always None in google-app-engine script


I am using the following code to parse url in google-app-engine script:

from urlparse import urlparse, parse_qs

def parse_url(url):
            parsed_url = urlparse(url)
            params = parse_qs(parsed_url.query)
            return params

class Handler(webapp2.RequestHandler):
     def get(self):      
        url = self.request.path_info
        params = parse_url(url)
        self.response.write(params) 

Params always None after calling the function. However, when using the exact same parsing code inside the handler (not as a function) - the parsing is good and I get a non-empty dictionary in params.

Any idea why it could happen?


Solution

  • The self.request.path_info value is not the full URL you need to be passing down to urlparse() to properly extract the params, it has the query parameters stripped off, which is why you get no parameters. It doesn't work inside the handler either, you may have done some additional changes since you tried that.

    To get the parameters using your parse_url() pass the full url:

        url = self.request.url
        params = parse_url(url)
    

    But you should note that all this is rather unnecessary, webapp2 already has a parameter parser included, except it returns a MultiDict. From Request data:

    params

    A dictionary-like object combining the variables GET and POST.

    All you have to do is convert it to a real dict identical to the one your parse_url() produces:

        self.response.write(dict(self.request.params))