Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
pyramid.pdf
Скачиваний:
10
Добавлен:
24.03.2015
Размер:
3.82 Mб
Скачать

CHAPTER

FOUR

CREATING YOUR FIRST PYRAMID APPLICATION

In this chapter, we will walk through the creation of a tiny Pyramid application. After we’re finished creating the application, we’ll explain in more detail how it works.

4.1 Hello World

Here’s one of the very simplest Pyramid applications:

1 from wsgiref.simple_server import make_server

2 from pyramid.config import Configurator

3 from pyramid.response import Response

4

5 def hello_world(request):

6return Response(’Hello %(name)s!’ % request.matchdict)

7

8 if __name__ == ’__main__’:

9config = Configurator()

10config.add_route(’hello’, ’/hello/{name}’)

11config.add_view(hello_world, route_name=’hello’)

12app = config.make_wsgi_app()

13server = make_server(’0.0.0.0’, 8080, app)

14server.serve_forever()

31

4. CREATING YOUR FIRST PYRAMID APPLICATION

When this code is inserted into a Python script named helloworld.py and executed by a Python interpreter which has the Pyramid software installed, an HTTP server is started on TCP port 8080.

On UNIX:

$ /path/to/your/virtualenv/bin/python helloworld.py

On Windows:

C:\> \path\to\your\virtualenv\Scripts\python.exe helloworld.py

This command will not return and nothing will be printed to the console. When port 8080 is visited by a browser on the URL /hello/world, the server will simply serve up the text “Hello world!”. If your application is running on your local system, using http://localhost:8080/hello/world in a browser will show this result.

Each time you visit a URL served by the application in a browser, a logging line will be emitted to the console displaying the hostname, the date, the request method and path, and some additional information. This output is done by the wsgiref server we’ve used to serve this application. It logs an “access log” in Apache combined logging format to the console.

Press Ctrl-C (or Ctrl-Break on Windows) to stop the application.

Now that we have a rudimentary understanding of what the application does, let’s examine it piece-by- piece.

4.1.1 Imports

The above helloworld.py script uses the following set of import statements:

1

2

3

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

from pyramid.response import Response

The script imports the Configurator class from the pyramid.config module. An instance of the Configurator class is later used to configure your Pyramid application.

Like many other Python web frameworks, Pyramid uses the WSGI protocol to connect an application and a web server together. The wsgiref server is used in this example as a WSGI server for convenience, as it is shipped within the Python standard library.

The script also imports the pyramid.response.Response class for later use. An instance of this class will be used to create a web response.

32

4.1. HELLO WORLD

4.1.2 View Callable Declarations

The above script, beneath its set of imports, defines a function named hello_world.

1 def hello_world(request):

2return Response(’Hello %(name)s!’ % request.matchdict)

The function accepts a single argument (request) and it returns an instance of the pyramid.response.Response class. The single argument to the class’ constructor is a string computed from parameters matched from the URL. This value becomes the body of the response.

This function is known as a view callable. A view callable accepts a single argument, request. It is expected to return a response object. A view callable doesn’t need to be a function; it can be represented via another type of object, like a class or an instance, but for our purposes here, a function serves us well.

A view callable is always called with a request object. A request object is a representation of an HTTP request sent to Pyramid via the active WSGI server.

A view callable is required to return a response object because a response object has all the information necessary to formulate an actual HTTP response; this object is then converted to text by the WSGI server which called Pyramid and it is sent back to the requesting browser. To return a response, each view callable creates an instance of the Response class. In the hello_world function, a string is passed as the body to the response.

4.1.3 Application Configuration

In the above script, the following code represents the configuration of this simple application. The application is configured using the previously defined imports and function definitions, placed within the confines of an if statement:

1 if __name__ == ’__main__’:

2config = Configurator()

3config.add_route(’hello’, ’/hello/{name}’)

4 config.add_view(hello_world, route_name=’hello’)

5app = config.make_wsgi_app()

6server = make_server(’0.0.0.0’, 8080, app)

Let’s break this down piece-by-piece.

4.1.4 Configurator Construction

33

4. CREATING YOUR FIRST PYRAMID APPLICATION

1

2

if __name__ == ’__main__’: config = Configurator()

The if __name__ == ’__main__’: line in the code sample above represents a Python idiom: the code inside this if clause is not invoked unless the script containing this code is run directly from the operating system command line. For example, if the file named helloworld.py contains the entire script body, the code within the if statement will only be invoked when python helloworld.py is executed from the command line.

Using the if clause is necessary – or at least best practice – because code in a Python .py file may be eventually imported via the Python import statement by another .py file. .py files that are imported by other .py files are referred to as modules. By using the if __name__ == ’__main__’: idiom, the script above is indicating that it does not want the code within the if statement to execute if this module is imported from another; the code within the if block should only be run during a direct script execution.

The config = Configurator() line above creates an instance of the Configurator class. The resulting config object represents an API which the script uses to configure this particular Pyramid application. Methods called on the Configurator will cause registrations to be made in an application registry associated with the application.

4.1.5 Adding Configuration

1

2

config.add_route(’hello’, ’/hello/{name}’) config.add_view(hello_world, route_name=’hello’)

First line above calls the pyramid.config.Configurator.add_route() method, which registers a route to match any URL path that begins with /hello/ followed by a string.

The second line, config.add_view(hello_world, route_name=’hello’), registers the hello_world function as a view callable and makes sure that it will be called when the hello route is matched.

4.1.6 WSGI Application Creation

1 app = config.make_wsgi_app()

34

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]