Python Pyramid – Hello World


Python Pyramid – Hello World



”;


Example

To check whether Pyramid along with its dependencies are properly installed, enter the following code and save it as hello.py, using any Python-aware editor.


from wsgiref.simple_server import make_server
from pyramid.config import Configurator
from pyramid.response import Response

def hello_world(request):
   return Response(''Hello World!'')
   
if __name__ == ''__main__'':
   with Configurator() as config:
      config.add_route(''hello'', ''/'')
      config.add_view(hello_world, route_name=''hello'')
      app = config.make_wsgi_app()
   server = make_server(''0.0.0.0'', 6543, app)
   server.serve_forever()

The Configurator object is required to define the URL route and bind a view function to it. The WSGI application object is obtained from this config object is an argument to the make_server() function along with the IP address and port of localhost. The server object enters a listening loop when serve_forever() method is called.

Run this program from the command terminal as.


Python hello.py

Output

The WSGI server starts running. Open the browser and enter http://loccalhost:6543/ in the address bar. When the request is accepted, the hello_world() view function gets executed. It returns the Hello world message. The Hello world message will be seen in the browser window.


Hello World

As mentioned earlier, the development server created by make_server() function in the wsgiref module is not suited for production environment. Instead, we shall use Waitress server. Modify the hello.py as per the following code −


from pyramid.config import Configurator
from pyramid.response import Response
from waitress import serve

def hello_world(request):
   return Response(''Hello World!'')
   
if __name__ == ''__main__'':
   with Configurator() as config:
      config.add_route(''hello'', ''/'')
      config.add_view(hello_world, route_name=''hello'')
      app = config.make_wsgi_app()
      serve(app, host=''0.0.0.0'', port=6543)

All other functionality is same, except we use serve() function of waitress module to start the WSGI server. On visiting the ”/” route in the browser after running the program, the Hello world message is displayed as before.

Instead of a function, a callable class can also be used as a view. A callable class is the one which overrides the __call__() method.


from pyramid.response import Response
class MyView(object):
   def __init__(self, request):
      self.request = request
   def __call__(self):
      return Response(''hello world'')

Advertisements

”;

Leave a Reply

Your email address will not be published. Required fields are marked *