Parse uuid from parameterized route path in falcon

453 Views Asked by At

I have a falcon app with a parameterized route for getting resources. The user does not know the uuid of the resource because it is temporary, so a redirect is needed.

The user will make a GET /transaction request, and a redirect to the returned path of 302 found response.

How can I parse the uuid from the request path?

The app would look like this:

api = falcon.API()
api.add_route('/transaction', Transaction)
api.add_route('/transaction/{id}', TransactionItem))

And the recources something like this:

class Transaction(object):    

    def on_get(self, req, resp):     
        id = get_current_id()
        resp.status = falcon.HTTPFound('/TransactionItem/{}'.format(id))

class TransactionItem(object):
    def on_get(self, req, resp):
        // Parse id from path?
        transaction = get_transaction(id)
        // ...
        // include info in the response, etc
        resp.status = falcon.HTTP_200
1

There are 1 best solutions below

0
On BEST ANSWER

Ok so.

Flacon passes the matched route fields as a keywords arguments. That means thats in Your TransactionItem class Your on_get must have one of the (You can chose one which is more clear for You) given definitions :

# 1st way
def on_get(self, req, resp, id=None):
    ...

# 2nd way (**kwargs catches all keywords args)
def on_get(self, req, resp, **kwargs):
    id = kwargs.get('id')

The passed field will be dafault passed as str if You want to have it converted by falcon You can use the builtin in Falcon UUIDConverter

Here the docs for converter : https://falcon.readthedocs.io/en/stable/api/routing.html#falcon.routing.UUIDConverter