[Twisted-web] documentation -- Techno Turkey's fifth adventure

lloyd at paisite.com lloyd at paisite.com
Sat Jul 15 14:40:24 CDT 2006


Hi Folks,

Here's a rough first draft of Techno Turkey's latest adventure. I've tried
to capture and integrate both Valentino and Daniel's ideas, but if I've
missed or misrepresented anything, please advise.

I haven't had a chance yet to finish setting up my own Twisted development
environment, so I haven't been able to test it. In preparing to set up my
environment, however, I realized that there may be conventions in the
community (directory layout and naming, for example) that would be very
helpful for turkey's like me.

So I've left a hole in the Turkey script for a link to a page (yet to be
written) that lay's out best practices for down-loading Twisted/Nevow and
setting up a productive development environment. My thought was that we
could put this page on the Turkey site, or elsewhere in the Twisted/Nevow
docs, then I could simply link to it from whereever appropriate in Turkey
scripts.

Anybody around to help me write the page? Or, if such a page already
exists, please point me to it.

Best wishes,

Lloyd

PS: I've been reviewing current Twisted/Nevow documentation. Much much
better than I remember from last year. Nevow tutorial is excellent.

So here's... Techno Turkey


Dialtone's Resource Magic


"It's magic!" said Techno Turkey.

"What's magic?" asked Twisted Wizard Daniel.

"I just type it in at the top of my browser and... shazamm... back comes
just the page I'm looking for -- could be from anywhere in the world. It's
like casting a magic spell."

"It's far more magical than you think," says Twisted Wizard Daniel. "Just
consider it's name: 'Uniform Resource Identifier' -- URI."

"I thought it was a URL," said Turkey.

"That was before people understood it's full mojo. Back then they called
it a 'Uniform Resource Locator.' But then they realized that it could be
used to identify anything in cyberspace."

"Anything?" asked Turkey.

"Sure, anything. We use URI's to identify servers, webpages, web services,
images, sound files..."

"But the only thing I ever get back are webpages."

"That's because that's what static HTTP webservers do. They listen for
their designated URI and return the specified HTML web page. But aided by
the right software, they can return anything of a digital nature."

Twisted Wizard Dialtone happened to be listening in.

"Hey, Turkey old bird," said Daniel, "Want to see my Resource magic?"

"The bird's computer got trashed by an electrical storm, remember," said
Daniel.

"No surge protection? No backup?"

"Don't rub it in," said Turkey.

"Never mind, here's how get back up and running again..."

***************

Need link here to step-by-step load and set up instructions for Twisted and
Nevow from both Twisted/Nevow sites and Debian.

Download Twisted from: http://twistedmatrix.com/products/download
Download Nevow from: http://divmod.org/trac/wiki/DivmodNevow#Download

Debian users can get the latest alpha, rc, or release by adding the
following to their /etc/apt/sources.list:

    Woody: deb http://twisted.sourceforge.net/debian/woody/ ./
        Sid/Sarge: deb http://twisted.sourceforge.net/debian/ ./

Once downloaded:

-- how to find Twisted and Nevow source directories
-- how to set up development environment
-- how to set up working directories -- user source, logs,
-- how to set up path variables
-- how to test development environment

Should be sufficiently detailed that even the slowest turkey on the farm
can implement.

Anybody up for fleshing in details for this page? I can edit, put it up on
the Turkey server, and link it into Turkey adventures.

***************

"Now, create a file called ResourceMagic.py in your Twisted source
directoy, and enter the following code:"


from zope.interface import implements

from nevow import inevow

##
## How does a request come to the Resource?
##
## or How to use Nevow without all the fancy automations
##

class Root(object):
    # This is a simple resource, representing the root, or top-most

    # resource of this site.  The inevow.IResource interface
    # tells us that it must implement two methods:
    # locateChild and renderHTTP.
    # locateChild is used to find children of the current resource.  It must
    # return a tuple of (resource, remaining_segments).  If no child resource
    # exists at this location, you may return nevow.rend.NotFound."
    # For more information see:
    # http://divmod.org/users/exarkun/nevow-doc/nevow-traversal.html
    implements(inevow.IResource)

    def locateChild(self, ctx, segments):
        # This locateChild is 'stupid' since it can only work if the tree of
        # resources is static. But it will work for our simple example
        if segments[0] == '':
            # If the server is looking for the root resource segments will
be ('',)
            # then renderHTTP will be called on self
            return self, ()
        elif segments[0] == 'foo':
            # Now we received a request whose segments had in the first
position
            # the string foo like http://example.org/foo/baz/ -> ('foo',
'baz').
            # After the resource has been located we return it with the
remaining segments
            # ('baz')
            return self.foo, segments[1:]

        else:
            return None, ()

    def renderHTTP(self, ctx):
        # When the server needs to return a response to the request it
will call
        # the renderHTTP method that will return a string of what needs to
be sent.
        def renderHTTP(self, ctx):
            return """<html><body>Hello, world!<br />"""

class Foo(object):
    implements(inevow.IResource)

    def locateChild(self, ctx, segments):
        # segments is the remaining segments returned by the root locateChild
        # see segments[1:]
        if segments[0] == 'baz':
            return self.baz, segment[1:]
        else:
            return None, ()

    def renderHTTP(self, ctx):
        return """<html><body><h1 id="heading">You are in Foo</h1>
        <a href="./foo/baz" id="baz">baz</a></body></html>
"""

class Baz(object):
    implements(inevow.IResource)
    def locateChild(self, ctx, segments):
        return None, ()
    def renderHTTP(self, ctx):
        return '<html><body><h1 id="heading">You are in
Baz</h1></body></html>'

# We are adding children to the resources.
# This could also happen inside the class.
root = Root()
root.foo = Foo()
root.foo.baz = Baz()


"Note," said Dialtone, "That this is the IResource interface from Nevow;
not the one from twisted.web."

"So now what?" said Turkey.

"At the end of your ResourceMagic.py source file enter:"

from twisted.internet import reactor
from nevow import appserver
site = appserver.NevowSite(root)
reactor.listenTCP(8080, site)

"Hey, I recognize the reactor bit from earlier adventures, " said
Turkey, "But what's this 'nevow?'"

"Nevow is a web-application construction kit written in Python. Check out
http://divmod.org/trac/wiki/DivmodNevow. But let's keep our eye on the
ball here...

"To cast the spell, just save the ResourceMagic.py file and enter at the
console prompt:"

python ResourceMagic.py

"Then point your browser to:"

http://localhost:8080/

"Wait," said Turkey, "Before we run it, I'm still confused by this word
'Resource.' When you say, 'Resource,' are you talking about web pages?"

"Could be," said Daniel. "But there are many more kinds of Resources than
webpages. A Resource is anything that a URI happens to point to --
anything in cyberspace."

"Well, at least," said Dialtone, "Anything available through the
designated server."

"Like my favorite Radiohead MP3?" said Turky.

"Anything that gets you through the day," said Daniel. "For more info,
check out:"

http://en.wikipedia.org/wiki/Resource_(Web)

"...or:"

http://en.wikipedia.org/wiki/Representational_State_Transfer#Resources

"OK," said Turkey, turning to Dialtone. "How's this magic spell of yours
supposed to work?"

"Well let's run it and see..."


Another way to run the code

Another way to run Dialtone's code uses the tac file approach. Replace
the lines:

from twisted.internet import reactor
from nevow import appserver
site = appserver.NevowSite(root)
reactor.listenTCP(8080, site)

with

from twisted.application import strports, service from nevow import
appserver application = service.Application('example') website =
appserver.NevowSite(root) webservice = strports.service('8080', website)
webservice.setServiceParent(application)

Now, at your browser prompt, enter:

twistd -noy myscript.tac

And point your browser to:

http://localhost:8080/


Anticipated Results:

You should see a root page with "Hello, world!," and a link to a child page
named "foo." Any other url except the one with the child foo will result
in a 404.

If you go in the foo child you'll see a page with the content "you are in
foo" and a link to foo's child page baz. Any other child page will result
in a 404.

If you go in the baz child you'll see a page with the content "you are in
baz." This page has no children and any other url will result in a 404.

How does it work?

Nevow is fundamentally based on the following  request processing schema:

arrives request \
--> root resource \
--> root.locateChild(url segments)
. child_resource.locateChild(url segments[1:])
. child_resource2.locateChild(url segments[2:])
. so forth until url segments == ()
==> FOUND RIGHT RESOURCE
==> RIGHT_RESOURCE.renderHTTP()  \

Where to go from here

Contrast Dialtone's code with Matt Goodall's Barebnes Dynamic Web Server in
Turkey's fourth adventure. Then review:

http://divmod.org/users/exarkun/nevow-doc/nevow-intro.html






-------------- next part --------------
A non-text attachment was scrubbed...
Name: TTResource
Type: application/octet-stream
Size: 8316 bytes
Desc: not available
Url : http://twistedmatrix.com/pipermail/twisted-web/attachments/20060715/a4afac78/TTResource.obj


More information about the Twisted-web mailing list