TurboGears has a minimal mode that makes it possible to create single file applications quickly. Simple examples and services can be built quickly with minimal set of dependencies.
Application class in a TG application is inherited from TGController class. Methods in this class are available for access by @expose decorator from tg module. In our first application, index() method is mapped as root of our application. The TGController class also needs to be imported from tg module.
from tg import expose, TGController class MyController(TGController): @expose() def index(self): return 'Hello World turbogears'
Next, set the application’s configuration and declare application object. AppConfig class constructor here takes two parameters – minimal attribute set to true and the controller class.
config = AppConfig(minimal = True, root_controller = RootController()) application = config.make_wsgi_app()
The make_wsgi_app() function here constructs application object.
In order to serve this application, we now need to start the HTTP server. As mentioned earlier, we shall use simple_server module in wsgiref package to set up and start it. This module has make_server() method which requires port number and application object as arguments.
from wsgiref.simple_server import make_server server = make_server('', 8080, application) server.serve_forever()
It means that our application is going to be served at port number 8080 of localhost.
The following is the complete code of our first TurboGears application −
app.py
from wsgiref.simple_server import make_server from tg import expose, TGController, AppConfig class MyController(TGController): @expose() def index(self): return 'Hello World TurboGears' config = AppConfig(minimal = True, root_controller = MyController()) application = config.make_wsgi_app() print "Serving on port 8080..." server = make_server('', 8080, application) server.serve_forever()
Run the above script from Python shell.
Python app.py
Enter http://localhost:8080 in browser’s address bar to view ‘Hello World TurboGears’ message.
The tg.devtools of TurboGears contains Gearbox. It is a set of commands, which are useful for management of more complex TG projects. Full stack projects can be quickly created by the following Gearbox command −
gearbox quickstart HelloWorld
This will create a project called HelloWorld.