Author:


Python httplib example

Posted by – August 21, 2010

This is a very simple example of httplib in Python. I am trying to write a very simple client which can simply ping a URL.

import httplib
while True:
 myURL = raw_input('\nURL Please: \n> ')
 if myURL == '':
 print '\URL Please: \n'
 break
httpconnection = httplib.HTTPConnection(myURL)
httpconnection.request('GET', '/')
res = httpconnection.getresponse()
#I am only interested in 200 OK response, anything else can be ignored
if res.status != 200:
 print 'Errr!!!!', myURL, 'seems to be a troublesome URL. The "Internet" says "', res.reason, '" and the status was', res.status, '. Try again.'
else:
 data = res.read()
 allheaders = res.getheaders()
 print data
Share LAMP Web Development Blog:
  • Print
  • PDF
  • email
  • Digg
  • del.icio.us
  • Facebook
  • Slashdot
  • Mixx
  • Google Bookmarks
  • FriendFeed
  • IndianPad
  • LinkedIn
  • Live
  • MSN Reporter
  • Netvibes
  • Sphinn
  • NewsVine
  • Reddit
  • StumbleUpon
  • Technorati
  • Twitter
  • Twitthis
  • Wikio IT
  • Yahoo! Bookmarks
  • Yahoo! Buzz

How to test a boolean?

Posted by – July 29, 2010

This is some of the best written code I have ever seen or I will ever see

public boolean isBooleanFalse(boolean value) {
   boolean response = false;
   if (value == true) {
       response = false;
   } else {
       response = true;
   }
   return response;
}

I bet no one can do better than this.

Share LAMP Web Development Blog:
  • Print
  • PDF
  • email
  • Digg
  • del.icio.us
  • Facebook
  • Slashdot
  • Mixx
  • Google Bookmarks
  • FriendFeed
  • IndianPad
  • LinkedIn
  • Live
  • MSN Reporter
  • Netvibes
  • Sphinn
  • NewsVine
  • Reddit
  • StumbleUpon
  • Technorati
  • Twitter
  • Twitthis
  • Wikio IT
  • Yahoo! Bookmarks
  • Yahoo! Buzz

The Big Pipe – Faster Facebook

Posted by – July 20, 2010

Facebook is a big time killer. You can harvest farm without owning an inch of land, kill your buddies and still brag about it, save unknown species of zoo animals and poke any girl you know and she wont mind.
But Facebook is a case study for web developers like me. A typical Facebook page, depending on network and host, loads within 5 seconds. Facebook team has set this time to 2.5 seconds. Anything beyond 2.5 seconds is a big no no. For me it loads 19 CSS files, just one JS file, all in all a 50KB page w/out images. If you didnt pay attention to last line, it FB loads just one JS file and if you look at the byte size its just 10K file. Like I mentioned earlier Gzipped content is much lighter i.e. low byte size, it can be sent over network quickly. Facebook and every other website follows and compress the content they send over the network. But this is not all.
Before I move ahead, lets understand how a page is “rendered” in browser.

  • You send a request to FB servers.
  • FB server looks at your request and prepares a page, if you were logged in, it will send your profile page otherwise a nice login page. This job is done by PHP, MySQL, Apache and some in house tools developed by FB.
  • FB sends you back the page, the HTML
  • The browser reads or “parses” the HTML and finds out well it also needs CSS, images and JS and sends separate requests for these assets.

Now here is the tricky part. Browsers need all the possible assets that can affect the rendering of page and JS is one thing that can hide images, change CSS applied on an element, add text or can change the complete layout. So when browsers encounter a JS file they stop loading anything and concentrate only on JS. Till the time JS is not loaded and processed nothing else is done. This have been, more or less, same for nearly all the browsers till date. Web developers try to deceive browsers in many ways. The one way suggested by Yahoo! is to load JS at the bottom of page or develop the page in such a way that JS is loaded just before body tag is closed. This is not feasible in many cases. Say for example, on my webpage a menu appears in top header not in bottom of the page so it is rendered first and I need it to be active. There are way outs.

  • RequireJS
  • labJS
  • Load JS using AJAX
  • Create Script tag dynamically
  • Load scripts in iFrame
  • and others

Facebook employs some thing it calls a BigPipe. Interestingly FB divides its page into smaller chunks, named pagelets and every pagelet has its own JS associated with it. Have a look at following BigPipe fragment

<script> big_pipe.onPageletArrive({
 "id": "pagelet_nav_lite",
 "phase": 1,
 "is_last": false,
 "append": false,
 "display_dependency": [
 "pagelet_navigation"
 ],
 "bootloadable": {
 "editable-side-nav-js": [
 "CiNUi",
 "WTiBX",
 "Nahdv",
 "vstFf"
 ]
 },
 "css": [
 "p0tHf",
 "HOV0r",
 "FLbGk",
 "mWAGo",
 "e2Nmn"
 ],
 "js": [
 "CiNUi",
 "WTiBX",
 "k29le",
 "kJEXe",
 "5CZKw",
 "S4cYi",
 "3iRY2"
 ],
 "resource_map": {
 "e2Nmn": {
 "name": "css\/sprite\/autogen\/a2gtd9_duri.css",
 "type": "css",
 "nonblocking": 1,
 "src": "http:\/\/static.ak.fbcdn.net\/rsrc.php\/z8ZLB\/hash\/40d4o2t0.css"
 },
 "vstFf": {
 "name": "js\/ui\/xhp\/page\/editable_side_nav.js",
 "type": "js",
 "src": "http:\/\/static.ak.fbcdn.net\/rsrc.php\/z5QP6\/p\/hash\/eoj7km8p.js"
 }
 },
 "requires": [

 ],
 "provides": [

 ],
 "onload": [

 ],
 "onafterload": [

 ],
 "onpagecache": [

 ],
 "onafterpagecache": [

 ],
 "refresh_pagelets": [

 ],
 "invalidate_cache": [

 ],
 "content": {
 "pagelet_nav_lite": "HTML removed, view source your own FB profile page :-) "
 },
 "page_cache": true
})</script>

Further spying on the DOM using Firebug, I could see an iframe named “bootloader_iframe” which loads JS files.

BigPipe has really changed the way Facebook loads and works. Facebook is showing generosity and is sharing what it does. Unlike Yahoo! and Google, Facebook is not so much developer friendly and is not well known to share its knowledge. I hoping to see more documentation on BigPipe. Here is some info: http://www.facebook.com/notes/facebook-engineering/bigpipe-pipelining-web-pages-for-high-performance/389414033919

The JSON object was formatted using JSONLint.

Share LAMP Web Development Blog:
  • Print
  • PDF
  • email
  • Digg
  • del.icio.us
  • Facebook
  • Slashdot
  • Mixx
  • Google Bookmarks
  • FriendFeed
  • IndianPad
  • LinkedIn
  • Live
  • MSN Reporter
  • Netvibes
  • Sphinn
  • NewsVine
  • Reddit
  • StumbleUpon
  • Technorati
  • Twitter
  • Twitthis
  • Wikio IT
  • Yahoo! Bookmarks
  • Yahoo! Buzz

Speed up your web page – Serve Gzipped content

Posted by – May 17, 2010

Today most of the browsers accept compressed content. See this. The compression on a Linux box can be achieved using GNU Zip or GZip. Here is a simple .htaccess trick to serve gzipped content to browsers.

<FilesMatch "\.(js|css)$">
RewriteEngine on
RewriteCond %{HTTP:Accept-encoding} gzip
RewriteCond %{REQUEST_FILENAME}.gz -f
RewriteRule ^(.*)$ %{REQUEST_URI}.gz [L,QSA]
</FilesMatch>
<FilesMatch "\.(js|css)\?.*$">
RewriteEngine on
RewriteCond %{HTTP:Accept-encoding} gzip
RewriteCond %{REQUEST_FILENAME}.gz -f
RewriteRule ^([^?]*)\?(.*)$ $1.gz?$2 [L]
</FilesMatch>
<FilesMatch "\.js\.gz(\?.*)?$">
AddEncoding x-gzip .gz
AddType text/javascript .gz
</FilesMatch>
<FilesMatch "\.css\.gz(\?.*)?$">
AddEncoding x-gzip .gz
AddType text/css .gz
</FilesMatch>

What this script does is very simple. It simply rewrites the request for browsers that accept compressed files from .css or .js to .css.gz or .js.gz ONLY if corresponding .gz files are available on file system. Then serves .gz files with a proper encoding. To use this on your server, you must have
a) Linux – Elementary
b) Apache – Again, elementary
c) gzip – If you are on Linux, you have it
d) mod_rewrite – mod_rewrite enabled.
e) .htaccess – you must have ability to create and use .htaccess
Now .js files can be zipped with following shell script snippet

for i in `find ./  -name  "*.js"`
do
gzip -9 -c -f $i > $i.gz
done

The shell script snippet above can be reduced to one line and can also compress html/css/js files. How? Find out and tell me. ;-)

Share LAMP Web Development Blog:
  • Print
  • PDF
  • email
  • Digg
  • del.icio.us
  • Facebook
  • Slashdot
  • Mixx
  • Google Bookmarks
  • FriendFeed
  • IndianPad
  • LinkedIn
  • Live
  • MSN Reporter
  • Netvibes
  • Sphinn
  • NewsVine
  • Reddit
  • StumbleUpon
  • Technorati
  • Twitter
  • Twitthis
  • Wikio IT
  • Yahoo! Bookmarks
  • Yahoo! Buzz

How to write a Facebook App?

Posted by – April 25, 2010

Writing a Facebook is as easy as signing up for Facebook account. There is just one prerequisite, you must have some sort of web hosting, steps given below use PHP so a web hosting with PHP support is required, and you must know how to upload files. Follow these steps

  1. Sign up for Facebook if you don’t have an account. If you can’t do this simple thing do not read further.
  2. Go to Account > Applications and add Facebook Developer application.
  3. Go to the app page, locate and click the “Set up new application” button.
  4. Follow the instructions which let you name your app and set other things.
  5. Dont bother if you dont understand anything in the forms. Fill what you understand and just pay attention to following fields:
    a) Under Canvas > Canvas Page URL, create a Canvas URL which will be your app’s URL on Facebook, for example “my-hello-world-app”
    b) Under Canvas > Canvas Callback URL, this will be URL where we will host our Facebook app, so if I host my app on kumarchetan.com, the URL will be http://www.kumarchetan.com/, easy
    c) Under Canvas > Canvas Settings > Render Method, choose FBML.
    Save changes.
  6. Download the client library from here: http://svn.facebook.com/svnroot/platform/clients/packages/facebook-platform.tar.gz
  7. Extract the library on your local machine and you will end with a folder with two sub folders. We will be using folder named “php”.
  8. Open “index.php” in your choice of editor and you will see following code
    <?php
    // Copyright 2007 Facebook Corp. All Rights Reserved.
    //
    // Application: Ye app puri philmy hai
    // File: 'index.php'
    // This is a sample skeleton for your application.
    //
    require_once 'facebook.php';
    $appapikey = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxx'; //Your API key
    $appsecret = 'yyyyyyyyyyyyyyyyyyyyyyyyyyyyy'; //and your secret ;-)
    $facebook = new Facebook($appapikey, $appsecret);
    $user_id = $facebook->require_login();// Login is required

    Delete everything after this code, we will simply say “Hello dear” with user name in our app.
  9. Add following
    echo 'Hello <fb:name uid="', $user_id, '" firstnameonly="true" />!';
  10. Upload all the files in php folder to the server which you provided in Canvas Callback URL.
  11. Go to URL http://app.facebook.com/my-hello-world-app, remember “my-hello-world-app” was Canvas URL for our app.
  12. Voila!!! Your app is ready!

This is a very very very basic app. You can add more interactivity to this app. You need to browse through http://developers.facebook.com/ and you can use my app here -> http://www.facebook.com/apps/application.php?id=111590402213823 which simply reads a flat file db of Bollywood dialogues and prints a random dialogue. It just goes a step further and asks for permission to publish the dialogue on profile wall. I have a test profile which is using this app and you can look at the wall: http://www.facebook.com/profile.php?id=100001044906526

Share LAMP Web Development Blog:
  • Print
  • PDF
  • email
  • Digg
  • del.icio.us
  • Facebook
  • Slashdot
  • Mixx
  • Google Bookmarks
  • FriendFeed
  • IndianPad
  • LinkedIn
  • Live
  • MSN Reporter
  • Netvibes
  • Sphinn
  • NewsVine
  • Reddit
  • StumbleUpon
  • Technorati
  • Twitter
  • Twitthis
  • Wikio IT
  • Yahoo! Bookmarks
  • Yahoo! Buzz