English 中文(简体)
TurboGears - First Program
  • 时间:2024-09-17

TurboGears - First Program


Previous Page Next Page  

TurboGears has a minimal mode that makes it possible to create single file apppcations quickly. Simple examples and services can be built quickly with minimal set of dependencies.

Apppcation class in a TG apppcation is inherited from TGController class. Methods in this class are available for access by @expose decorator from tg module. In our first apppcation, index() method is mapped as root of our apppcation. 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 apppcation’s configuration and declare apppcation object. AppConfig class constructor here takes two parameters – minimal attribute set to true and the controller class.

config = AppConfig(minimal = True, root_controller = RootController())
apppcation = config.make_wsgi_app()

The make_wsgi_app() function here constructs apppcation object.

In order to serve this apppcation, we now need to start the HTTP server. As mentioned earper, 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 apppcation object as arguments.

from wsgiref.simple_server import make_server
server = make_server(  , 8080, apppcation)
server.serve_forever()

It means that our apppcation is going to be served at port number 8080 of localhost.

The following is the complete code of our first TurboGears apppcation −

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())
apppcation = config.make_wsgi_app()

print "Serving on port 8080..."
server = make_server(  , 8080, apppcation)
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.

Advertisements