ВУЗ: Не указан
Категория: Не указан
Дисциплина: Не указана
Добавлен: 02.01.2026
Просмотров: 2749
Скачиваний: 0
20. COMMAND-LINE PYRAMID
[console_scripts]
show_settings = myproject.scripts:settings_show
The show_settings name will be the name of the script that is installed into bin. The colon (:) between myproject.scripts and settings_show above indicates that myproject.scripts is a Python module, and settings_show is the function in that module which contains the code you’d like to run as the result of someone invoking the show_settings script from their command line.
The result will be something like:
1 |
import os |
2 |
|
3 |
from setuptools import setup, find_packages |
4 |
|
5 |
here = os.path.abspath(os.path.dirname(__file__)) |
6 |
README = open(os.path.join(here, ’README.txt’)).read() |
7 |
CHANGES = open(os.path.join(here, ’CHANGES.txt’)).read() |
8 |
|
9 |
requires = [’pyramid’, ’pyramid_debugtoolbar’] |
10
11setup(name=’MyProject’,
12version=’0.0’,
13description=’My project’,
14long_description=README + ’\n\n’ + CHANGES,
15classifiers=[
16"Programming Language :: Python",
17"Framework :: Pylons",
18"Topic :: Internet :: WWW/HTTP",
19"Topic :: Internet :: WWW/HTTP :: WSGI :: Application",
20],
21author=’’,
22author_email=’’,
23url=’’,
24keywords=’web pyramid pylons’,
25packages=find_packages(),
26include_package_data=True,
27zip_safe=False,
28install_requires=requires,
29tests_require=requires,
30test_suite="myproject",
31entry_points = """\
32[paste.app_factory]
33main = myproject:main
34[console_scripts]
35show_settings = myproject.scripts:settings_show
226
20.7. MAKING YOUR SCRIPT INTO A CONSOLE SCRIPT
36
37
""",
)
Once you’ve done this, invoking $somevirtualenv/bin/python setup.py develop will install a file named show_settings into the $somevirtualenv/bin directory with a small bit of Python code that points to your entry point. It will be executable. Running it without any arguments will print an error and exit. Running it with a single argument that is the path of a config file will print the settings. Running it with an --omit=foo argument will omit the settings that have keys that start with foo. Running it with two “omit” options (e.g. --omit=foo --omit=bar) will omit all settings that have keys that start with either foo or bar:
[chrism@thinko somevenv]$ bin/show_settings development.ini \
|
--omit=pyramid \ |
|
--omit=debugtoolbar |
debug_routematch |
False |
debug_templates |
True |
reload_templates |
True |
mako.directories |
[] |
debug_notfound |
False |
default_locale_name |
en |
reload_resources |
False |
debug_authorization |
False |
reload_assets |
False |
prevent_http_cache |
False |
Pyramid’s pserve, pcreate, pshell, prequest, ptweens and other p* scripts are implemented as console scripts. When you invoke one of those, you are using a console script.
227
20. COMMAND-LINE PYRAMID
228
CHAPTER
TWENTYONE
INTERNATIONALIZATION AND LOCALIZATION
Internationalization (i18n) is the act of creating software with a user interface that can potentially be displayed in more than one language or cultural context. Localization (l10n) is the process of displaying the user interface of an internationalized application in a particular language or cultural context.
Pyramid offers internationalization and localization subsystems that can be used to translate the text of buttons, error messages and other softwareand template-defined values into the native language of a user of your application.
21.1 Creating a Translation String
While you write your software, you can insert specialized markup into your Python code that makes it possible for the system to translate text values into the languages used by your application’s users. This markup creates a translation string. A translation string is an object that behaves mostly like a normal Unicode object, except that it also carries around extra information related to its job as part of the Pyramid translation machinery.
21.1.1 Using The TranslationString Class
The most primitive way to create a translation string is to use the pyramid.i18n.TranslationString callable:
229
21. INTERNATIONALIZATION AND LOCALIZATION
1
2
from pyramid.i18n import TranslationString ts = TranslationString(’Add’)
This creates a Unicode-like object that is a TranslationString.
latex-note.png
For people more familiar with Zope i18n, a TranslationString is a lot like a zope.i18nmessageid.Message object. It is not a subclass, however. For people more familiar with Pylons or Django i18n, using a TranslationString is a lot like using “lazy” versions of related gettext APIs.
The first argument to TranslationString is the msgid; it is required. It represents the key into the translation mappings provided by a particular localization. The msgid argument must be a Unicode object or an ASCII string. The msgid may optionally contain replacement markers. For instance:
1
2
from pyramid.i18n import TranslationString ts = TranslationString(’Add ${number}’)
Within the string above, ${number} is a replacement marker. It will be replaced by whatever is in the mapping for a translation string. The mapping may be supplied at the same time as the replacement marker itself:
1 from pyramid.i18n import TranslationString
2 ts = TranslationString(’Add ${number}’, mapping={’number’:1})
Any number of replacement markers can be present in the msgid value, any number of times. Only markers which can be replaced by the values in the mapping will be replaced at translation time. The others will not be interpolated and will be output literally.
A translation string should also usually carry a domain. The domain represents a translation category to disambiguate it from other translations of the same msgid, in case they conflict.
1
2
3
from pyramid.i18n import TranslationString
ts = TranslationString(’Add ${number}’, mapping={’number’:1}, domain=’form’)
230
21.1. CREATING A TRANSLATION STRING
The above translation string named a domain of form. A translator function will often use the domain to locate the right translator file on the filesystem which contains translations for a given domain. In this case, if it were trying to translate our msgid to German, it might try to find a translation from a gettext file within a translation directory like this one:
locale/de/LC_MESSAGES/form.mo
In other words, it would want to take translations from the form.mo translation file in the German language.
Finally, the TranslationString constructor accepts a default argument. If a default argument is supplied, it replaces usages of the msgid as the default value for the translation string. When default is None, the msgid value passed to a TranslationString is used as an implicit message identifier. Message identifiers are matched with translations in translation files, so it is often useful to create translation strings with “opaque” message identifiers unrelated to their default text:
1
2
3
from pyramid.i18n import TranslationString
ts = TranslationString(’add-number’, default=’Add ${number}’, domain=’form’, mapping={’number’:1})
When default text is used, Default text objects may contain replacement values.
21.1.2 Using the TranslationStringFactory Class
Another way to generate a translation string is to use the TranslationStringFactory object. This object is a translation string factory. Basically a translation string factory presets the domain value of any translation string generated by using it. For example:
1
2
3
from pyramid.i18n import TranslationStringFactory _ = TranslationStringFactory(’pyramid’)
ts = _(’add-number’, default=’Add ${number}’, mapping={’number’:1})
latex-note.png
We assigned the translation string factory to the name _. This is a convention which will be supported by translation file generation tools.
231
21. INTERNATIONALIZATION AND LOCALIZATION
After assigning _ to the result of a TranslationStringFactory(), the subsequent result of calling _ will be a TranslationString instance. Even though a domain value was not passed to _ (as would have been necessary if the TranslationString constructor were used instead of a translation string factory), the domain attribute of the resulting translation string will be pyramid. As a result, the previous code example is completely equivalent (except for spelling) to:
1
2
3
from pyramid.i18n import TranslationString as _
ts = _(’add-number’, default=’Add ${number}’, mapping={’number’:1}, domain=’pyramid’)
You can set up your own translation string factory much like the one provided above by using the TranslationStringFactory class. For example, if you’d like to create a translation string factory which presets the domain value of generated translation strings to form, you’d do something like this:
1
2
3
from pyramid.i18n import TranslationStringFactory _ = TranslationStringFactory(’form’)
ts = _(’add-number’, default=’Add ${number}’, mapping={’number’:1})
Creating a unique domain for your application via a translation string factory is best practice. Using your own unique translation domain allows another person to reuse your application without needing to merge your translation files with his own. Instead, he can just include your package’s translation directory via the pyramid.config.Configurator.add_translation_dirs() method.
latex-note.png
For people familiar with Zope internationalization, a TranslationStringFactory is a lot like a zope.i18nmessageid.MessageFactory object. It is not a subclass, however.
21.2 Working With gettext Translation Files
The basis of Pyramid translation services is GNU gettext. Once your application source code files and templates are marked up with translation markers, you can work on translations by creating various kinds of gettext files.
232
21.2. WORKING WITH GETTEXT TRANSLATION FILES
latex-note.png
The steps a developer must take to work with gettext message catalog files within a Pyramid application are very similar to the steps a Pylons developer must take to do the same. See the Pylons internationalization documentation for more information.
GNU gettext uses three types of files in the translation framework, .pot files, .po files and .mo files.
.pot (Portable Object Template) files
A .pot file is created by a program which searches through your project’s source code and which picks out every message identifier passed to one of the _() functions (eg. translation string constructions). The list of all message identifiers is placed into a .pot file, which serves as a template for creating .po files.
.po (Portable Object) files
The list of messages in a .pot file are translated by a human to a particular language; the result is saved as a .po file.
.mo (Machine Object) files
A .po file is turned into a machine-readable binary file, which is the .mo file. Compiling the translations to machine code makes the localized program run faster.
The tools for working with gettext translation files related to a Pyramid application is Babel and Lingua. Lingua is a Babel extension that provides support for scraping i18n references out of Python and Chameleon files.
21.2.1 Installing Babel and Lingua
In order for the commands related to working with gettext translation files to work properly, you will need to have Babel and Lingua installed into the same environment in which Pyramid is installed.
Installation on UNIX
If the virtualenv into which you’ve installed your Pyramid application lives in /my/virtualenv, you can install Babel and Lingua like so:
233