Login

Validate request params without custom form

Author:
xiaoym
Posted:
April 23, 2013
Language:
Python
Version:
Not specified
Score:
0 (after 0 ratings)

When work at site api for android client, I found use form to validate user input is too complex, so I write this. usage:

@param('param_name', 'default_value', validate_func) def api_func(request): # access cleaned data. param_name = request.DATA['param_name']

JsonResponse is my class. replace with HttpResponse or whatever

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
time_from = lambda x : datetime.fromtimestamp(long(x is not None and x or '0'))
time_to = lambda x : x is not None and datetime.fromtimestamp(long(x)) or datetime.now()
void = lambda x : x

def param(key, default, validate):
    def decorator(view_func):
        @wraps(view_func, assigned = available_attrs(view_func))
        def _wrapped_view(request, *args, **kwargs):
            try:
                value = request.REQUEST.get(key, default)
                value = validate(value)

                if hasattr(request, 'DATA'):
                    dct = getattr(request, 'DATA')
                    dct.update({key : value})
                else:
                    dct = {key: value}
                
                setattr(request, 'DATA', dct)
                
            except ValueError, e:
                return JsonResponse(error = -3, error_msg = u'参数%s格式错误' % key)
            except TypeError, e:
                return JsonResponse(error = -4, error_msg = u'参数%s不能为空' % key)
            
            return view_func(request, *args, **kwargs)
        
        return _wrapped_view
    
    return decorator

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 2 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 2 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 9 months, 2 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 10 months, 1 week ago
  5. Help text hyperlinks by sa2812 11 months ago

Comments

Please login first before commenting.