Building a Twisted web server

Twisted contains a series of classes and utilities to create various types of servers and clients. It is possible to create configurations for web servers and configurations to use the SSL protocol between clients and servers. In this example, we are developing a server that receives HTTP requests.

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

#!/usr/bin/env python3

from twisted.internet import reactor
from twisted.web import server, resource

class TwistedResource(resource.Resource):
def render_GET(self, request):
return b"<html><center><h1>Twisted server is running on port 8080</h1></center></html>"

root = resource.Resource()
root.putChild(b"twisted", TwistedResource())
site = server.Site(root)
reactor.listenTCP(8080, site)
reactor.run()

The following is the output of the web server after executing this script:

In this section, we have analyzed how to create our own server with Twisted by using the event loop that was provided by the twisted.internet package.

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

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