Skip to content

Instantly share code, notes, and snippets.

@Kos
Created November 22, 2014 21:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Kos/31f56585c2740cbdb245 to your computer and use it in GitHub Desktop.
Save Kos/31f56585c2740cbdb245 to your computer and use it in GitHub Desktop.
Dajaxice replacement idea
from rest_framework.decorators import api_view
from rest_framework.response import Response
import ajaxmelt
@ajaxmelt.register('POST')
@api_view
@login_required
def edit_name(request):
campaign = get_object_or_404(Campaign.objects.visible_to(request.user), id=campaign_id)
request.data['campaign_id']
new_name = request.data.get('new_name', 'No name')
campaign.name = new_name
campaign.save()
return Response({'OK'})
# Stuff that happens here:
#
# - @login_required is obvious
# - @api_view from Django Rest Framework fills request.user, request.data,
# translates Response into HTTPResponse, negotiates content type... (we could
# do without this dependency, but it just fits)
# - @ajaxmelt.register makes the view available as /melt/__module__/__name__/
# In your root urlconf you'd just register the /melt/ view somewhere, and it
# would do the dispatching. All urls like /melt/... are normal json-json
# endpoints, you can talk to them through jQuery or curl or whatnot.
@ajaxmelt.register('POST')
@ajaxmelt.unpack
@api_view
@login_required
def edit_name(request, campaign_id, new_name='No name'):
campaign = get_object_or_404(Campaign.objects.visible_to(request.user), id=campaign_id)
campaign.name = new_name
campaign.save()
return Response({'OK'})
# same thing, but with one extra decorator that unpacks request.data into named
# parameters. (Normally request.data can be any JSON data type, but here it
# needs to be an object with keys matching params)
// Essentially you could talk to the views normally, like:
$.post('/melt/mypackage.campaigns.ajax/edit_name/').then(...);
// Or you could make a simple wrapper around that if you care about
// Dajaxice-style function-like calls:
var Campaigns = Melt.Module('mypackage.campaigns.ajax');
Campaigns.edit_name({'campaign_id': 123, 'new_name': 321}).then(...);
// This is pretty, but misses several bits of info:
// - root URL for /melt/ urls
// - which URLs should use GET or POST or...
// A generated setup script would solve both, but I imagine for simplicity you could
// live with these: setup the root URL manually and specify the request method
// every time, kind of like...
Melt.setup({'root_url': '/melt/');
Campaigns.edit_name.post({'campaign_id': 123, 'new_name': 321}).then(...);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment