9b45a3207fe89478cd6701a27abd6fb9f3afdfbb
[redakcja.git] / apps / api / utils.py
1 # -*- encoding: utf-8 -*-
2
3 __author__ = "Ɓukasz Rekucki"
4 __date__ = "$2009-09-20 21:48:03$"
5 __doc__ = "Module documentation."
6
7
8 from functools import wraps
9 from piston.emitters import Emitter
10 from piston.utils import rc
11
12 import api.response
13
14 import wlrepo
15 import settings
16
17 class TextEmitter(Emitter):
18     def render(self, request):
19         return unicode(self.construct())
20
21 Emitter.register('raw', TextEmitter, 'text/plain; charset=utf-8')
22 Emitter.register('rawhtml', TextEmitter, 'text/html; charset=utf-8')
23 Emitter.register('rawxml', TextEmitter, 'application/xml; charset=utf-8')
24
25 class DjangoAuth(object):
26
27     def is_authenticated(self, request):
28         return request.user.is_authenticated()
29
30     def challenge(self):
31         return rc.FORBIDDEN
32
33
34 def validate_form(formclass, source='GET'):
35   
36     def decorator(func):
37         @wraps(func)
38         def decorated(self, request, * args, ** kwargs):
39             form = formclass(getattr(request, source), request.FILES)
40
41             if not form.is_valid():
42                 errorlist = [{'field': k, 'errors': str(e)} for k, e in form.errors.items()]
43                 return api.response.BadRequest().django_response(errorlist)
44
45             kwargs['form'] = form
46             return func(self, request, * args, ** kwargs)
47         return decorated
48     return decorator
49     
50 def hglibrary(func):
51     @wraps(func)
52     def decorated(self, *args, **kwargs):
53         l = wlrepo.open_library(settings.REPOSITORY_PATH, 'hg')
54         kwargs['lib'] = l
55         return func(self, *args, **kwargs)
56     return decorated
57
58
59
60 import re
61 NAT_EXPR = re.compile(r'(\d+)', re.LOCALE | re.UNICODE)
62 def natural_order(get_key=lambda x: x):
63     def getter(key):
64         key = [int(x) if n%2 else x for (n,x) in enumerate(NAT_EXPR.split(get_key(key))) ]
65         return key
66
67     return getter
68