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