Where does related logic go on model creation when working with REST api with Django, Backbone, and Tastypie? - rest

We are trying to move some of our app to use backbone and tastypie. I have the REST api set up and it is working on some basic examples. However, there are a few issues where currently we post an ajax request to a custom url, and in that view do a few things like
make related objects
call a few related functions
However, now that I've switched some of this functionality to using backbone and the REST api, I'm not sure where all of that should go!
For example, I had a view to make a Message, and when I made a Message, I also made a Notification and called a function to add some points to the user. Something like
def ajax_send_message(request):
## ... set up some variables ...
## Make the new message
message = Message(user=user, content=message)
message.save()
## Make the notification
notification = Notification(message=message)
notification.save()
## Give the user points
user.add_points_for_message();
return json_response({"status": "ok"})
Now--am I just supposed to do this all in JavaScript? I have a Message Backbone model as well.
// Create message backbone object
var msg = new Message({content:content, user: user});
// Post to server
msg.save();
// Add to backbone collection
messages.add(msg);
I've looked at different parts of tastypie, and it seems you can create custom URL endpoints, and also do validation, but that doesnt seem like the right spot to call related methods. It seems that calling related methods goes against the REST part of it---but then where are they supposed to go?
If I want to add some logic to backbone only when an object is created, where does that go?

The first thing I would suggest is to switch your mindset to an event-based model, where your code reacts to events. In your example above, you save the model to the server then immediately dd it to the collection. How do you even know that the model was saved correctly? That procedural style of programming works better in a synchronous, server-side style of programming.
In the asynchronous world of client-side programming, you make a request and then set up callbacks which determine what will happen next, depending on the events your are listening for. In your case, you want to react a certain way when the message is saved successfully, correct? You can define a success callback for your save operation like so:
msg.save({
success: function(model, response, options) {
messages.add(model);
// code to add notification
// code to add points
}
});
Basically, you are saying "I would like to save this model, and then listen for a success event. When the event comes in, execute the following code." Notice also that I am adding the model returned from the API to the collection, since this is the exact object that was persisted to the server so it's more appropriate to add than the model you created.

Related

Play Framework: Don't change URL after form validation failed

In a plain Play application I have the following scenario.
A route file which looks like this:
GET /accounts/add controllers.Accounts.add()
POST /accounts controllers.Accounts.create()
The first route results in a view where I can add a new account. The form to submit the new account looks something like this:
#helper.form(action = routes.Accounts.create()) {...}
Now the controller binds the input to the form and checks for any validation errors:
public static Result create() {
Form<Account> form = Form.form(Account.class).bindFromRequest();
if (form.hasErrors()) {
return badRequest(views.html.account.add.render(form));
}
...
}
Now the thing is, the client will see the same view with some additional error messages. However, meanwhile the URL has changed from http://example.com/accounts/add to http://example.com/accounts.
If the client now reloads the browser this calls GET http://example.com/accounts (which isn't even mapped in this scenario - thus getting a 404 - Not Found).
Maybe it's just me but I find this kind of annoying and browsing some GitHub projects I couldn't find a good solution for this case.
Of cause things would be much simpler if the second route is rewritten to:
POST /accounts/add controllers.Accounts.create()
... in which case everything works fine. But from a REST point of view this doesn't feel good either. The same applies to update scenarios (having GET /accounts/:id/update vs. PUT /accounts/:id).
Is there a guide on how to handle this? Am I getting something wrong or is this no problem at all (from a pragmatic point of view)?
It's not possible to leave the previous URL because a request for a new address has already been made. A controller only provides response for a requested resource. To go to the previous URL you could only make a redirect in case of validation failure but you would lost errors that way so this is not a solution.
I suggest mapping both actions with the same URL. This way you would solve problem with the browser reload.
If you create a REST service for http clients that aren't browsers you will probably want to serve different response than a simple http page. The separation of actions for particular clients could be a good solution for keeping REST API clean and a browser user happy.

Real time model events in Sails.js 0.10-rc5

I've been playing around with building some realtime functionality using Sails.js version 0.10-rc5 (currently the #beta release).
To accomplish anything, i've been following the sweet SailsCast tutorial on this subject (sailsCast link)
It talks about subscribing to a model via a 'subscribe' action within the model's controller. Then listening to it at the client side, waiting for the server to emit messages. Quite straightforward, although I do not seem to receive any messages.
I'm trying to do this to get real-time updates on anything that changes in my User models, or if new ones get created.. So I can display login status etc. in real time. Pretty much exactly the stuff that's explained in the sailsCast.
In my terminal i'll get two things worth noticing, of which the first is the following:
debug: Deprecated: `Model.subscribe(socket, null, ...)`
debug: See http://links.sailsjs.org/docs/config/pubsub
debug: (⌘ + double-click to open link from terminal)
debug: Please use instance rooms instead (or raw sails.sockets.*() methods.)
It seems like the 'subscribe' method has been deprecated. Could anybody tell me if that's correct, and tell me how to fix this? I've been checking out the reference to the documentation in the debug message, although it just points me to the global documentation page. I've been searching for an answer elsewhere, but haven't found anything useful.
The second message I'm getting is:
warn: You are trying to render a view (_session/new), but Sails doesn't support rendering views over Socket.io... yet!
You might consider serving your HTML view normally, then fetching data with sockets in your client-side JavaScript.
If you didn't intend to serve a view here, you might look into content-negotiation
to handle AJAX/socket requests explictly, instead of `res.redirect()`/`res.view()`.
Now, i'm quite sure this is because I have an 'isAuthenticated' policy added to all of my controllers and actions. When a user is not authenticated, it'll redirect to a session/new page. Somebody must log in to be able to use the application. When I remove the 'isAuthenticated' policy from the 'subscribed' action, the warnings disappear. Although that means anyone will get updates via sockets (when I get it to work), even when they're logged out. - I don't really feel like people just sitting at the login screen, fishing out the real time messages which are intended only for users who are logged in.
Can anyone help me getting the real time updates to work? I'd really appreciate!
As far as the socket messages not being received, the issue is that you're following a tutorial for v0.9.x, but you're using a beta version of Sails in which PubSub has gone through some changes. That's covered in this answer about the "create" events not being received.
Your second issue isn't about sockets at all; you'll just need to reconsider your architecture a bit. If you want to to use socket requests to sign users in, then you'll have to be more careful about redirecting them because, as the message states, you can't render a view over a socket. Technically you could send a bunch of HTML back to the client over a socket, and replace your current page with it, but that's not very good practice. What you can do instead is, in your isAuthenticated policy, check whether the request is happening via sockets (using req.isSocket) and if so, send back a message that the front end can interpret to mean, "you should redirect to the login page now". Something like:
module.exports = function (req, res, next) {
if ([your auth logic here]) {
return next();
}
else {
if (req.isSocket) {
return res.json({status: 403, redirectTo: "/session/new"});
} else {
return res.redirect("/session/new");
}
}
}

Dancer Hooks on a per-request method basis?

I'm working on a CRUD application using Dancer. One of the things I need to do is check a user is authorized to perform POST (create) and PUT (update) / DELETE (remove) operations.
I've read up on before hooks in the Dancer documentation, but have been unable to figure out the best way to do varying types of authorization.
For a POST operation, all I want to do is check that a valid API key has been submitted with the request, but for a PUT/DELETE operation, I want to check that the API key submitted matches the user who is attached to the record to be updated or deleted.
I understand how to do the logic behind checking the API keys, but I'm wondering if hooks (or something else) would allow me to call that logic without having to add the same boilerplate function call to every single PUT/POST/DELETE function on every route.
like I told the poster on IRC, I think a combination of https://metacpan.org/pod/Dancer#request (the Dancer request object) and its HTTP verbs querying things should do the trick. See for example: https://metacpan.org/pod/Dancer::Request#is_post .
I'm not sure if it's a very elegant solution, but I think it should work.
Here's another take on this issue, based on experience:
Since Dancer has not had the opportunity to parse your input parameters when the 'before' hook executes, you may not have a consistent way to read in your authentication credentials, if your application allows them to be provided in a variety of ways.
In particular, if you're using input parameters to pass a nonce to prevent CSRF attacks (which you should definitely consider!), you won't have a consistent way to obtain that nonce. You could do your own mini-parameter-parsing within 'before', but that could be messy too.
I ran into this problem when I worked on an application some time ago, and remember having to add the dreaded boilerplate authentication function to every PUT/POST/DELETE route. Then, if you're doing that, it becomes irrelevant to check request->is_post because you're already deciding whether to place the boilerplate authentication function within the route.
I haven't tried this yet, but it may be possible to handle the pre-requisite action in your Route base class, then pass upon success. This will leave your specific packages to handle the request as normal once your base class has verified authentication.
An action can choose not to serve the current request and ask Dancer to process the request with the next matching route. This is done with the pass keyword, like in the following example
get '/say/:word' => sub {
return pass if (params->{word} =~ /^\d+$/);
"I say a word: ".params->{word};
};
get '/say/:number' => sub {
"I say a number: ".params->{number};
};

Simplest example for sending post data via links in Zend Framework

Starting with Zend and I´d like to know what is the simplest way of sending POST data to another page, not by forms, but by some link in my view instead. Thanks :)
You can't send POST data through a link. At least not through a normal link. Link can only carry GET data.
If you need to send POST over a link it's most certainly a design flaw.
If you're 100% sure, that you need it, you can do that using jQuery and onclick event. It`s not possible to do it without javascript. Other option would be to send it using form with hidden fields with single submit button visible - that would even work without javascript.
Normal hyperlinks in HTML are sent with GET requests and are not supposed to change the state of the resource being accessed. This is known as being idempotent. You can repeat the request over and over, and the result of each succeeding request to the same URL is the same as the first one.
POST requests don't have this restriction and are intended for when the user needs to change something (such as creating a new resource.)
It's not possible to send a POST request via a normal HTML link. And even if you find a way, it breaks an almost universal expectation that web users have. What are you trying to accomplish? Maybe there's a better way.
But to answer your question, you could use something like jQuery to capture the "click" event and make it do a POST request:
$('.my-link').click(function() {
var url = $(this).attr('href');
var data = {};
$.post(url, data, function() {
window.alert('success!');
});
return false;
});
If your URL has any query parameters, i.e. "?foo=bar&baz=bum", then you'd probably need to strip them off of the URL and pass them as a second parameter to the $.post() function. This is left as an exercise for the reader. ;-)

MVC 2.0 Post Form to action instead of redirect to action

I am using T4MVC to redirect to another action return RedirectToAction(MVC.MyController.MyAction());.
In result it is doing get request.
Is there any way to make post request from controller. I want to keep all the same but only make post instead get. I cant find any methods for that. I found one post helper here http://geekswithblogs.net/rakker/archive/2006/04/21/76044.aspx but i cant pass any values i need using this post helper. I was trying to pass values through TempData but they are not coming when i using this helper. May be some one have any ideas?
The reason i want to do this because when user come from one controller to another and then if user click update or just click enter in browser address bar, page will break.
Should i use session for that reason?
A RedirectToAction will always perform a GET, never a POST (it returns a HTTP 302 to the browser, which will then issue a GET request).
To persist data across the redirect, if it is data that can be easily represented as a string and stored in the query string, then you can just add it to the route values of the redirect.
e.g.
return RedirectToAction("Search", new { searchString = "whatever" });
If it is a complex type, then you will need to store it in TempData. A number of other questions on StackOverflow (such as this one) give details on how.
If repeatedly storing to and reading from TempData across your application offends your code-sense, then you can encapsulate this by using the PassParametersDuringRedirect attribute and generic RedirectToAction available in the MvcContrib project. Some details on this technique are available here.
only way of doing post is by having a form and doing submit on that form, either with a submit button or with javascript, any info you want passed to that action must be in that form and you will find everything posted in FormCollection(hope I spelled it right).