Search code examples
falconframework

Multiple parameters to falcon service


I have a falcon script that I am trying to pass multiple parameters to:

import falcon
import random
import os
import time


waitTime = int(os.environ.get('WAIT_TIME', '2'))

class SomeFunc(object):
    def on_get(self, req, response):
        req.path, _, query = req.relative_uri.partition('?')
        query = falcon.uri.decode(query)
        decoded_params = falcon.uri.parse_query_string(query, keep_blank=True, csv=False)
        print(decoded_params)

    ...


api = falcon.API()
api.add_route('/func', SomeFunc())

I need to pass n parameters to this service. However, when I call it:

curl localhost:8000/servicedb?limit=12&time=1

It prints out just the first parameter:

{'limit': '12'}

What is the correct code on the client/server to get all parameters?


Solution

  • First of all, it looks like your Falcon code does what you expect it to, just (depending on the shell you use) you most likely forgot to escape the curl invocation, which essentially forks a shell command time=1.

    See also: How to include an '&' character in a bash curl statement.

    Sending the request as

    curl "http://localhost:8000/func?limit=12&time=1"
    

    I get the below output:

    {'limit': '12', 'time': '1'}
    

    In addition, while not directly causing any problems, you don't really need to manually parse the URI that way. Simple reference req.params to get obtain all parameters at once, or use the specialized req.get_param_*() methods to get the value of a single parameter.

    For example:

    import falcon
    
    
    class SomeFunc(object):
        def on_get(self, req, response):
            print(req.params)
            print(req.get_param_as_int('limit'))
    
    
    app = falcon.App()
    app.add_route('/func', SomeFunc())
    

    now prints:

    {'limit': '12', 'time': '1'}
    12