如何在裸露的函数中强制转换参数? [英] How to cast parameters in exposed functions cherrypy?

查看:30
本文介绍了如何在裸露的函数中强制转换参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我有一个公开的功能,例如:

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)

有没有一种方法可以自动将价格转换为浮动价格,将金额转换为int并将说明转换为str.如果其中任何一个失败,则将其视为错误.

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.

推荐答案

没有内置解决方案,但是cherrypy的工具提供了一个足以满足需要的钩子.这是一个

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):

如果您很幸运地编写了仅Python 3的代码,则函数注释将提供一个更加优雅的解决方案.

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

更新:自版本 6.2 .

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

这篇关于如何在裸露的函数中强制转换参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆