handling request wsgi
handling request wsgi

Handling Request in WSGI Application

Posted on

We could handle requests sent by web browser in WSGI application either GET or POST requests. We use QUERY_STRING variable for handling GET request, then we use CONTENT_LENGTH and wsgi.input variables for handling POST request. I use python 3.10 for examples.

Handling GET Request

We could use this code as example to handle GET request in WSGI, just copy-paste the code in notepad++, save file as get.py and run on our python environment. I my self use anaconda environment installed in my computer.

Open your anaconda terminal, activate the environment, change directory where the get.py file existed, and run command “python get.py”

Next, open your web browser and write on the address bar “localhost:5000”, load the page, input the firstname and lastname, klik the send button and see what happen.

Finally, we’ve succeded to run the code for handling GET request.

The explanations for the code:

Since we handle GET request, so the query string showed on URL is “localhost:5000/?firstname=Danny&lastname=Tan”. The code a=parse_qs(environ[‘QUERY_STRING’]) will convert the query string to the form of Dictionary (dict). Thus the letter “a” is an object of dictionary, so we invoke element from the object a by method get() which we can found in the code “firstname=a.get(‘firstname’)[0]” to invoke the firstname element from object “a”. Since I use python 3, so I change the “code return[body]” into “return[body.encode()]”. It’s because wsgi is made for python 2.

Handling POST Request

Use this code to handle GET request in WSGI. Copy-paste the code in notepad++, save file as post.py and run on your python environment.

Open your anaconda terminal, activate the environment, change directory where the post.py file existed, and run command “python post.py”

Next, open your web browser and write on the address bar “localhost:5000”, load the page, input the firstname and lastname, klik the send button.

Finally, we’ve succeded to run the code for handling POST request.


Leave a Reply

Your email address will not be published. Required fields are marked *