RT.
刚学2天……
每一个请求中都要用一大堆if 去判断传进来的参数是否合理,有没有什么简单的方法去处理?
刚学2天……
每一个请求中都要用一大堆if 去判断传进来的参数是否合理,有没有什么简单的方法去处理?
|
1
封装成一个独立的方法呗,
|
|
2
装饰器
|
|
batman2010Apr 15, 2015
3
用一个数组把所有合法值封起来。
|
|
batman2010Apr 15, 2015
4
@batman2010 看错要求了,sorry
|
|
5
如果是面向对象的语言,尽量把参数封装成自定义的类,然后在类构造的时候检查,类还可以提供类似 isValidForXXX() 的方法作特殊的检查。
|
|
SeptembersApr 15, 2015
7
|
|
loadingApr 15, 2015 via iPhone
8
把判断写到一个函数里调用,这样一般情况下就看不到了,等发现更好方法时,再修改那个函数。
你没代码,帮不到你。 |
|
gkiwiApr 15, 2015
9
听楼主的意思像是前端post过来数据,需要不停的写if来进行判断.
说实话,没有太好的方法. 不过,而一些较为通用的规则,比如不能为空啊,必须为数字之类的可以封装成装饰器~ 我的某个not_empty: https://gist.github.com/5d84822a5b0d707c53d8.git 不过wtforms也许会对你有些帮助. https://wtforms.readthedocs.org/en/latest/ |
|
gkiwiApr 15, 2015
10
上个git貌似打不开,可以瞅下我的代码: https://gist.github.com/bugkiwi/5d84822a5b0d707c53d8
|
|
11
🌰
``` @bp.route('/order/comment',methods=['GET','POST']) @login_required @not_empty('orderId',POST=['servicesc','envsc','tastesc','foods']) def order_comment(): pass ``` |
|
13
FYI 可以参考一下 WTForm 这种声明式的方法来做,会好看很多(也好维护)
|
|
15
schema、marshmallow
|
|
16
大量的if else基本可以用decorator模式或chain of responsibility来代替
|
|
17
可以看看 voluptuous https://github.com/alecthomas/voluptuous
|
|
FastMemApr 15, 2015
18
封装, PHP function is_chinese($value) {//Do}
然后用的时候这样 if(is_chinses($_POST['Comments'])) {} else {} |
|
RichardzhibuApr 15, 2015
19
我一般把参数类型分类,比如int、 uint、long、float、str、mail、url、password,然后把业务规则分配到到这些类型里
|
|
FrankFang128Apr 15, 2015
20
表编程
|
|
C0VNApr 15, 2015
21
什么样的请求参数?
可以用 **kwds 参数传递来接受参数 python判断流程可以用 try...except... |
|
laike9mApr 15, 2015
22
贴代码吧,说不定真正的问题并不出在if else上面
|
|
OpooPagesApr 15, 2015 via iPad
23
适配器模式。
|
|
messenseApr 15, 2015
24
可以试试用 JSON Schema 描述校验,用 https://github.com/sunlightlabs/validictory 这个库校验。
|
|
saber000Apr 15, 2015
25
@messense JSON Schema更多的文档可以看这里:http://spacetelescope.github.io/understanding-json-schema/
这种方法很推荐,现在基本上已经成为我的标准方法.具体有多爱呢,我基于JSON Schema写了一个序列化任意Python对象的库,不要脸发出来求指教. |
|
virusdefenderApr 16, 2015
26
参考django的form或者django rest framework的serializer 就是写一个类,里面写明字段和验证方法,然后进行验证
|
|
kzzhrApr 16, 2015
27
可以在某些地方放一些规则,比如正则。然后用循环的方式依次判断。
这样可以吧。。随口说的莫喷。。。 |
|
m_zApr 16, 2015
28
前端验证呢?不通过不提交...
|
|
29
|
|
CatstyleApr 16, 2015
30
@gkiwi
if params is None and params == [] and len(kargs) == 0: raise Exception("You should give me some params;") 这个判断确定能跑过? 前两个有什么情况能为True? |
|
MarioLuisGarciaApr 16, 2015
32
定义里是kkargs, 判断里是kargs了啊
|
|
33
http://simeonfranklin.com/blog/2012/jul/1/python-decorators-in-12-steps/
楼主如果想看看装饰器作 类型限制的话可以看看这个. 当时我连decorator是啥都不知道呢, 看完这个就多少明白了. |
|
ligyxyJul 15, 2015
34
property装饰器
|