Moki
Moki

Reputation: 199

Passing multiple parameters in url using cherrypy

I would like to send GET request with url like this "/api/stats?ad_ids=1,2,3&start_time=2013-09-01&end_time=2013-10-01" but I do not know how to mount my class to this url. I am using cherrypy mount method and MethodDispatcher. So far I managed to call GET method from this url api/stats/1.

Also what parameters should I pass to the GET method?

I would very appreciate any suggestion or comment?

Here are the code samples:

cherrypy.tree.mount(
    Ads(), '/api/stats',
    {'/':
        {'request.dispatch': cherrypy.dispatch.MethodDispatcher()}
    }
)


def GET(self,ad_id=None,*args, **kwargs):



    jsonData1={}


    jsonData = self.readData()

    counter2 = 0
    for item in jsonData:

        index = jsonData[item][2]


        if index==ad_id:

            jsonData1[counter2] = jsonData[item]
            counter2 += 1



    print jsonData1
    return ('Here is the stat %s')%(jsonData1)

Thank you in advance!

BR,

Momir

Upvotes: 0

Views: 3493

Answers (1)

cyraxjoe
cyraxjoe

Reputation: 5741

The query string can be reached with keyword arguments for the GET method.

Using your method you can access them with the dictionary kwargs.

cherrypy.tree.mount(
    Songs(), '/api/stats',
    {'/':
        {'request.dispatch': cherrypy.dispatch.MethodDispatcher()}
    }
)

def GET(self,ad_id=None,*args, **kwargs):
    start_time = kwargs.get('start_time', None)
    end_time = kwargs.get('end_time', None)
    # you can also use kwargs['XXX']
    # or do lookups with 'XXX' in kwargs
    # or set (start_time=None, end_time=None) at the signature
    # as a keyword argument.
    jsonData1={}
    jsonData = self.readData()
    counter2 = 0
    for item in jsonData:
        index = jsonData[item][2]
        if index==ad_id:
            jsonData1[counter2] = jsonData[item]
            counter2 += 1
    print jsonData1
    return ('Here is the stat %s')%(jsonData1)

Also, *args will contain any positional argument for any additional segment of the URL for example /api/stats/1/a/b/c will create args=('a', 'b', 'c')

Upvotes: 3

Related Questions