MyApplication.py
- this is our module.MyResource
and in principle it will have a structure that looks like this:
class MyResource:
def respond(self, trans):
[Examine the transaction, decide what the user wants to do.]
[Perform some kind of action with the information supplied.]
[Produce some kind of response which tells the user what happened.]
It is in this kind of resource
class that we write the
actual application code or at least the beginnings of it. When a user
of the application sends us a request,
the respond
method
will be called and the code
within it executed. The parts of the pseudo-code in
the above text which aren't valid Python
(ie. the bits in square brackets) will, when we have written them, use
the trans
object to find out what any given user of the application has sent us,
and to send information back
to the
user in response.
The simplest way to turn this into a working application is to ignore the first two activities mentioned in the pseudo-code and just to produce some kind of response. Here is how we can make our application do something:
MyApplication.py
.MyResource
:class MyResource:
def respond(self, trans):
out = trans.get_response_stream()
print >>out, "Hello world."
To test this resource we need to deploy it, and to do that we need an adapter to connect it to the outside world. Here is a quick way of writing an adapter and testing this code:
MyAdapter.py
- you
can choose another name if you want - this will be where the adapter
code lives.from WebStack.Adapters.BaseHTTPRequestHandler import deploy # import the support for the server environment
from MyApplication import MyResource # import the main resource class
print "Serving..." # just for testing - we might want to remove this later
deploy(MyResource()) # connect a resource object to the server environment
Now, with two files in your directory, MyApplication.py
and MyAdapter.py
, you may run MyAdapter.py
as follows:
python MyAdapter.py
This should start the adapter program and print the following message:
Serving...
You should now be able to visit http://localhost:8080
in your
browser and see the message printed by your application:
Hello world.
The code presented in this document is very similar to that found in the following files:
examples/Common/VerySimple/__init__.py
(where a package, VerySimple
, is used to hold a VerySimpleResource
class)examples/BaseHTTPRequestHandler/VerySimpleApp.py
(where the resource is deployed)Note that a number of different adapters are provided in the examples
directory hierarchy; for example:
examples/CGI/VerySimpleHandler.py
(deploys the example as a CGI script)examples/Twisted/VerySimpleApp.py
(deploys the example as a Twisted application)See "Deploying a WebStack Application" for more information about adapters.