ВУЗ: Не указан

Категория: Не указан

Дисциплина: Не указана

Добавлен: 02.01.2026

Просмотров: 2756

Скачиваний: 0

ВНИМАНИЕ! Если данный файл нарушает Ваши авторские права, то обязательно сообщите нам.

5.8. THE MYPROJECT PROJECT

whirlwind tour of what exists in this file in this section.

Your application’s name can be any string; it is specified in the name field. The version number is specified in the version value. A short description is provided in the description field. The long_description is conventionally the content of the README and CHANGES file appended together. The classifiers field is a list of Trove classifiers describing your application. author and author_email are text fields which probably don’t need any description. url is a field that should point at your application project’s URL (if any). packages=find_packages() causes all packages within the project to be found when packaging the application. include_package_data will include non-Python files when the application is packaged if those files are checked into version control. zip_safe indicates that this package is not safe to use as a zipped egg; instead it will always unpack as a directory, which is more convenient. install_requires and tests_require indicate that this package depends on the pyramid package. test_suite points at the package for our application, which means all tests found in the package will be run when setup.py test is invoked. We examined entry_points in our discussion of the development.ini file; this file defines the main entry point that represents our project’s application.

Usually you only need to think about the contents of the setup.py file when distributing your application to other people, when adding Python package dependencies, or when versioning your application for your own use. For fun, you can try this command now:

$ python setup.py sdist

This will create a tarball of your application in a dist subdirectory named MyProject-0.1.tar.gz. You can send this tarball to other people who want to install and use your application.

5.8.5 setup.cfg

The setup.cfg file is a setuptools configuration file. It contains various settings related to testing and internationalization:

Our generated setup.cfg looks like this:

1

[nosetests]

2

match = ^test

3

nocapture = 1

4

cover-package = myproject

5

with-coverage = 1

6

cover-erase = 1

7

 

8

[compile_catalog]

53


5. CREATING A PYRAMID PROJECT

9 directory = myproject/locale

10domain = MyProject

11statistics = true

12

13[extract_messages]

14add_comments = TRANSLATORS:

15output_file = myproject/locale/MyProject.pot

16width = 80

17

18[init_catalog]

19domain = MyProject

20input_file = myproject/locale/MyProject.pot

21output_dir = myproject/locale

22

23[update_catalog]

24domain = MyProject

25input_file = myproject/locale/MyProject.pot

26output_dir = myproject/locale

27previous = true

The values in the default setup file allow various commonly-used internationalization commands and testing commands to work more smoothly.

5.9 The myproject Package

The myproject package lives inside the MyProject project. It contains:

1.An __init__.py file signifies that this is a Python package. It also contains code that helps users run the application, including a main function which is used as a entry point for commands such as pserve, pshell, pviews, and others.

2.A templates directory, which contains Chameleon (or other types of) templates.

3.A tests.py module, which contains unit test code for the application.

4.A views.py module, which contains view code for the application.

These are purely conventions established by the scaffold: Pyramid doesn’t insist that you name things in any particular way. However, it’s generally a good idea to follow Pyramid standards for naming, so that other Pyramid developers can get up to speed quickly on your code when you need help.

54

5.9. THE MYPROJECT PACKAGE

5.9.1 __init__.py

We need a small Python module that configures our application and which advertises an entry point for use by our PasteDeploy .ini file. This is the file named __init__.py. The presence of an __init__.py also informs Python that the directory which contains it is a package.

1 from pyramid.config import Configurator

2

3 def main(global_config, **settings):

4""" This function returns a Pyramid WSGI application.

5"""

6config = Configurator(settings=settings)

7 config.add_static_view(’static’, ’static’, cache_max_age=3600) 8 config.add_route(’home’, ’/’)

9config.scan()

10return config.make_wsgi_app()

1.Line 1 imports the Configurator class from pyramid.config that we use later.

2.Lines 3-10 define a function named main that returns a Pyramid WSGI application. This function is meant to be called by the PasteDeploy framework as a result of running pserve.

Within this function, application configuration is performed. Line 6 creates an instance of a Configurator.

Line 7 registers a static view, which will serve up the files from the myproject:static asset specification (the static directory of the myproject package).

Line 8 adds a route to the configuration. This route is later used by a view in the views module.

Line 9 calls config.scan(), which picks up view registrations declared elsewhere in the package (in this case, in the views.py module).

Line 10 returns a WSGI application to the caller of the function (Pyramid’s pserve).

5.9.2 views.py

Much of the heavy lifting in a Pyramid application is done by view callables. A view callable is the main tool of a Pyramid web application developer; it is a bit of code which accepts a request and which returns a response.

55


5. CREATING A PYRAMID PROJECT

1

2

3

4

5

from pyramid.view import view_config

@view_config(route_name=’home’, renderer=’templates/mytemplate.pt’) def my_view(request):

return {’project’:’MyProject’}

Lines 3-5 define and register a view callable named my_view. The function named my_view is decorated with a view_config decorator (which is processed by the config.scan() line in our __init__.py). The view_config decorator asserts that this view be found when a route named home is matched. In our case, because our __init__.py maps the route named home to the URL pattern /, this route will match when a visitor visits the root URL. The view_config decorator also names a renderer, which in this case is a template that will be used to render the result of the view callable. This particular view declaration points at templates/mytemplate.pt, which is a asset specification that specifies the mytemplate.pt file within the templates directory of the myproject package. The asset specification could have also been specified as myproject:templates/mytemplate.pt; the leading package name and colon is optional. The template file it actually points to is a Chameleon ZPT template file.

This view callable function is handed a single piece of information: the request. The request is an instance of the WebOb Request class representing the browser’s request to our server.

This view returns a dictionary. When this view is invoked, a renderer converts the dictionary returned by the view into HTML, and returns the result as the response. This view is configured to invoke a renderer which uses a Chameleon ZPT template (templates/my_template.pt).

See Writing View Callables Which Use a Renderer for more information about how views, renderers, and templates relate and cooperate.

latex-note.png

Because our development.ini has a pyramid.reload_templates = true directive indicating that templates should be reloaded when they change, you won’t need to restart the application server to see changes you make to templates. During development, this is handy. If this directive had been false (or if the directive did not exist), you would need to restart the application server for each template change. For production applications, you should set your project’s pyramid.reload_templates to false to increase the speed at which templates may be rendered.

56

5.9. THE MYPROJECT PACKAGE

5.9.3 static

This directory contains static assets which support the mytemplate.pt template. It includes CSS and images.

5.9.4 templates/mytemplate.pt

The single Chameleon template that exists in the project. Its contents are too long to show here, but it displays a default page when rendered. It is referenced by the call to @view_config as the renderer of the my_view view callable in the views.py file. See Writing View Callables Which Use a Renderer for more information about renderers.

Templates are accessed and used by view configurations and sometimes by view functions themselves. See Using Templates Directly and Templates Used as Renderers via Configuration.

5.9.5 tests.py

The tests.py module includes unit tests for your application.

1 import unittest

2

3 from pyramid import testing

4

5 class ViewTests(unittest.TestCase):

6def setUp(self):

7self.config = testing.setUp()

8

9def tearDown(self):

10

testing.tearDown()

11

 

12def test_my_view(self):

13from .views import my_view

14request = testing.DummyRequest()

15info = my_view(request)

16self.assertEqual(info[’project’], ’MyProject’)

This sample tests.py file has a single unit test defined within it. This test is executed when you run python setup.py test. You may add more tests here as you build your application. You are not required to write tests to use Pyramid, this file is simply provided as convenience and example.

See Unit, Integration, and Functional Testing for more information about writing Pyramid unit tests.

57



5. CREATING A PYRAMID PROJECT

5.10 Modifying Package Structure

It is best practice for your application’s code layout to not stray too much from accepted Pyramid scaffold defaults. If you refrain from changing things very much, other Pyramid coders will be able to more quickly understand your application. However, the code layout choices made for you by a scaffold are in no way magical or required. Despite the choices made for you by any scaffold, you can decide to lay your code out any way you see fit.

For example, the configuration method named add_view() requires you to pass a dotted Python name or a direct object reference as the class or function to be used as a view. By default, the starter scaffold would have you add view functions to the views.py module in your package. However, you might be more comfortable creating a views directory, and adding a single file for each view.

If your project package name was myproject and you wanted to arrange all your views in a Python subpackage within the myproject package named views instead of within a single views.py file, you might:

Create a views directory inside your myproject package directory (the same directory which holds views.py).

Move the existing views.py file to a file inside the new views directory named, say, blog.py.

Create a file within the new views directory named __init__.py (it can be empty, this just tells Python that the views directory is a package.

You can then continue to add view callable functions to the blog.py module, but you can also add other .py files which contain view callable functions to the views directory. As long as you use the @view_config directive to register views in conjuction with config.scan() they will be picked up automatically when the application is restarted.

5.11 Using the Interactive Shell

It is possible to use the pshell command to load a Python interpreter prompt with a similar configuration as would be loaded if you were running your Pyramid application via pserve. This can be a useful debugging tool. See The Interactive Shell for more details.

58

5.12. WHAT IS THIS PSERVE THING

5.12 What Is This pserve Thing

The code generated by an Pyramid scaffold assumes that you will be using the pserve command to start your application while you do development. pserve is a command that reads a PasteDeploy .ini file (e.g. development.ini) and configures a server to serve a Pyramid application based on the data in the file.

pserve is by no means the only way to start up and serve a Pyramid application. As we saw in Creating Your First Pyramid Application, pserve needn’t be invoked at all to run a Pyramid application. The use of pserve to run a Pyramid application is purely conventional based on the output of its scaffolding. But we strongly recommend using while developing your application, because many other convenience introspection commands (such as pviews, prequest, proutes and others) are also implemented in terms of configuration availaibility of this .ini file format. It also configures Pyramid logging and provides the --reload switch for convenient restarting of the server when code changes.

5.13 Using an Alternate WSGI Server

Pyramid scaffolds generate projects which use the Waitress WSGI server. Waitress is a server that is suited for development and light production usage. It’s not the fastest nor the most featureful WSGI server. Instead, its main feature is that it works on all platforms that Pyramid needs to run on, making it a good choice as a default server from the perspective of Pyramid’s developers.

Any WSGI server is capable of running a Pyramid application. But we suggest you stick with the default server for development, and that you wait to investigate other server options until you’re ready to deploy your application to production. Unless for some reason you need to develop on a non-local system, investigating alternate server options is usually a distraction until you’re ready to deploy. But we recommend developing using the default configuration on a local system that you have complete control over; it will provide the best development experience.

One popular production alternative to the default Waitress server is mod_wsgi. You can use mod_wsgi to serve your Pyramid application using the Apache web server rather than any “pure-Python” server like Waitress. It is fast and featureful. See Running a Pyramid Application under mod_wsgi for details.

Another good production alternative is Green Unicorn (aka gunicorn). It’s faster than Waitress and slightly easier to configure than mod_wsgi, although it depends, in its default configuration, on having a buffering HTTP proxy in front of it. It does not, as of this writing, work on Windows.

59