Версия 13 от 2010-06-11 13:02:31

Убрать это сообщение

Учебник - часть 1

Вступление

В главе Первые шаги, был описан процесс установки BlueBream и создания проекта из шбалона bluebream. В этом учебнике, вы научитесь создавать простое приложение ticket collector. Данная серия уроков поможет ближе ознакомится с принципами BlueBream.

Вот несколько функций будущего приложения:

Это первая часть обучения. После завершения этой главы, вы должны уметь:

Примеры, которые предлагаются для изучения в документации можно загрузить отсюда. Исходники доступны на разных этапах, соответственно разделам.

  • Этап 1 : разделы от 5.2 до 5.7
  • Этап 2 : раздел 5.8
  • Этап 3 : раздел 5.9
  • Этап 4 : раздел 6.2
  • Этап 5 : раздел 6.3
  • Этап 6 : разделы 6.4 & 6.5

Создание нового проекта

Использование шаблона проекта bluebream

В этом разделе мы будем создавать структуру папок для нашего приложения. Я предполагаю, что вы уже установили bluebream, используя команду easy_install bluebream, как упоминалось в главе Первые шаги. Давайте назовем приложение ticketcollector, и создадим Python пакет с именем tc.main. Итак, мы создали проект с именем ticketcollector, пакетом пространства имен tc и под-пакетом main. Давайте создадим структуру папок для нашего приложения:

   1 $ paster create -t bluebream
   2 
   3 Selected and implied templates:
   4   bluebream#bluebream  A BlueBream project, base template
   5 
   6 Enter project name: ticketcollector
   7 Variables:
   8   egg:      ticketcollector
   9   package:  ticketcollector
  10   project:  ticketcollector
  11 Enter python_package (Main Python package (with namespace, if any)) ['ticketcollector']: tc.main
  12 Enter interpreter (Name of custom Python interpreter) ['breampy']:
  13 Enter version (Version (like 0.1)) ['0.1']:
  14 Enter description (One-line description of the package) ['']: Ticket Collector
  15 Enter long_description (Multi-line description (in reST)) ['']: An issue tracking application
  16 Enter keywords (Space-separated keywords/tags) ['']:
  17 Enter author (Author name) ['']: Baiju M
  18 Enter author_email (Author email) ['']: baiju@example.com
  19 Enter url (URL of homepage) ['']:
  20 Enter license_name (License name) ['']: ZPL
  21 Enter zip_safe (True/False: if the package can be distributed as a .zip file) [False]:
  22 Creating template bluebream
  23 Creating directory ./ticketcollector
  24 
  25 Your project has been created! Now, you want to:
  26 1) put the generated files under version control
  27 2) run: python boostrap.py
  28 3) run: ./bin/buildout

Как видно из примера выше, мы предоставили почти всю информацию о проекте. Значения, которые были указаны, можно поменять позже. Это сделать очень просто; все, что трудно изменить позже - это имена пакетов, потому что на них позже может быть много ссылок в коде.

Организация нового пакета

Если вы перейдете в папку ticketcollector, вы увидите несколько папок и файлов:

jack@computer:/projects/ticketcollector$ ls -CF
bootstrap.py  debug.ini   etc/      src/  versions.cfg
buildout.cfg  deploy.ini  setup.py  var/

Когда структура проекта готова, вы можете добавить его в систему контроля версий. Вам не следует добавлять папку src/ticketcollector.egg-info, так как она автоматически создается с помощью setuptools. Вот пример с использованием bzr:

jack@computer:/projects/ticketcollector$ rm -fr src/ticketcollector.egg-info/
jack@computer:/projects/ticketcollector$ bzr init
Created a standalone tree (format: 2a)
jack@computer:/projects/ticketcollector$ bzr add *
adding bootstrap.py
adding buildout.cfg
adding debug.ini
...
jack@computer:/projects/ticketcollector$ bzr ci -m "Initial import"
Committing to: /projects/ticketcollector/
added bootstrap.py
added buildout.cfg
...
Committed revision 1.

Добавление проекта в систему контроля версий необязательный, но рекомендуемый шаг. У вас теперь есть правильный исходный код, который, после построения, приобретет вид рабочего приложения. Проект теперь полностью независим, от дистрибутива bluebream, который только помогает добраться до этой точки развития. Теперь проект содержит все необходимое для установки зависимостей из Интернета и настройки приложения.

Генерация (bootstrapping) проекта

Следующий шаг - установка Buildout. Цель Buildout - автоматизировать сборку Python приложений из исходников. Единственное требование для Buildout - это Python. BlueBream предоставляет скрипт генерации для установки !Buildout и настройки проекта для его запуска. Этот скрипт называется bootstrap.py и делает следующие вещи:

Когда вы запускаете bootstrap.py, вы видите, что он создает несколько папок и скрипт bin/buildout, как было упомянуто раньше:

jack@computer:/projects/ticketcollector$ python bootstrap.py
Creating directory '/projects/ticketcollector/bin'.
Creating directory '/projects/ticketcollector/parts'.
Creating directory '/projects/ticketcollector/develop-eggs'.
Creating directory '/projects/ticketcollector/eggs'.
Generated script '/projects/ticketcollector/bin/buildout'.

Настройка Buildout

После генерации проекта вы можете собрать приложение. Все шаги, которые на этот момент уже сделаны, делаются всего один раз для нового проекта, но запуск сборщика необходим при каждом изменение его конфигурации. Теперь вы готовы запустить bin/buildout для того, чтобы собрать приложение, но перед этим следует взглянуть на содержимое файла buildout.cfg:

   1 [buildout]
   2 develop = .
   3 extends = versions.cfg
   4 parts = app
   5         test
   6 
   7 [app]
   8 recipe = zc.recipe.egg
   9 eggs = ticketcollector
  10        z3c.evalexception>=2.0
  11        Paste
  12        PasteScript
  13        PasteDeploy
  14 interpreter = breampy
  15 [test]
  16 recipe = zc.recipe.testrunner
  17 eggs = ticketcollector

Конфигурация сборщика разделена на несколько секций, называемых частями. Главная часть - [buildout], является первой частью в листинге выше. Каждая часть, кроме [buildout], обрабатывается подключаемым механизмом системы Buildout, который называется рецепт. [buildout] обрабатывается как исключительный случай, так как содержит общие настройки.

Давайте рассмотрим [buildout]:

   1 [buildout]
   2 develop = .
   3 extends = versions.cfg
   4 parts = app
   5         test

Первая опция (develop) указывает сборщику, что текущая папка - папка с исходниками дистрибутива, то есть содержит файл setup.py. Buildout will inspect the setup.py and create a develop egg link inside the develop-eggs directory. The link file should contain the path to the location where the Python package is residing. So buildout will make sure that the packages are always importable. The value of the develop option could be a relative path, as given above, or absolute path to some directory. You can also add multiple lines to the develop option with different paths.

The extends option tells buildout to include the full content of the versions.cfg file as part the configuration. The versions.cfg is another Buildout configuration file of the same format as buildout.cfg and contains the release numbers of different dependencies. You can add multiple lines to the extends option to include multiple configuration files.

The parts option lists all the parts to be built by Buildout. Buildout expects a recipe for each of the parts listed here.

Now let’s look at the app part:

[app] recipe = zc.recipe.egg eggs = ticketcollector

interpreter = breampy This part takes care of all the eggs required for the application to function. The zc.recipe.egg is an advanced Buildout recipe with many features for dealing with eggs. Most of the dependencies will come as part of the main application egg. The option eggs lists all the eggs. The first egg, ticketcollector is the main locally developed egg. The last option, interpreter specifies the name of the custom interpreter created by this part. The custom interpreter contains the paths to all eggs listed here and their dependencies, so that you can import any module which is listed as a dependency.

The last part creates the test runner:

[test] recipe = zc.recipe.testrunner eggs = ticketcollector The testrunner recipe creates a test runner using the zope.testing module. The only mandatory option is eggs where you can specify the eggs.

Перевод: Ростислав Дзинько

Данная страница находится в процессе перевода ...