Vans S
Vans S

Reputation: 1813

How to cast parameters in exposed functions cherrypy?

For example I have a exposed function like:

@cherrypy.expose
def create_purchase(self, price, amount, description):

    price = float(price)
    amount = int(amount)
    descript = str(description)

Is there a way to automatically cast price to float, amount to int, and description to str. If any of them fail consider it an error.

Upvotes: 1

Views: 517

Answers (1)

A. Coady
A. Coady

Reputation: 57338

There's no builtin solution, but cherrypy's tools provide a hook which could suffice. Here's an example hook called params. Which would be used like this:

@cherrypy.expose
@params(price=float, amount=int, description=str)
def create_purchase(self, price, amount, description):

And if you're fortunate enough to be writing Python 3-only code, function annotations would provide an even more elegant solution.

Update: This has been built-in since version 6.2.

@cherrypy.tools.params()
def create_purchase(self, price: float, amount: int, description):

Upvotes: 2

Related Questions