The magic of Twisted: create your own web server

  

In many cases, we will need a web server, but you may not know how to implement it yourself. It is ok to implement it. Just use Twisted and the method is below. It doesn't need to be too much to realize the advantages of the Web server itself, mainly to control the specific implementation. You can also interact in accordance with your own habits.

And Twisted is written in C below tcp, ip and udp should be a mixture of C and Python, and httpsmtp and so on are Python, which can be well extended.

Let's look at a concrete example:

First you need to edit the name of a file ending with html and put it in your htm directory.

Then create a file in the upper directory of htm, the file name is web.py, the content is as follows:

Code:

[code:1:79fbd7e444]< Br>

PORT=80# This is 80. If your port is occupied, change to other

fromtwisted.web.resourceimportResource

fromtwisted.webimportserver

fromtwisted.webimportstatic

fromtwisted.internetimportreactor

classReStructured(Resource):

def__init__(self,filename,*a):

self.rst= Open(filename).read()

defrender(self,request):

returnself.rst

resource=static.File('./htm/')< Br>

resource.processors={'.html' :ReStructured}

resource.indexNames=['index.html']

reactor.listenTCP(

PORT,

server.Site(resource)

)

reactor.run()

[/code:1:79fbd7e444]

Enter the directory under the console and type pythonweb.py, then hit Open a browser, enter http://127.0.0.1, see your site?

Now try to see how to achieve it, methods and operations are simple, you can do it step by step It is a good thing to be able to implement the web server by yourself. There are many advantages. If you need it, you may wish to try it.

Copyright © Windows knowledge All Rights Reserved