Handlers in web application

66 views Asked by At

I am new to web app development. The pyhton file which displays 'Hello World' in the browser is

import webapp2

class MainHandler(webapp2.RequestHandler):
    def get(self):
        self.response.write('Hello World')

app = webapp2.WSGIApplication([('/', MainHandler)
], debug=True)

What I couldn't understand is the function of the line

app = webapp2.WSGIApplication([('/', MainHandler) ], debug=True)

I have searched the net for the answer but failed to get a satisfactory answer. It would be great if anyone would explain it considering I am a beginner.

2

There are 2 answers

0
Hett On

By this line your're creating your wsgi web application.

app = webapp2.WSGIApplication([('/', MainHandler) ], debug=True)

So let's break it to smaller parts.

If you're familiar to web programming in any language (and in general to concept), you should know that your server should know what url's is he going yo serve. In your case you have registered "/" (root) url, which is the same as http://127.0.0.1/. And also you have defined that the response for "/" url will provide MainHandler class.

('/', MainHandler)

So when the request will reach your wsgi server it will be redirected to your MainHandler's get method. In general your get handler should make a proper http response. As your MainHandler class inherited from the webapp2.RequestHandler class it already have some tools to make a response, so you will not take care about http headers and so. By the following line you're forming the response, which is in your case just a simple string "Hello World".

self.response.write('Hello World')

After your get function invocation the wsgi server will send back to the browser already formed http response like this:

HTTP/1.1 200 OK
Content-Type: text/plain
Content-Length: length

Hello World.

You can also check this tutorial for further details on webapp2 framework.

Good luck.

0
deathangel908 On

As far as I understand webapp2.WSGIApplication creates a new listener on default port. When you type 127.0.0.1/ a browser will send a request to your application that listens the default port (I assume it's 80). The webapp2.WSGIApplication listener will create a new instance of MainHandler for this request (and for every single request it receives) Then WSGIApplication will trigger get overridden method of MainHandler to generate output. In the end of the day WSGIApplication will serve back output text.