| 1 |
# Copyright (c) Twisted Matrix Laboratories. |
| 2 |
# See LICENSE for details. |
| 3 |
|
| 4 |
""" |
| 5 |
This example demonstrates how to render the output of a system process to a |
| 6 |
twisted web server. |
| 7 |
|
| 8 |
In order to run this, you need to have fortune installed. Fortune is a simple |
| 9 |
game that displays a random message from a database of quotations. You will need |
| 10 |
to change the path of the fortune program if it's not in the "/usr/game" |
| 11 |
directory. |
| 12 |
|
| 13 |
To test the script, copy fortune.rpy to any |
| 14 |
directory, let's say /var/www/html/ |
| 15 |
|
| 16 |
Now, start your Twisted web server: |
| 17 |
$ twistd -n web --path /var/www/html/ |
| 18 |
|
| 19 |
And visit http://127.0.0.1:8080/fortune.rpy with a web browser. |
| 20 |
""" |
| 21 |
|
| 22 |
from twisted.web.resource import Resource |
| 23 |
from twisted.web import server |
| 24 |
from twisted.internet import utils |
| 25 |
|
| 26 |
|
| 27 |
class FortuneResource(Resource): |
| 28 |
""" |
| 29 |
This resource will only respond to HEAD & GET requests. |
| 30 |
""" |
| 31 |
|
| 32 |
# Link your fortune program to /usr/games or change the path. |
| 33 |
fortune = "/usr/games/fortune" |
| 34 |
|
| 35 |
def render_GET(self, request): |
| 36 |
""" |
| 37 |
Get a fortune and serve it as the response to this request. |
| 38 |
|
| 39 |
Use L{utils.getProcessOutput}, which spawns a process and returns a |
| 40 |
Deferred which fires with its output. |
| 41 |
""" |
| 42 |
request.write(b"<pre>\n") |
| 43 |
deferred = utils.getProcessOutput(self.fortune) |
| 44 |
deferred.addCallback(lambda s: (request.write(s + b"\n"), request.finish())) |
| 45 |
deferred.addErrback( |
| 46 |
lambda s: (request.write(str(s).encode("utf8")), request.finish()) |
| 47 |
) |
| 48 |
return server.NOT_DONE_YET |
| 49 |
|
| 50 |
|
| 51 |
resource = FortuneResource() |