Initial import to Tizen
[profile/ivi/python-twisted.git] / doc / web / examples / fortune.rpy.py
1 # Copyright (c) Twisted Matrix Laboratories.
2 # See LICENSE for details.
3
4 """
5 This example demostrates 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, rename the file to fortune.rpy, and move it 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 from twisted.python import util
26
27 class FortuneResource(Resource):
28     """
29     This resource will only repond to HEAD & GET requests.
30     """
31     # Link your fortune program to /usr/games or change the path.
32     fortune = "/usr/games/fortune"
33
34     def render_GET(self, request):
35         """
36         Get a fortune and serve it as the response to this request.
37
38         Use L{utils.getProcessOutput}, which spawns a process and returns a
39         Deferred which fires with its output.
40         """
41         request.write("<pre>\n")
42         deferred = utils.getProcessOutput(self.fortune)
43         deferred.addCallback(lambda s:
44                              (request.write(s+"\n"), request.finish()))
45         deferred.addErrback(lambda s:
46                      (request.write(str(s)), request.finish()))
47         return server.NOT_DONE_YET
48
49 resource = FortuneResource()