Задать вопрос

Тел: +7 965 3737 888

439

Просмотров

0

Ответов

Ajax API class

<p>Whip up an AJAX API for your site in a jiffy:</p>
class MySite(AJAXApi):
  @AJAXApi.export
  def hello(request):
      return {'content': self.get_content()}

  def get_content(self):
    return 'Hello, world!'

  urlpatterns += MySite().url_patterns()

<p>(the example needs the JSON encoding middleware of <a href="http://foothold.ru/knowledge/detail/json-encoding-middleware.html">snippet 803</a> to work.)</p>
<p>The secret is that bound instance methods are callable too, so work as views. (Most Django people only use functions, or sometimes classes with __call__, as view functions.)</p>
<p>You get implicit type dispatch off that self object. So you could subclass MySite, change get_content, and still use the same hello method.</p>
<p>See (django-webapp)[http://code.google.com/p/django-webapp/] for a REST-ish Resource class using this same idea.</p>
<p>You can clearly do better than my func_to_view, and also make a better decorator than exported (so you can actually say @exported('name') def function() etc.). This is more of a proof of concept that should work for most people.</p>
<p>Caveat: I've changed a few things since I last really tested this.</p>
<p>(psst, this also works for non-AJAX views too.)</p>

Вопрос полезен? Да0/Нет0
file_2853.py(1.1Кб)
None