Hacked around the descriptor issues, since there were only three.
[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.utils.encoding import smart_str
12
13 from philo.exceptions import MIDDLEWARE_NOT_CONFIGURED, ViewCanNotProvideSubpath, ViewDoesNotProvideSubpaths
14 from philo.models.base import TreeEntity, Entity, register_value_model
15 from philo.models.fields import JSONField
16 from philo.utils import ContentTypeSubclassLimiter
17 from philo.utils.entities import LazyPassthroughAttributeMapper
18 from philo.signals import view_about_to_render, view_finished_rendering
19
20
21 __all__ = ('Node', 'View', 'MultiView', 'Redirect', 'File')
22
23
24 _view_content_type_limiter = ContentTypeSubclassLimiter(None)
25
26
27 class Node(TreeEntity):
28         """
29         :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.
30         
31         """
32         view_content_type = models.ForeignKey(ContentType, related_name='node_view_set', limit_choices_to=_view_content_type_limiter)
33         view_object_id = models.PositiveIntegerField()
34         #: :class:`GenericForeignKey` to a non-abstract subclass of :class:`View`
35         view = generic.GenericForeignKey('view_content_type', 'view_object_id')
36         
37         @property
38         def accepts_subpath(self):
39                 """A property shortcut for :attr:`self.view.accepts_subpath <View.accepts_subpath>`"""
40                 if self.view:
41                         return self.view.accepts_subpath
42                 return False
43         
44         def handles_subpath(self, subpath):
45                 return self.view.handles_subpath(subpath)
46         
47         def render_to_response(self, request, extra_context=None):
48                 """This is a shortcut method for :meth:`View.render_to_response`"""
49                 return self.view.render_to_response(request, extra_context)
50         
51         def get_absolute_url(self, request=None, with_domain=False, secure=False):
52                 """
53                 This is essentially a shortcut for calling :meth:`construct_url` without a subpath.
54                 
55                 :returns: The absolute url of the node on the current site.
56                 
57                 """
58                 return self.construct_url(request=request, with_domain=with_domain, secure=secure)
59         
60         def construct_url(self, subpath="/", request=None, with_domain=False, secure=False):
61                 """
62                 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.
63                 
64                 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`.
65                 
66                 :meth:`construct_url` may raise the following exceptions:
67                 
68                 - :class:`NoReverseMatch` if "philo-root" is not reversable -- for example, if :mod:`philo.urls` is not included anywhere in your urlpatterns.
69                 - :class:`Site.DoesNotExist <ObjectDoesNotExist>` if with_domain is True but no :class:`Site` or :class:`RequestSite` can be built.
70                 - :class:`~philo.exceptions.AncestorDoesNotExist` if the root node of the site isn't an ancestor of the node constructing the URL.
71                 
72                 :param string subpath: The subpath to be constructed beyond beyond the node's URL.
73                 :param request: :class:`HttpRequest` instance. Will be used to construct a :class:`RequestSite` if :meth:`Site.objects.get_current` fails.
74                 :param with_domain: Whether the constructed URL should include a domain name and protocol.
75                 :param secure: Whether the protocol, if included, should be http:// or https://.
76                 :returns: A constructed url for accessing the given subpath of the current node instance.
77                 
78                 """
79                 # Try reversing philo-root first, since we can't do anything if that fails.
80                 root_url = reverse('philo-root')
81                 
82                 try:
83                         current_site = Site.objects.get_current()
84                 except Site.DoesNotExist:
85                         if request is not None:
86                                 current_site = RequestSite(request)
87                         elif with_domain:
88                                 # If they want a domain and we can't figure one out,
89                                 # best to reraise the error to let them know.
90                                 raise
91                         else:
92                                 current_site = None
93                 
94                 root = getattr(current_site, 'root_node', None)
95                 path = self.get_path(root=root)
96                 
97                 if current_site and with_domain:
98                         domain = "http%s://%s" % (secure and "s" or "", current_site.domain)
99                 else:
100                         domain = ""
101                 
102                 if not path or subpath == "/":
103                         subpath = subpath[1:]
104                 
105                 return '%s%s%s%s' % (domain, root_url, path, subpath)
106         
107         class Meta:
108                 app_label = 'philo'
109
110
111 # the following line enables the selection of a node as the root for a given django.contrib.sites Site object
112 models.ForeignKey(Node, related_name='sites', null=True, blank=True).contribute_to_class(Site, 'root_node')
113
114
115 class View(Entity):
116         """
117         :class:`View` is an abstract model that represents an item which can be "rendered", generally in response to an :class:`HttpRequest`.
118         
119         """
120         #: A generic relation back to nodes.
121         nodes = generic.GenericRelation(Node, content_type_field='view_content_type', object_id_field='view_object_id')
122         
123         #: Property or attribute which defines whether this :class:`View` can handle subpaths. Default: ``False``
124         accepts_subpath = False
125         
126         def handles_subpath(self, subpath):
127                 """Returns True if the :class:`View` handles the given subpath, and False otherwise."""
128                 if not self.accepts_subpath and subpath != "/":
129                         return False
130                 return True
131         
132         def reverse(self, view_name=None, args=None, kwargs=None, node=None, obj=None):
133                 """
134                 If :attr:`accepts_subpath` is True, try to reverse a URL using the given parameters using ``self`` as the urlconf.
135                 
136                 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.
137                 
138                 :param view_name: The name of the view to be reversed.
139                 :param args: Extra args for reversing the view.
140                 :param kwargs: A dictionary of arguments for reversing the view.
141                 :param node: The node whose subpath this is.
142                 :param obj: An object to be passed to :meth:`get_reverse_params` to generate a view_name, args, and kwargs for reversal.
143                 :returns: A subpath beyond the node that reverses the view, or an absolute url that reverses the view if a node was passed in.
144                 :except philo.exceptions.ViewDoesNotProvideSubpaths: if :attr:`accepts_subpath` is False
145                 :except philo.exceptions.ViewCanNotProvideSubpath: if a reversal is not possible.
146                 
147                 """
148                 if not self.accepts_subpath:
149                         raise ViewDoesNotProvideSubpaths
150                 
151                 if obj is not None:
152                         # Perhaps just override instead of combining?
153                         obj_view_name, obj_args, obj_kwargs = self.get_reverse_params(obj)
154                         if view_name is None:
155                                 view_name = obj_view_name
156                         args = list(obj_args) + list(args or [])
157                         obj_kwargs.update(kwargs or {})
158                         kwargs = obj_kwargs
159                 
160                 try:
161                         subpath = reverse(view_name, urlconf=self, args=args or [], kwargs=kwargs or {})
162                 except NoReverseMatch, e:
163                         raise ViewCanNotProvideSubpath(e.message)
164                 
165                 if node is not None:
166                         return node.construct_url(subpath)
167                 return subpath
168         
169         def get_reverse_params(self, obj):
170                 """
171                 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`.
172                 
173                 """
174                 raise NotImplementedError("View subclasses must implement get_reverse_params to support subpaths.")
175         
176         def attributes_with_node(self, node, mapper=LazyPassthroughAttributeMapper):
177                 """
178                 Returns a :class:`LazyPassthroughAttributeMapper` which can be used to directly retrieve the values of :class:`Attribute`\ s related to the :class:`View`, falling back on the :class:`Attribute`\ s of the passed-in :class:`Node` and its ancestors.
179                 
180                 """
181                 return mapper((self, node))
182         
183         def render_to_response(self, request, extra_context=None):
184                 """
185                 Renders the :class:`View` as an :class:`HttpResponse`. This will raise :const:`~philo.exceptions.MIDDLEWARE_NOT_CONFIGURED` if the `request` doesn't have an attached :class:`Node`. This can happen if the :class:`~philo.middleware.RequestNodeMiddleware` is not in :setting:`settings.MIDDLEWARE_CLASSES` or if it is not functioning correctly.
186                 
187                 :meth:`render_to_response` will send the :data:`~philo.signals.view_about_to_render` signal, then call :meth:`actually_render_to_response`, and finally send the :data:`~philo.signals.view_finished_rendering` signal before returning the ``response``.
188
189                 """
190                 if not hasattr(request, 'node'):
191                         raise MIDDLEWARE_NOT_CONFIGURED
192                 
193                 extra_context = extra_context or {}
194                 view_about_to_render.send(sender=self, request=request, extra_context=extra_context)
195                 response = self.actually_render_to_response(request, extra_context)
196                 view_finished_rendering.send(sender=self, response=response)
197                 return response
198         
199         def actually_render_to_response(self, request, extra_context=None):
200                 """Concrete subclasses must override this method to provide the business logic for turning a ``request`` and ``extra_context`` into an :class:`HttpResponse`."""
201                 raise NotImplementedError('View subclasses must implement actually_render_to_response.')
202         
203         class Meta:
204                 abstract = True
205
206
207 _view_content_type_limiter.cls = View
208
209
210 class MultiView(View):
211         """
212         :class:`MultiView` is an abstract model which represents a section of related pages - for example, a :class:`~philo.contrib.penfield.BlogView` might have a foreign key to :class:`Page`\ s for an index, an entry detail, an entry archive by day, and so on. :class:`!MultiView` subclasses :class:`View`, and defines the following additional methods and attributes:
213         
214         """
215         #: Same as :attr:`View.accepts_subpath`. Default: ``True``
216         accepts_subpath = True
217         
218         @property
219         def urlpatterns(self):
220                 """Returns urlpatterns that point to views (generally methods on the class). :class:`MultiView`\ s can be thought of as "managing" these subpaths."""
221                 raise NotImplementedError("MultiView subclasses must implement urlpatterns.")
222         
223         def handles_subpath(self, subpath):
224                 if not super(MultiView, self).handles_subpath(subpath):
225                         return False
226                 try:
227                         resolve(subpath, urlconf=self)
228                 except Http404:
229                         return False
230                 return True
231         
232         def actually_render_to_response(self, request, extra_context=None):
233                 """
234                 Resolves the remaining subpath left after finding this :class:`View`'s node using :attr:`self.urlpatterns <urlpatterns>` and renders the view function (or method) found with the appropriate args and kwargs.
235                 
236                 """
237                 clear_url_caches()
238                 subpath = request.node.subpath
239                 view, args, kwargs = resolve(subpath, urlconf=self)
240                 view_args = getargspec(view)
241                 if extra_context is not None and ('extra_context' in view_args[0] or view_args[2] is not None):
242                         if 'extra_context' in kwargs:
243                                 extra_context.update(kwargs['extra_context'])
244                         kwargs['extra_context'] = extra_context
245                 return view(request, *args, **kwargs)
246         
247         def get_context(self):
248                 """Hook for providing instance-specific context - such as the value of a Field - to any view methods on the instance."""
249                 return {}
250         
251         def basic_view(self, field_name):
252                 """
253                 Given the name of a field on the class, accesses the value of
254                 that field and treats it as a ``View`` instance. Creates a
255                 basic context based on self.get_context() and any extra_context
256                 that was passed in, then calls the ``View`` instance's
257                 render_to_response() method. This method is meant to be called
258                 to return a view function appropriate for urlpatterns.
259                 
260                 :param field_name: The name of a field on the instance which contains a :class:`View` subclass instance.
261                 :returns: A simple view function.
262                 
263                 Example::
264                         
265                         class Foo(Multiview):
266                                 page = models.ForeignKey(Page)
267                                 
268                                 @property
269                                 def urlpatterns(self):
270                                         urlpatterns = patterns('',
271                                                 url(r'^$', self.basic_view('page'))
272                                         )
273                                         return urlpatterns
274                 
275                 """
276                 field = self._meta.get_field(field_name)
277                 view = getattr(self, field.name, None)
278                 
279                 def inner(request, extra_context=None, **kwargs):
280                         if not view:
281                                 raise Http404
282                         context = self.get_context()
283                         context.update(extra_context or {})
284                         return view.render_to_response(request, extra_context=context)
285                 
286                 return inner
287         
288         class Meta:
289                 abstract = True
290
291
292 class TargetURLModel(models.Model):
293         """An abstract parent class for models which deal in targeting a url."""
294         #: An optional :class:`ForeignKey` to a :class:`.Node`. If provided, that node will be used as the basis for the redirect.
295         target_node = models.ForeignKey(Node, blank=True, null=True, related_name="%(app_label)s_%(class)s_related")
296         #: A :class:`CharField` which may contain an absolute or relative URL, or the name of a node's subpath.
297         url_or_subpath = models.CharField(max_length=200, blank=True, help_text="Point to this url or, if a node is defined and accepts subpaths, this subpath of the node.")
298         #: A :class:`~philo.models.fields.JSONField` instance. If the value of :attr:`reversing_parameters` is not None, the :attr:`url_or_subpath` will be treated as the name of a view to be reversed. The value of :attr:`reversing_parameters` will be passed into the reversal as args if it is a list or as kwargs if it is a dictionary. Otherwise it will be ignored.
299         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.")
300         
301         def clean(self):
302                 if not self.target_node and not self.url_or_subpath:
303                         raise ValidationError("Either a target node or a url must be defined.")
304                 
305                 if self.reversing_parameters and not (self.url_or_subpath or self.target_node):
306                         raise ValidationError("Reversing parameters require either a view name or a target node.")
307                 
308                 try:
309                         self.get_target_url()
310                 except (NoReverseMatch, ViewCanNotProvideSubpath), e:
311                         raise ValidationError(e.message)
312                 
313                 super(TargetURLModel, self).clean()
314         
315         def get_reverse_params(self):
316                 params = self.reversing_parameters
317                 args = kwargs = None
318                 if isinstance(params, list):
319                         args = params
320                 elif isinstance(params, dict):
321                         # Convert unicode keys to strings for Python < 2.6.5. Compare
322                         # http://stackoverflow.com/questions/4598604/how-to-pass-unicode-keywords-to-kwargs
323                         kwargs = dict([(smart_str(k, 'ascii'), v) for k, v in params.items()])
324                 return self.url_or_subpath, args, kwargs
325         
326         def get_target_url(self):
327                 """Calculates and returns the target url based on the :attr:`target_node`, :attr:`url_or_subpath`, and :attr:`reversing_parameters`."""
328                 node = self.target_node
329                 if node is not None and node.accepts_subpath and self.url_or_subpath:
330                         if self.reversing_parameters is not None:
331                                 view_name, args, kwargs = self.get_reverse_params()
332                                 subpath = node.view.reverse(view_name, args=args, kwargs=kwargs)
333                         else:
334                                 subpath = self.url_or_subpath
335                                 if subpath[0] != '/':
336                                         subpath = '/' + subpath
337                         return node.construct_url(subpath)
338                 elif node is not None:
339                         return node.get_absolute_url()
340                 else:
341                         if self.reversing_parameters is not None:
342                                 view_name, args, kwargs = self.get_reverse_params()
343                                 return reverse(view_name, args=args, kwargs=kwargs)
344                         return self.url_or_subpath
345         target_url = property(get_target_url)
346         
347         class Meta:
348                 abstract = True
349
350
351 class Redirect(TargetURLModel, View):
352         """Represents a 301 or 302 redirect to a different url on an absolute or relative path."""
353         #: A choices tuple of redirect status codes (temporary or permanent).
354         STATUS_CODES = (
355                 (302, 'Temporary'),
356                 (301, 'Permanent'),
357         )
358         #: An :class:`IntegerField` which uses :attr:`STATUS_CODES` as its choices. Determines whether the redirect is considered temporary or permanent.
359         status_code = models.IntegerField(choices=STATUS_CODES, default=302, verbose_name='redirect type')
360         
361         def actually_render_to_response(self, request, extra_context=None):
362                 """Returns an :class:`HttpResponseRedirect` to :attr:`self.target_url`."""
363                 response = HttpResponseRedirect(self.target_url)
364                 response.status_code = self.status_code
365                 return response
366         
367         class Meta:
368                 app_label = 'philo'
369
370
371 class File(View):
372         """Stores an arbitrary file."""
373         #: Defines the mimetype of the uploaded file. This will not be validated.
374         mimetype = models.CharField(max_length=255)
375         #: Contains the uploaded file. Files are uploaded to ``philo/files/%Y/%m/%d``.
376         file = models.FileField(upload_to='philo/files/%Y/%m/%d')
377         
378         def actually_render_to_response(self, request, extra_context=None):
379                 wrapper = FileWrapper(self.file)
380                 response = HttpResponse(wrapper, content_type=self.mimetype)
381                 response['Content-Length'] = self.file.size
382                 return response
383         
384         class Meta:
385                 app_label = 'philo'
386         
387         def __unicode__(self):
388                 """Returns the path of the uploaded file."""
389                 return self.file.name
390
391
392 register_value_model(Node)