[Twisted-web] Re: Can someone translate this, please?

David Bolen twisted-web@twistedmatrix.com
26 Feb 2004 20:32:57 -0500


Phil Hunt <phil.hunt@tech.mrc.ac.uk> writes:

> rosetta1 kind-of does what I want, but not quite, when I try to fetch
> the URL <http://localhost:1450/xxx?aaa=bbb&c=12345> in my web browser,
> it says request.path = /xxx, whereas I'm interested in the variable/value
> pairs as well, i.e. /xxx?aaa=bbb&c=12345

Ah, yeah, that would be a difference between that and the simpler HTTP
handler object in the standard library.  The Twisted support code
automatically parses out the arguments for you and makes them
available from the request object (passed in to the render method in
rosetta1) in the args attribute.  It's a dictionary keyed by variable,
with the value being a list of values supplied.  The value is always a
list even if only one instance of the variable occurs in the URL.

So in your example here, in the render() method, request.args would be
set to {'aaa':['bbb'],'c':['12345']}.

> If I wrote a program like this that was invoked by the ``python'' program
> rather than ``twistd'', would that make a difference it what it can do?

Not particularly - you can pretty much do anything in either case, but
the sequence of how to initialize things (and how much work you might
need to do to accomplish a particular initialization) will differ.
twistd provides some standard startup handling, but you can initialize
things and run the reactor yourself if you want.

For example, one way to have a more standalone version would be to
replace the bottom portion of rosetta1 (starting from "application = "
down) with:

    site = server.Site(resource=MyResource())
    reactor.listenTCP(1450, site)
    reactor.run()

and you'd need a "from twisted.internet import reactor" at the top
(and could remove the application imports).  It's not exactly
identical since the application/service approach is initializing a
more flexible framework, but for this example, the end result is the
same.  With the above change you could just run the script with
Python.

You can pretty much do anything you want at that point, although you
need to get to the reactor.run() for most stuff to start running.

You can also hang other services off of your application object and do
other initialization in the twistd/tac case.  I don't tend to use twistd
that much myself, but I'm sure for others it's what they prefer.

Oh, and if you'd like to see some simple logging of requests and what
not you can just enable logging by:

    import sys
    from twisted.python import log

at the top, and

    log.startLogging(sys.stdout)

before creating your site.  I think the equivalent is just a command
line option with twistd.

-- David