Creating a WSGI application

All the requests that we make to our server will be handled by the WSGI application, which will be a single file. This application will be responsible for handling the requests and returning the appropriate response according to the requested URL. In this application, we will have to define a function that acts with each user's request. This function must be a valid application WSGI function. This means that it should be called application and it should receive two parameters: environ, from the os module, which provides a dictionary of standard HTTP requests and other environment variables, and the start_response function, from WSGI, which is responsible for delivering the HTTP response to the user.

In the following example, we will create a web server that responds to the localhost on port 8080.

You can find the following code in the wsgi_example.py file:

#!/usr/bin/env python3

from wsgiref.simple_server import make_server

def page(content, *args):
yield b'<html><head><title>wsgi_example.py</title></head><body>'
yield (content % args).encode('utf-8')
yield b'</body></html>'

def application(environ, start_response):
# I keep the output that I will return in response
response = "<p>This is my web page built with python wsgi</p>"
# A response to the browser is generated
start_response('200 OK', [('Content-Type', 'text/html; charset=utf-8')])
return page(response)

if __name__ == '__main__':
print('Listening on localhost:8080')
srv = make_server('localhost', 8080, application)
srv.serve_forever()

The controller that we used previously does not take into account the URL that we accessed the server with, and will always generate the same response. Using the information about the request that we have stored in the environ dictionary, we can build different answers according to the request by taking into account the access URL, for example.

The environ dictionary that is received with each HTTP request contains the standard variables of the CGI specification, including the following:

  • REQUEST_METHOD: GET and POST methods
  • SCRIPT_NAME: The initial part of the route, which corresponds to the application
  • PATH_INFO: The second part of the route determines the virtual location within the application
  • QUERY_STRING: The portion of the URL that follows the ?
  • CONTENT_TYPE, CONTENT_LENGTH of the HTTP request
  • SERVER_NAME, SERVER_PORT, that, combined with SCRIPT_NAME and PATH_INFO, give the URL
  • SERVER_PROTOCOL: The protocol version (HTTP/1.0 or HTTP/1.1)

In this way, we can develop a controller to check the access URL and work with the parameters that were sent by the GET method. In this example, we are using the QUERY_STRING environment variable to perform a basic operation by parameters in the URL. For example, if we want to multiply two numbers, we can use these parameters in the URL query string, like so: operation?operator1=2&operator2=10&operation=*.

You can find the following code in the wsgi_example2.py file:

#!/usr/bin/env python3
from wsgiref.simple_server import make_server

def page(content, *args):
yield b'<html><head><title>wsgi_example.py</title></head><body>'
yield (content % args).encode('utf-8')
yield b'</body></html>'

In the first code block, we imported the module for creating our server and defined the function that will generate the HTML page. In the following code block, we are defining the application method for processing the query string and parameters:

def application(environ, start_response):
if environ['PATH_INFO'] == '/':
response = "<p>This is my web page built with python wsgi</p>"
start_response('200 OK', [('Content-Type', 'text/html; charset=utf-8')])
return page(response)
elif environ['PATH_INFO'] == '/operation':
print('environ["QUERY_STRING"]:',environ["QUERY_STRING"])
params = environ["QUERY_STRING"].split("&")
print('Parameters ',params)
operator1 = params[0].split("=")[1]
print('Operator 1:',operator1)
operator2 = params[1].split("=")[1]
print('Operator 2:',operator2)
operation = params[2].split("=")[1]
print('Operation:',operation)
result = str(eval(operator1+operation+operator2))
print('Result:',result)
response = "<p>The operation result is %s</p>" %result
start_response('200 OK', [('Content-Type', 'text/html; charset=utf-8')])
return page(response)
else:
response = "<p>This URL is not valid</p>"
start_response('404 Not Found', [('Content-Type', 'text/html; charset=utf-8')])
return page(response)

Finally, we have our main program for creating the server in localhost 8080, which we provide by using the application method defined in the previous code block:

if __name__ == '__main__':
print('Listening on localhost:8080')
server = make_server('localhost', 8080, application)
server.serve_forever()

In the following screenshot, we can see the execution of the wsgi_example2.py script, where we can see the server running in localhost:8080. When we invoke the operator url endpoint, it shows information about the operation and the result:

In this section, we have introduced the wsgiref.simple_server package to create a web page that's been developed with Python using the WSGI standard, which is a specification of a universal interface between web servers and web applications.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset