Skip to content

Instantly share code, notes, and snippets.

@node
Created November 24, 2011 07:02
Show Gist options
  • Save node/1390796 to your computer and use it in GitHub Desktop.
Save node/1390796 to your computer and use it in GitHub Desktop.
Getting start with twisted
1 Visit http://twistedmatrix.com to learn twisted
2 Visit http://twistedmatrix.com/trac/wiki/Downloads to download twisted and zope.interface (required on windows)
3 Setup twisted and zope.interface( need setuptoools/easy_isntall, download by http://pypi.python.org/packages/2.6/s/setuptools/setuptools-0.6c11.win32-py2.6.exe#md5=1509752c3c2e64b5d0f9589aafe053dc)
4 Run example code from twisted website:
- Easy Custom Servers and Clients
Twisted makes it easy to implement custom network applications, both servers and clients. Here's a TCP server that echoes back everything that's written to it:
from twisted.internet import protocol, reactor
class Echo(protocol.Protocol):
def dataReceived(self, data):
self.transport.write(data)
class EchoFactory(protocol.Factory):
def buildProtocol(self, addr):
return Echo()
reactor.listenTCP(1234, EchoFactory())
reactor.run()
- Event-Driven Web Applications ¶
Twisted includes an event-driven web server. Here's a sample web application:
from twisted.web import server, resource
from twisted.internet import reactor
class HelloResource(resource.Resource):
isLeaf = True
numberRequests = 0
def render_GET(self, request):
self.numberRequests += 1
request.setHeader("content-type", "text/plain")
return "I am request #" + str(self.numberRequests)
reactor.listenTCP(8080, server.Site(HelloResource()))
reactor.run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment