Moved Node and View documentation from rst files to the source file.
[philo.git] / philo / models / nodes.py
1 from inspect import getargspec
2
3 from django.contrib.contenttypes import generic
4 from django.contrib.contenttypes.models import ContentType
5 from django.contrib.sites.models import Site, RequestSite
6 from django.core.exceptions import ValidationError
7 from django.core.servers.basehttp import FileWrapper
8 from django.core.urlresolvers import resolve, clear_url_caches, reverse, NoReverseMatch
9 from django.db import models
10 from django.http import HttpResponse, HttpResponseServerError, HttpResponseRedirect, Http404
11 from django.template import add_to_builtins as register_templatetags
12 from django.utils.encoding import smart_str
13
14 from philo.exceptions import MIDDLEWARE_NOT_CONFIGURED, ViewCanNotProvideSubpath, ViewDoesNotProvideSubpaths
15 from philo.models.base import TreeEntity, Entity, QuerySetMapper, register_value_model
16 from philo.models.fields import JSONField
17 from philo.utils import ContentTypeSubclassLimiter
18 from philo.validators import RedirectValidator
19 from philo.signals import view_about_to_render, view_finished_rendering
20
21
22 _view_content_type_limiter = ContentTypeSubclassLimiter(None)
23
24
25 class Node(TreeEntity):
26         """
27         :class:`Node`\ s are the basic building blocks of a website using Philo. They define the URL hierarchy and connect each URL to a :class:`View` subclass instance which is used to generate an HttpResponse.
28         
29         """
30         view_content_type = models.ForeignKey(ContentType, related_name='node_view_set', limit_choices_to=_view_content_type_limiter)
31         view_object_id = models.PositiveIntegerField()
32         #: :class:`GenericForeignKey` to a non-abstract subclass of :class:`View`
33         view = generic.GenericForeignKey('view_content_type', 'view_object_id')
34         
35         @property
36         def accepts_subpath(self):
37                 """A property shortcut for :attr:`self.view.accepts_subpath <View.accepts_subpath>`"""
38                 if self.view:
39                         return self.view.accepts_subpath
40                 return False
41         
42         def handles_subpath(self, subpath):
43                 return self.view.handles_subpath(subpath)
44         
45         def render_to_response(self, request, extra_context=None):
46                 """This is a shortcut method for :meth:`View.render_to_response`"""
47                 return self.view.render_to_response(request, extra_context)
48         
49         def get_absolute_url(self, request=None, with_domain=False, secure=False):
50                 """
51                 This is essentially a shortcut for calling :meth:`construct_url` without a subpath.
52                 
53                 :returns: The absolute url of the node on the current site.
54                 
55                 """
56                 return self.construct_url(request=request, with_domain=with_domain, secure=secure)
57         
58         def construct_url(self, subpath="/", request=None, with_domain=False, secure=False):
59                 """
60                 This method will do its best to construct a URL based on the Node's location. If with_domain is True, that URL will include a domain and a protocol; if secure is True as well, the protocol will be https. The request will be used to construct a domain in cases where a call to :meth:`Site.objects.get_current` fails.
61                 
62                 Node urls will not contain a trailing slash unless a subpath is provided which ends with a trailing slash. Subpaths are expected to begin with a slash, as if returned by :func:`django.core.urlresolvers.reverse`.
63                 
64                 :meth:`construct_url` may raise the following exceptions:
65                 
66                 - :class:`NoReverseMatch` if "philo-root" is not reversable -- for example, if :mod:`philo.urls` is not included anywhere in your urlpatterns.
67                 - :class:`Site.DoesNotExist <ObjectDoesNotExist>` if with_domain is True but no :class:`Site` or :class:`RequestSite` can be built.
68                 - :class:`~philo.exceptions.AncestorDoesNotExist` if the root node of the site isn't an ancestor of the node constructing the URL.
69                 
70                 :param string subpath: The subpath to be constructed beyond beyond the node's URL.
71                 :param request: :class:`HttpRequest` instance. Will be used to construct a :class:`RequestSite` if :meth:`Site.objects.get_current` fails.
72                 :param with_domain: Whether the constructed URL should include a domain name and protocol.
73                 :param secure: Whether the protocol, if included, should be http:// or https://.
74                 :returns: A constructed url for accessing the given subpath of the current node instance.
75                 
76                 """
77                 # Try reversing philo-root first, since we can't do anything if that fails.
78                 root_url = reverse('philo-root')
79                 
80                 try:
81                         current_site = Site.objects.get_current()
82                 except Site.DoesNotExist:
83                         if request is not None:
84                                 current_site = RequestSite(request)
85                         elif with_domain:
86                                 # If they want a domain and we can't figure one out,
87                                 # best to reraise the error to let them know.
88                                 raise
89                         else:
90                                 current_site = None
91                 
92                 root = getattr(current_site, 'root_node', None)
93                 path = self.get_path(root=root)
94                 
95                 if current_site and with_domain:
96                         domain = "http%s://%s" % (secure and "s" or "", current_site.domain)
97                 else:
98                         domain = ""
99                 
100                 if not path or subpath == "/":
101                         subpath = subpath[1:]
102                 
103                 return '%s%s%s%s' % (domain, root_url, path, subpath)
104         
105         class Meta:
106                 app_label = 'philo'
107
108
109 # the following line enables the selection of a node as the root for a given django.contrib.sites Site object
110 models.ForeignKey(Node, related_name='sites', null=True, blank=True).contribute_to_class(Site, 'root_node')
111
112
113 class View(Entity):
114         """
115         :class:`View` is an abstract model that represents an item which can be "rendered", generally in response to an :class:`HttpRequest`.
116         
117         """
118         #: A generic relation back to nodes.
119         nodes = generic.GenericRelation(Node, content_type_field='view_content_type', object_id_field='view_object_id')
120         
121         #: Property or attribute which defines whether this :class:`View` can handle subpaths. Default: ``False``
122         accepts_subpath = False
123         
124         def handles_subpath(self, subpath):
125                 """Returns True if the the :class:`View` handles the given subpath, and False otherwise."""
126                 if not self.accepts_subpath and subpath != "/":
127                         return False
128                 return True
129         
130         def reverse(self, view_name=None, args=None, kwargs=None, node=None, obj=None):
131                 """
132                 If :attr:`accepts_subpath` is True, try to reverse a URL using the given parameters using ``self`` as the urlconf.
133                 
134                 If ``obj`` is provided, :meth:`get_reverse_params` will be called and the results will be combined with any ``view_name``, ``args``, and ``kwargs`` that may have been passed in.
135                 
136                 This method will raise the following exceptions:
137                 
138                 - :class:`~philo.exceptions.ViewDoesNotProvideSubpaths` if :attr:`accepts_subpath` is False.
139                 - :class:`~philo.exceptions.ViewCanNotProvideSubpath` if a reversal is not possible.
140                 
141                 :param view_name: The name of the view to be reversed.
142                 :param args: Extra args for reversing the view.
143                 :param kwargs: A dictionary of arguments for reversing the view.
144                 :param node: The node whose subpath this is.
145                 :param obj: An object to be passed to :meth:`get_reverse_params` to generate a view_name, args, and kwargs for reversal.
146                 :returns: A subpath beyond the node that reverses the view, or an absolute url that reverses the view if a node was passed in.
147                 
148                 """
149                 if not self.accepts_subpath:
150                         raise ViewDoesNotProvideSubpaths
151                 
152                 if obj is not None:
153                         # Perhaps just override instead of combining?
154                         obj_view_name, obj_args, obj_kwargs = self.get_reverse_params(obj)
155                         if view_name is None:
156                                 view_name = obj_view_name
157                         args = list(obj_args) + list(args or [])
158                         obj_kwargs.update(kwargs or {})
159                         kwargs = obj_kwargs
160                 
161                 try:
162                         subpath = reverse(view_name, urlconf=self, args=args or [], kwargs=kwargs or {})
163                 except NoReverseMatch, e:
164                         raise ViewCanNotProvideSubpath(e.message)
165                 
166                 if node is not None:
167                         return node.construct_url(subpath)
168                 return subpath
169         
170         def get_reverse_params(self, obj):
171                 """
172                 This method is not implemented on the base class. It should return a (``view_name``, ``args``, ``kwargs``) tuple suitable for reversing a url for the given ``obj`` using ``self`` as the urlconf. If a reversal will not be possible, this method should raise :class:`~philo.exceptions.ViewCanNotProvideSubpath`.
173                 
174                 """
175                 raise NotImplementedError("View subclasses must implement get_reverse_params to support subpaths.")
176         
177         def attributes_with_node(self, node):
178                 return QuerySetMapper(self.attribute_set, passthrough=node.attributes)
179         
180         def render_to_response(self, request, extra_context=None):
181                 if not hasattr(request, 'node'):
182                         raise MIDDLEWARE_NOT_CONFIGURED
183                 
184                 extra_context = extra_context or {}
185                 view_about_to_render.send(sender=self, request=request, extra_context=extra_context)
186                 response = self.actually_render_to_response(request, extra_context)
187                 view_finished_rendering.send(sender=self, response=response)
188                 return response
189         
190         def actually_render_to_response(self, request, extra_context=None):
191                 raise NotImplementedError('View subclasses must implement actually_render_to_response.')
192         
193         class Meta:
194                 abstract = True
195
196
197 _view_content_type_limiter.cls = View
198
199
200 class MultiView(View):
201         accepts_subpath = True
202         
203         @property
204         def urlpatterns(self):
205                 raise NotImplementedError("MultiView subclasses must implement urlpatterns.")
206         
207         def handles_subpath(self, subpath):
208                 if not super(MultiView, self).handles_subpath(subpath):
209                         return False
210                 try:
211                         resolve(subpath, urlconf=self)
212                 except Http404:
213                         return False
214                 return True
215         
216         def actually_render_to_response(self, request, extra_context=None):
217                 clear_url_caches()
218                 subpath = request.node.subpath
219                 view, args, kwargs = resolve(subpath, urlconf=self)
220                 view_args = getargspec(view)
221                 if extra_context is not None and ('extra_context' in view_args[0] or view_args[2] is not None):
222                         if 'extra_context' in kwargs:
223                                 extra_context.update(kwargs['extra_context'])
224                         kwargs['extra_context'] = extra_context
225                 return view(request, *args, **kwargs)
226         
227         def get_context(self):
228                 """Hook for providing instance-specific context - such as the value of a Field - to all views."""
229                 return {}
230         
231         def basic_view(self, field_name):
232                 """
233                 Given the name of a field on ``self``, accesses the value of
234                 that field and treats it as a ``View`` instance. Creates a
235                 basic context based on self.get_context() and any extra_context
236                 that was passed in, then calls the ``View`` instance's
237                 render_to_response() method. This method is meant to be called
238                 to return a view function appropriate for urlpatterns.
239                 """
240                 field = self._meta.get_field(field_name)
241                 view = getattr(self, field.name, None)
242                 
243                 def inner(request, extra_context=None, **kwargs):
244                         if not view:
245                                 raise Http404
246                         context = self.get_context()
247                         context.update(extra_context or {})
248                         return view.render_to_response(request, extra_context=context)
249                 
250                 return inner
251         
252         class Meta:
253                 abstract = True
254
255
256 class TargetURLModel(models.Model):
257         target_node = models.ForeignKey(Node, blank=True, null=True, related_name="%(app_label)s_%(class)s_related")
258         url_or_subpath = models.CharField(max_length=200, validators=[RedirectValidator()], blank=True, help_text="Point to this url or, if a node is defined and accepts subpaths, this subpath of the node.")
259         reversing_parameters = JSONField(blank=True, help_text="If reversing parameters are defined, url_or_subpath will instead be interpreted as the view name to be reversed.")
260         
261         def clean(self):
262                 if not self.target_node and not self.url_or_subpath:
263                         raise ValidationError("Either a target node or a url must be defined.")
264                 
265                 if self.reversing_parameters and not (self.url_or_subpath or self.target_node):
266                         raise ValidationError("Reversing parameters require either a view name or a target node.")
267                 
268                 try:
269                         self.get_target_url()
270                 except (NoReverseMatch, ViewCanNotProvideSubpath), e:
271                         raise ValidationError(e.message)
272                 
273                 super(TargetURLModel, self).clean()
274         
275         def get_reverse_params(self):
276                 params = self.reversing_parameters
277                 args = kwargs = None
278                 if isinstance(params, list):
279                         args = params
280                 elif isinstance(params, dict):
281                         # Convert unicode keys to strings for Python < 2.6.5. Compare
282                         # http://stackoverflow.com/questions/4598604/how-to-pass-unicode-keywords-to-kwargs
283                         kwargs = dict([(smart_str(k, 'ascii'), v) for k, v in params.items()])
284                 return self.url_or_subpath, args, kwargs
285         
286         def get_target_url(self):
287                 node = self.target_node
288                 if node is not None and node.accepts_subpath and self.url_or_subpath:
289                         if self.reversing_parameters is not None:
290                                 view_name, args, kwargs = self.get_reverse_params()
291                                 subpath = node.view.reverse(view_name, args=args, kwargs=kwargs)
292                         else:
293                                 subpath = self.url_or_subpath
294                                 if subpath[0] != '/':
295                                         subpath = '/' + subpath
296                         return node.construct_url(subpath)
297                 elif node is not None:
298                         return node.get_absolute_url()
299                 else:
300                         if self.reversing_parameters is not None:
301                                 view_name, args, kwargs = self.get_reverse_params()
302                                 return reverse(view_name, args=args, kwargs=kwargs)
303                         return self.url_or_subpath
304         target_url = property(get_target_url)
305         
306         class Meta:
307                 abstract = True
308
309
310 class Redirect(TargetURLModel, View):
311         STATUS_CODES = (
312                 (302, 'Temporary'),
313                 (301, 'Permanent'),
314         )
315         status_code = models.IntegerField(choices=STATUS_CODES, default=302, verbose_name='redirect type')
316         
317         def actually_render_to_response(self, request, extra_context=None):
318                 response = HttpResponseRedirect(self.target_url)
319                 response.status_code = self.status_code
320                 return response
321         
322         class Meta:
323                 app_label = 'philo'
324
325
326 class File(View):
327         """ For storing arbitrary files """
328         
329         mimetype = models.CharField(max_length=255)
330         file = models.FileField(upload_to='philo/files/%Y/%m/%d')
331         
332         def actually_render_to_response(self, request, extra_context=None):
333                 wrapper = FileWrapper(self.file)
334                 response = HttpResponse(wrapper, content_type=self.mimetype)
335                 response['Content-Length'] = self.file.size
336                 return response
337         
338         class Meta:
339                 app_label = 'philo'
340         
341         def __unicode__(self):
342                 return self.file.name
343
344
345 register_templatetags('philo.templatetags.nodes')
346 register_value_model(Node)