Test coverage report: permission.decorators.utils

# permission.decorators.utils: 94 total statements, 84.1% covered

Generated: Thu 2012-03-01 14:22 CST

Source file: /home/alisue/Dropbox/Codes/django-permission/permission/decorators/utils.py

Stats: 69 executed, 13 missed, 12 excluded, 73 ignored

1. `#!/usr/bin/env python`
2. `# vim: set fileencoding=utf-8 :`
3. `"""`
4. `Utils used in decorators`
5. ``
6. ``
7. `AUTHOR:`
8. `lambdalisue[Ali su ae] (lambdalisue@hashnote.net)`
9. ``
10. `License:`
11. `The MIT License (MIT)`
12. ``
13. `Copyright (c) 2012 Alisue allright reserved.`
14. ``
15. `Permission is hereby granted, free of charge, to any person obtaining a copy`
16. `of this software and associated documentation files (the "Software"), to`
17. `deal in the Software without restriction, including without limitation the`
18. `rights to use, copy, modify, merge, publish, distribute, sublicense, and/or`
19. `sell copies of the Software, and to permit persons to whom the Software is`
20. `furnished to do so, subject to the following conditions:`
21. ``
22. `The above copyright notice and this permission notice shall be included in`
23. `all copies or substantial portions of the Software.`
24. ``
25. `THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR`
26. `IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,`
27. `FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE`
28. `AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER`
29. `LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING`
30. `FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS`
31. `IN THE SOFTWARE.`
32. ``
33. `"""`
34. `from __future__ import with_statement`
35. `import time`
36. `import datetime`
37. `import urlparse`
38. `from django.conf import settings`
39. `from django.http import Http404`
40. `from django.db.models.fields import DateTimeField`
41. `from django.shortcuts import get_object_or_404`
42. `from django.contrib.auth import REDIRECT_FIELD_NAME`
43. `from permission.exceptions import ValidationError`
44. ``
45. `try:`
46. `from django.utils import timezone`
47. `datetime_now = timezone.now`
48. `except ImportError:`
49. `datetime_now = datetime.datetime.now`
50. ``
51. `def redirect_to_login(request, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME):`
52. `"""redirect to login"""`
53. `path = request.build_absolute_uri()`
54. `# if the login url is the same scheme and net location then just`
55. `# use the path as the "next" url.`
56. `login_scheme, login_netloc = urlparse.urlparse(login_url or settings.LOGIN_URL)[:2]`
57. `current_scheme, current_netloc = urlparse.urlparse(path)[:2]`
58. `if ((not login_scheme or login_scheme == current_scheme) and`
59. `(not login_netloc or login_netloc == current_netloc)):`
60. `path = request.get_full_path()`
61. `from django.contrib.auth.views import redirect_to_login as auth_redirect_to_login`
62. `return auth_redirect_to_login(path, login_url, redirect_field_name)`
63. ``
64. `def get_object_from_classbased_instance(instance, queryset, request, *args, **kwargs):`
65. `"""get object from an instance of classbased generic view"""`
66. `# initialize request, args, kwargs of classbased_instance`
67. `# most of methods of classbased view assumed these attributes`
68. `# but these attributes is initialized in ``dispatch`` method.`
69. `instance.request = request`
70. `instance.args = args`
71. `instance.kwargs = kwargs`
72. ``
73. `# get queryset from class if ``queryset_or_model`` is not specified`
74. `if hasattr(instance, 'get_queryset') and not queryset:`
75. `queryset = instance.get_queryset()`
76. `elif hasattr(instance, 'queryset') and not queryset:`
77. `queryset = instance.queryset`
78. `elif hasattr(instance, 'model') and not queryset:`
79. `queryset = instance.model._default_manager.all()`
80. ``
81. `# get object`
82. `if hasattr(instance, 'get_object'):`
83. `obj = instance.get_object(queryset)`
84. `elif hasattr(instance, 'object'):`
85. `obj = instance.object`
86. `else:`
87. `obj = None`
88. `return obj`
89. ``
90. `def get_object_from_list_detail_view(request, *args, **kwargs):`
91. `"""get object from generic list_detail.detail view"""`
92. `queryset = kwargs['queryset']`
93. `object_id = kwargs.get('object_id', None)`
94. `slug = kwargs.get('slug', None)`
95. `slug_field = kwargs.get('slug_field', 'slug')`
96. `if object_id:`
97. `obj = get_object_or_404(queryset, pk=object_id)`
98. `elif slug and slug_field:`
99. `obj = get_object_or_404(queryset, **{slug_field: slug})`
100. `else:`
101. `raise AttributeError(`
102. `"Generic detail view must be called with either an "`
103. `"object_id or a slug/slug_field."`
104. `)`
105. `return obj`
106. `def _get_object_from_list_detail_view_validation(request, *args, **kwargs):`
107. `if 'queryset' not in kwargs:`
108. `return False`
109. `elif 'object_id' not in kwargs and 'slug' not in kwargs:`
110. `return False`
111. `return True`
112. `get_object_from_list_detail_view.validate = _get_object_from_list_detail_view_validation`
113. ``
114. ``
115. `def get_object_from_date_based_view(request, *args, **kwargs):`
116. `"""get object from generic date_based.detail view"""`
117. `year, month, day = kwargs['year'], kwargs['month'], kwargs['day']`
118. `month_format = kwargs.get('month_format', '%b')`
119. `day_format = kwargs.get('day_format', '%d')`
120. `date_field = kwargs['date_field']`
121. `queryset = kwargs['queryset']`
122. `object_id = kwargs.get('object_id', None)`
123. `slug = kwargs.get('slug', None)`
124. `slug_field = kwargs.get('slug_field', 'slug')`
125. ``
126. `try:`
127. `tt = time.strptime(`
128. `'%s-%s-%s' % (year, month, day),`
129. `'%s-%s-%s' % ('%Y', month_format, day_format)`
130. `)`
131. `date = datetime.date(*tt[:3])`
132. `except ValueError:`
133. `raise Http404`
134. ``
135. `model = queryset.model`
136. ``
137. `if isinstance(model._meta.get_field(date_field), DateTimeField):`
138. `lookup_kwargs = {`
139. `'%s__range' % date_field: (`
140. `datetime.datetime.combine(date, datetime.time.min),`
141. `datetime.datetime.combine(date, datetime.time.max),`
142. `)}`
143. `else:`
144. `lookup_kwargs = {date_field: date}`
145. ``
146. `now = datetime_now()`
147. `if date >= now.date() and not kwargs.get('allow_future', False):`
148. `lookup_kwargs['%s__lte' % date_field] = now`
149. `if object_id:`
150. `lookup_kwargs['pk'] = object_id`
151. `elif slug and slug_field:`
152. `lookup_kwargs['%s__exact' % slug_field] = slug`
153. `else:`
154. `raise AttributeError(`
155. `"Generic detail view must be called with either an "`
156. `"object_id or a slug/slug_field."`
157. `)`
158. `return get_object_or_404(queryset, **lookup_kwargs)`
159. `def _get_object_from_date_based_view_validation(request, *args, **kwargs):`
160. `if 'queryset' not in kwargs:`
161. `return False`
162. `elif 'year' not in kwargs or 'month' not in kwargs or 'day' not in kwargs:`
163. `return False`
164. `elif 'object_id' not in kwargs and 'slug' not in kwargs:`
165. `return False`
166. `return True`
167. `get_object_from_date_based_view.validate = _get_object_from_date_based_view_validation`