Express for Node.js

Express is a simple web application framework for building hybrid web applications. You can render web pages, generate  customized responses and create user-friendly APIs quickly with ease. It just fits the trade with Node.js.

This post covers the installation and hello world example:

Installation:

buntu@ubuntu:~$ sudo npm install express
express@3.1.0 node_modules/express
├── methods@0.0.1
├── fresh@0.1.0
├── cookie-signature@0.0.1
├── range-parser@0.0.4
├── buffer-crc32@0.1.1
├── cookie@0.0.5
├── debug@0.7.2
├── commander@0.6.1
├── mkdirp@0.3.3
├── send@0.1.0 (mime@1.2.6)
└── connect@2.7.2 (pause@0.0.1, bytes@0.1.0, formidable@1.0.11, qs@0.5.1)

Hello World Example:

In the above example:

  • 1. express module is imported and application object is created
  • 2. Object’s get() method is called and callback is set to respond with ‘hello world’
  • 3. When user sends a GET request at port 3000, an event is generated that is handled by callback function(request, response)
Advertisements

Tornado – Autoreload

One of the most irritating (i would say) things about web development is about restarting your web server whenever there’s a change in the code base or the template files to test if the development change has been propagated correctly… If you’re a web developer you know exactly about the agony I’m referring to… Well, Tornado has something to offer in this realm as well..

tornado.autoreload module automatically detects development changes and restarts the server when a module is modified. Not only that, it can also restart when a monitored file has changed. (File change acts as a trigger) Moreover, the developer can hook into the restart call and execute a method call just before the server restarts. Let’s see all the above features with code snippets.

Example 1:

In this example, tornado.autoreload() re-starts the web server when there is a change in tornadoreload.py file. Sequence of events go like this:

  • When user runs tornadoreload.py app, you don’t see any message on command line and ioloop has started.
  • On browsing to http://localhost:8000/, Main class handles the GET request and renders ‘Main’ on the web page
  • With the web server still running, open another terminal and edit tornadoreload.py to change say ‘Main’ to ‘MainO’
  • Refer to the terminal where you are running the server, you would notice a message stating ‘Hooked before reloading…’.
  • This is because when tornadoreload.py has changed, web server restarts with tornado.autoreload.start() and also before restarting it calls the hooked function with tornado.autoreload.add_reload_hook(fn) where the method fn() prints the ‘Hooked before reloading…’ message on command line..
  • And if you refresh your browser, you would see ‘MainO’ pertaining to the change in tornadoreload.py app
  • So as a web developer, you’re free.. 🙂 But restart is destructive and cancels the pending requests..

Example 2:

In this example, we demonstrate how tornado can restart based on a change in watched (monitored) file. Here, the file ‘watch’ is being monitored for change for tornado to restart.. Also note tornado gets restarted when the app and any modules imported in the app are changed.

 

Many applications built on Tornado don’t use these and often end up using debug=True in tornado.web.Application constructor, which is also useful in detecting changes in module and static file content.

Tornado – Internationalization

 

Web development often calls for internationalization (i18n), Tornado provides this facility with tornado.locale class.

In the example below, we create request handlers to cater to users request for different locale. For instance, DEHandler renders a standard web page (locale_template.html) in German language after translating the English words from the template.

Translation is governed by de_DE.csv file located under translation folder.

 

Tornado – Cookies

Cookies are used by web developers or designers to store data on the client side. When user submits some information to the server, the server takes a decision based on posted data and redirects the user to relevant page. But when user browses to all together a different page, this information is lost. Cookies help to store this information across web pages. Cookies could be persistent (until expired) or temporary (deleted when browser is closed) as designed by developer.

Tornado has methods can set/get cookies. Let see how with this example:

In the above example,

1. When user browses to http://127.0.0.1:8888/user/, web server checks if it finds any cookie with name ‘technobeans’. If not, it sets a cookie with name ‘technobeans’ and renders a web page stating ‘Cookie is now set’.

2. If this web page is refreshed (with cookie still set), web page renders a message ‘Cookie is technobeans’.

User behavior in the above two cases is mimicked with tornadocookierequest.py and tornadocookieresponse.txt depicts the response and content returned by web server for the requests.

Deleting a cookie

Cookies can be cleared with a method clear_cookie(). For instance, if cookie with name “user” needs to be deleted, it can be done as

self.clear_cookie("user")

Tornado – Error Handling

Web development often calls for gracefully handling of non-existent pages or broken links that users request for. A simple way to achieve error handling in Tornado is with:

  • tornado.web.HTTPError - Exception handler that can used to generate error code of specified type. 
    It is often used to raise an exception as we would see in the example below
  • send_error - Generates an error page of the status code provided along with error description if debug=True

In the example below, when user generates a GET request on http://127.0.0.1:8888/articles/, articles along with author names are shown up.

But when GET request is made on http://127.0.0.1:8888/articles/1, since there is no Id implementation for articles page, error is handled with self.send_error(500) or raise tornado.web.HTTPError(404, ‘Page Not Found Error!!’)

Case1: raise tornado.web.HTTPError(404, ‘Page Not Found Error!!’) is enabled

  • Traceback (most recent call last):                                          —– Traceback is noticed on web page
    File “/home/ubuntu/tornado-2.2/tornado/web.py”, line 988, in _execute
    getattr(self, self.request.method.lower())(*args, **kwargs)
    File “errorhandling.py”, line 12, in get
    raise tornado.web.HTTPError(400, ‘Page Not Found Error!!’)
    HTTPError: HTTP 400: Bad Request (Page Not Found Error!!)
  • WARNING:root:400 GET /articles/1 (127.0.0.1): Page Not Found Error!!     —– Error description where web server is running
    WARNING:root:400 GET /articles/1 (127.0.0.1) 10.68ms

Case2: self.send_error(500) is enabled

  • ‘500: Internal Server Error’ web page shows up
  • ERROR:root:500 GET /articles/1 (127.0.0.1) 0.41ms error line is generated where web server is running

Example:

Tornado – Templates – Run time and Cached

Website development often calls for reuse of pages. For instance, when you open your Citibank account after login the welcome page you see is same what other bank customers see but its customized with your name and settings. Do you think Citi creates so many web pages for all its customers? Well, they use, what’s called as template. Template is a layout or a skeleton that separates content from presentation and helps in mass production of web pages..

Control Statements in Templates

Tornado supports templates with expressions and control statements; straight from Tornadoweb, “Control statements are surronded by {% and %}, e.g., {% if len(items) > 2 %}. Expressions are surrounded by {{ and }}, e.g., {{ items[0] }}.”

In the above example, we have created a template (template.html) that requires a scalar value for title and a dictionary for listing dictionary items in the form of a table (List data types also work well in Tornado templates). The python code provide these values in the code line

self.render(‘template.html’, title=’Articles’, dict=articles)

Output

tornado templates example

Run-time Template Generation and Compiling Templates

Let’s now understand two important methods in Tornado templates, how do they work and how are they implemented:

  1. Template()
  2. Loader()

Template() – helps in generating a template at run time. For instance, there is a web page with lesser content and that need not be rendered quite often, we can utilize this Template method.

Loader() – helps in compiling and caching templates from a predefined location of your machine. Compiling and caching improves performance of web server while rendering web pages.

Example 2

In example 2,

t = Template(“<html>{{ name }}</html>”) — generates template at run time

self.write(loader.load(“template.html”).generate(name=”John”))  — template is compiled, cached and loaded