Friday, October 12, 2012

CORS and PSY Gangnan on saturday morning...

I need to run a python script which will serve images. And this image servlet will also accept POST which will upload images to the servlet. But the challenge is the post can come from a different domain.

SO my python script should accept crossdomain post and get for image

Consider an eg) like

Two domain :

  • http://localhost:80/
  • http://localhost:8081/

You have a web page hpsted in http://localhost:8081/ . From this page you would like to submit data or get data from a server running @ http://localhost:80/.

@ http://localhost:8081/

Here you use a normal html page and a jquery script to do the post .  

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="js/jquery-1.7.2.js"></script>
</head>
<body>
<script type="text/javascript">
$().ready(function(){
   
    console.log("Helooworld");
    $.ajax({
          url: "http://localhost:80/cgi-bin/upload.cgi"
        }).done(function(result) {
          console.log("result = "+result);
        });
    $("[name='submit']").live('click',function(event){
        console.log('clicked');
        event.preventDefault();
        var formdata = new FormData($("form").get()[0])
        $.ajax({
            url: "http://localhost:80/cgi-bin/upload.cgi",
            type:'POST'    ,
            data:formdata,
            cache: false,
            contentType: false,
            processData: false
        }).done(function(data){
            console.log("success!!");
        });
    });


});
</script>
<form enctype="multipart/form-data" method="post" name="fileinfo">
File name: <input name="file_1" type="file"><br>
File name: <input name="file_2" type="file"><br>
File name: <input name="file_3" type="file"><br>
<input name="submit" type="submit">
</form>
</body>
</html> 

 

Not the FormData element, this is part of the xhr2 spec of html5. Which allows cross domain file upload. Just like CORS this is only supported in latest browsers.

I have used jquery for the ajax submit . Versions of jquery after 1.5.1 support CORS so the hassles of CORS to a limit are handled by jquery. Making the like of developer

much easy. Also to prevent jquery from processing the FormData object i have mentioned processData:false and also the content type is also set to false. These are imp!!.

Now this code should be able to submit the files to a server located in another domain. We shall look into the 2nd server now

@ http://localhost:80/

At my second server i have used a Python cgi script for handling the file upload. Here  look at the script

print "Access-Control-Allow-Origin: http://localhost:8080"
print "Content-Type: text/html\n"
print HTML_TEMPLATE % {'SCRIPT_NAME':os.environ['SCRIPT_NAME']}

.

.

.

form = cgi.FieldStorage()
    if not form.has_key(form_field): return
    fileitem = form[form_field]
    if not fileitem.file: return
    fout = file (os.path.join(upload_dir, fileitem.filename), 'wb')

 

 

revent Here not that i have set the header option print "Access-Control-Allow-Origin: http://localhost:8080"  for the response which allow this cgi to

accept as well as serve content for the domain http://localhost:8080 . This is specifially for python. For other technologies on how to set the response header

check this . Thus i was able to remotely upload files to a different domain as well as get data from their without the need of comples ajax file upload plugins

or jsonp. Thi is one of the signs of rising power on the client tier. Now its sunday morning 10.19. The delay i would say was due to the

/tmp problem..I uploaded my files to /tmp in fedora . And couldnt find it ther. Then i came across this blog which said in fedora /tmp is mounted with tmpfs.

Anywas Happy coding

Thursday, October 4, 2012

Backbone as simple as angular

Often people misunderstand javascript to be too inferior . And they fear the more code we write in js the more will be the maintenance nightmare. So my pursuit is to convince how much readable code are the new genre of javascript frameworks providing us. I shall be mainly dealing with Backbone which i came across when searching for a stable and well proven framework.

 

define([
  'underscore',
  'backbone',
], function(_, Backbone) {
    Profile = Backbone.Model.extend({
        idAttribute: "accountid",
        urlRoot : '/trip-2/tpp/account/',           
        initialize : function(model,options){
            this.bind("change",this.displaylog);
        },
        parse:function(response){
            return response.account;
        },
        displaylog:function(model){
            console.log(model.toJSON());
           }
    }); 
  return Profile;
});

Above code represent a typical Model object in BackBone. THe backbone of Backbone are three standard Objects defined by framework. And they are

The view and model corresponds to the same as in MVC architecture. The model is the link b/w the server side service and the javascript. Somebody asked me is it synonymous to the Business Modl in server side? If you think you are doing critical business functionalities in client side then offcource you can encapsulate them in Model. But i think majority of javascript apps deals with displaying and doing trifle actions like checking,updating,creating,view related actions like drag,drop etc. Out of these the major things affecting our data  are update,save delete etc. Its these update delete create that are organised into model.

The profile model here is linked to service  '/trip-2/tpp/account/' .During fetch a GET action is fired to this url and when data is updated a PUT is fired and when a new profile is added a POST is fired.

This completes our backbone Model.

Now one of the major adavantage of using Backbone is its flexibility. Its optional we use a Router or a View. THese are useful if we are to bring in seprataion of concern in the javascript layer.Like we have a separate js dealing with DOM manipulation namely VIew. And another js for handling model and server communication namely Model. You may ask why separation of concern since it only seeks to increase the number of files associated.

  • It improves code maintainability. WHich is an important factor when you are writing complex client side application.
  • Mix and match of various technologies .

 hus this particular model object gets its data by calling the service at this link via a GET request.

And when to save the data of this model it call the same url but with a PUT.

And when to create a new model it update server side by calling POST to the same url. This is something knows as the REST based convention. Where this object corresponds to a Resource at the server side. And all operations are accessed cia a RESTful url with actions - GET,PUT,POST,DELETE etc. Backbone expects your application to be of RESTful nature by default. But this is not a mandatory. Once can change the urls/format/operations of the save update delete etc. By implementing the save,fetch,destroy methos in the model