Книга: Learning Concurrency in Python
Назад: Twisted
Дальше: Gevent

A simple web server example

Twisted is absolutely ideal for doing things such as serving websites. We can set up a simple TCP server that listens on a particular endpoint that can serve files from a relative file location to someone requesting it in a browser.

In this example, we'll set up a very simple web server that serves local content from a tmp directory within the same directory as your program.

We will first import the necessary parts of the twisted.web and twisted.internet modules. We will then define an instance of the file resource that maps to the directory we wish to serve. Below this, we will create an instance of the site factory using our newly defined resource.

Finally, we will map our Site factory to a TCP port and start listening before calling reactor.run(), which drives our entire program by handling things such as accepting any incoming TCP connections and passing bytes in and out of the said connections:

from twisted.web.server import Site
from twisted.web.static import File
from twisted.internet import reactor, endpoints

resource
= File('tmp')
factory = Site(resource)
endpoint = endpoints.TCP4ServerEndpoint(reactor,
8888)
endpoint.listen(factory)
reactor.run()

We'll serve this very simple .html file, which features a <h1> tag within its body. Nothing special, but it represents a good starting point for any website:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device
width, initial-scale=1.0"
>
<meta http-equiv="X-UA-Compatible"
content="ie=edge">
<title>Twisted Home Page</title>
</head>
<body>
<h1>Twisted Homepage</h1>
</body>
</html>

Upon running the preceding code, navigate to http://localhost:8888 in your local browser, and you should see our newly created website in all it's glory being served up.

This represents just a very small fraction of what the Twisted framework is capable of, and unfortunately, due to concerns for the brevity of this book, I cannot possibly divulge all of its inner workings. The overall power of this framework is incredible, and it has been a joy working with it in the past.

Назад: Twisted
Дальше: Gevent