Search code examples
pythongetcherrypy

CherryPy only receiving 1st query string parameter


I've just begun my journey into the realms of the CherryPy module in Python. It's pretty awesome how easy it makes it to setup a server with a RESTful api, however I've ran into an issue. My code is only acknowledging the first parameter in a query string.

I want to make a GET request like so: curl -X GET 127.0.0.1:8080/api/sum/?a=2&b=3

My Python code is as follows:

import cherrypy

class getSum:
    exposed = True
    def GET(self, **params):
        a = float(params['a'])
        b = float(params['b'])
        return a+b

if __name__ == '__main__':
    cherrypy.tree.mount(getSum(), '/api/sum/', {'/': {'request.dispatch': cherrypy.dispatch.MethodDispatcher()}})
    cherrypy.engine.start()
    cherrypy.engine.block()

After fiddling with the code for a while I've come to the following diagnosis: When the query string is being read into params, instead of starting a new entry in the dictionary when it reaches the '&' it just stops instead.

Has anyone got any advice on how to read multiple parameters in as a single query string?

With Thanks, Sean.


Solution

  • The Python script posted in my question is actually a working implementation of what I wanted to do. The problem was instead with the curl request that I was making.

    The '&' character in my curl request was truncating my bash command, resulting in this: curl -X GET 127.0.0.1:8080/api/sum/?a=2

    The fix for this is to wrap my url in quotes like so: curl -X GET "127.0.0.1:8080/api/sum/?a=2&b=3"

    When executing this command 5.0 is returned to the terminal, as expected.

    This following post contains a useful discussion on the use of ampersands in curl requests: How to include an '&' character in a bash curl statement