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