Search code examples
pythongoogle-app-engineurlurlparse

Getting the Parameter name of a Value in a URL request


I have a Python App Engine web app class that I am accessing with the following POST url: http://localhost:8087/moderate?5649364211118945661=on

How can I get the Parameter name - not the value of the 5649364211118945661parameter, but a list of all the parameter names that contain the on value.

For example, in the following url:

http://localhost:8087/moderate?5649364211118945661=on&23984729386481734=on&456287432349725=on&6753847523429875=off

how can I extract this:

['5649364211118945661', '23984729386481734', '456287432349725']

Thanks very much.


Solution

  • Use urlparse, http://docs.python.org/library/urlparse.html.

    import urlparse
    url = urlparse.urlparse('http://localhost:8087/moderate?5649364211118945661=on&23984729386481734=on&456287432349725=on&6753847523429875=off')
    query = urlparse.parse_qs(url.query)
    print [key for key, value in query.iteritems() if value == 'on']
    

    If you are talking about an incoming URL on Google App Engine, use

    args_on = [arg for arg in self.request.arguments() if self.request.get(arg) == 'on']