nagare package

Subpackages

Submodules

nagare.ajax module

Asynchronous update objects and Python to javascript transcoder

class nagare.ajax.JS(o)

Bases: object

Transcode a Python function or module to javascript code

generate_action(priority, renderer)

Include the transcoded javascript into <head>

In:
  • prioritynot used
  • renderer – the current renderer
Return:
  • javascript fragment of the call to the transcoded function
class nagare.ajax.Update(**kw)

Bases: object

Asynchronous updater object

Send a XHR request that can do an action, render a component and finally update the HTML with the rendered view

generate_action(priority, renderer)

Generate the javascript action

In:
  • priority – type of the action (see callbacks.py)
  • renderer – the current renderer
Return:
  • the javascript code
classmethod no_action(*args, **kw)
class nagare.ajax.Updates(**kw)

Bases: nagare.ajax.Update

A list of Update objects

action(request, response, *args, **kw)

Execute all the actions of the Update objects

class nagare.ajax.ViewToJs(js, id, renderer, output)

Bases: object

class nagare.ajax.ViewsToJs

Bases: list

A list of ViewToJS objects

nagare.ajax.javascript

alias of JS

nagare.ajax.javascript_dependencies(renderer)
class nagare.ajax.js

Bases: str

A javascript code object

nagare.ajax.py2js(value, h=None)

No default transcodage

nagare.ajax.render(self, h)

Generic method to transcode a javascript code

In:
  • value – a javascript code
  • h – the current renderer
Return:
  • transcoded javascript
nagare.ajax.serialize(self, content_type, doctype, declaration)

Wrap a view into a javascript code

In:
  • content_type – the rendered content type
  • doctype – the (optional) doctype
  • declaration – is the XML declaration to be outputed?
Return:
  • a tuple (‘text/plain’, Javascript to evaluate on the client)
nagare.ajax.serialize_body(view_to_js, content_type, doctype)

Wrap a view body into a javascript code

In:
  • view_to_js – the view
  • content_type – the rendered content type
  • doctype – the (optional) doctype
  • declaration – is the XML declaration to be outputed?
Return:
  • Javascript to evaluate on the client
nagare.ajax.serialize_views(self, content_type, doctype, declaration)

Wrap a view into a javascript code

In:
  • content_type – the rendered content type
  • doctype – the (optional) doctype
  • declaration – is the XML declaration to be outputed?
Return:
  • a tuple (‘text/plain’, Javascript to evaluate on the client)
nagare.ajax.str2js(src, namespace)

Translate a string with Python code to javascript

In:
  • src – the Python code
  • namespace – the namespace of this code
Return:
  • the javascript code

nagare.callbacks module

Callbacks manager

Manage the dictionary of the ids / callbacks associations

exception nagare.callbacks.CallbackLookupError

Bases: exceptions.LookupError

nagare.callbacks.clean(old, new)

Keep the old callbacks registered by a view only if this view has not registered new callbacks

In:
  • old – the old registered callbacks
  • new – the new registered callbacks
nagare.callbacks.process(callbacks, request, response)

Call the actions associated to the callback identifiers received

In:
  • callbacks – dictionary where the keys are the callback ids and the values are tuples (callback, with_request, render)
  • request – the web request object
  • response – the web response object
Return:
  • the render function
nagare.callbacks.register(model, priority, callback, with_request, render, callbacks)

Register a callback

In:
  • model – name of the view which registers this callback (None for the default view)
  • priority – type of the callback
    • 0 : <form>.pre_action
    • 1 : action with value (<textarea>, checkbox …)
    • 2 : action without value (radio button)
    • 3 : <form>.post_action
    • 4 : action with continuation and without value (<a>, submit button …)
    • 5 : action with continuation and with value (special case for >input type=’image’>)
  • callback – the action function or method
  • with_request – will the request and response objects be passed to the action?
  • render – the render function or method
Out:
  • callbacks – dictionary where the keys are the callback ids and the values are tuples (callback, with_request, render)
Return:
  • the callback identifier

nagare.comet module

Comet-style channels i.e HTTP push channels

This implementation is only working with a multi-threaded publisher

class nagare.comet.Channel(id, js, history_size=0, poll_time=1000)

Bases: object

A comet-style channel i.e XHR long polling channel

close()

Close a channel

connect(nb, fileno, response)

A browser wants to be connected to this channel

In:
  • nb – identifier of the next wanted message
  • fileno – the I/O file handle
  • responsewebob response object
discard_disconnected_clients()

Forgot about the disconnected clients

get_old_msg(nb)

Check if a message in the history is ready to be sent

In:
  • nb – identifier of the next message wanted by the client
Return:
  • the tuple: - identifier of the next msg to ask for - the msg if available or None
send(msg)

Send a message to all the connected clients

In:
  • msg – message to send
class nagare.comet.Channels

Bases: dict

Channels manager

channel_factory

alias of Channel

connect(id, nb, fileno, response)

A browser wants to be connected to a channel

In:
  • id – the channel identifier
  • nb – identifier of the next message wanted
  • fileno – the I/O file handle
  • responsewebob response object
create(id, *args, **kw)

Create a new channel

In:
  • id – the channel identifier
discard_disconnected_clients()
has_clients(id)
send(id, msg)

Send a message to all the connected clients of a channel

In:
  • id – the channel identifier
  • msg – message to send
class nagare.comet.Client(fileno, response)

Bases: object

A connected client

block()
fileno()
is_blocked()
release()
send(msg=None, status=None)
class nagare.comet.TextChannel(id, js, history_size=0, poll_time=1000)

Bases: nagare.comet.Channel

get_old_msg(nb)

Check if a message in the history is ready to be sent

In:
  • nb – identifier of the next message wanted by the client
Return:
  • the tuple: - identifier of the next msg to ask for - the msg if available or None
class nagare.comet.TextChannels

Bases: nagare.comet.Channels

channel_factory

alias of TextChannel

nagare.comet.render(self, h, *args)

nagare.component module

This module implements the component model of the framework.

This model is inspired by the Seaside one. With the possibility to embed, replace and call a component. It’s described in ComponentModel

exception nagare.component.AnswerWithoutCall

Bases: exceptions.BaseException

class nagare.component.Component(o=None, model=0, url=None)

Bases: object

This class transforms any Python object into a component

A component has views, can the embedded, replaced, called and can answsered a value.

answer(r=None)

Answer to a call

In:
  • the value to answer
becomes(o=<object object>, model=0, url=None)

Replace a component by an object or an other component

In:
  • o – object to be replaced by
  • model – the name of the view to use (None for the default view)
  • url – the url fragment to add before all the links generated by views of this component
Return:
  • self
call(o=<object object>, model=0, url=None)

Call an other object or component

The current component is replaced and will be back when the object will do an answer()

In:
  • o – the object to call
  • model – the name of the view to use (None for the default view)
  • url – the url fragment to add before all the links generated by views of this component
Return:
  • the answer of the called object
init(url, http_method, request)

Initialisation from an url

Forward the call to the generic method of the presentation service

on_answer(f, *args, **kw)

Register a function to listen to my answer

In:
  • f – function to call with my answer
  • args, kwf parameters
register_callback(model, priority, callback, with_request, render)

Register a callback for this component

In:
  • model – name of the view which registers this callback (None for the default view)
  • priority – type and priority of the callback
  • callback – the action function or method
  • with_request – will the request and response objects be passed to the action?
  • render – the render function or method
render(renderer, model=0)

Rendering method of a component

Forward the call to the generic method of the presentation service

serialize_callbacks(clean_callbacks)

Return the callbacks to serialize

In:
  • clean_callbacks – do we have to forget all the old callbacks?
Return:
  • the callbacks of this component
class nagare.component.Task

Bases: object

A Task encapsulated a simple method. A task is typically used to manage other components by calling them.

Warning

A Task is an object, not a component: you must wrap it into a Component() to use it.

go(comp)
nagare.component.init_for(self, url, comp, http_method, request)

Initialisation from an url

In:
  • url – rest of the url to process
  • comp – the component
  • http_method – the HTTP method
  • request – the complete Request object
Return:
  • presentation.NOT_FOUND if the url is invalid, else None
nagare.component.render(self, renderer, comp, model)

Rendering of a Component

In:
  • renderer – the renderer
  • comp – the component
  • model – the name of the view
Return:
  • the view of the component object
nagare.component.render_function(f, renderer, comp, *args)
nagare.component.render_task(self, renderer, comp, *args)

nagare.config module

Helper to validate a configuration

nagare.config.validate(filename, config, error)

Validate a ConfigObj object

In:
  • filename – the path to the configuration file
  • config – the ConfigObj object, created from the configuration file
  • error – the function to call in case of configuration errors
Return:
  • is the configuration valid ?

nagare.continuation module

A Continuation() object captures an execution context

Calling switch() on a continuation permutes the current execution context and the captured one, thus resuming where the context was captured.

class nagare.continuation.Channel

Bases: _stackless.channel

switch(value=None)

Permute this execution context with the current one

In:
  • value - value returned to the captured execution context
nagare.continuation.Continuation(f, *args, **kw)

Create a new execution context where f is launched.

This new execution context became the current one.

In:
  • f – function to call
  • args, kwf arguments
nagare.continuation.call_wrapper(action, *args, **kw)

A wrapper that creates a continuation and calls a function.

It’s necessary to wrapper a callable that do directly or indirectly a comp.call(o) into such a call_wrapper.

Note

The actions your registered on the <a> tags or on the submit buttons are already wrapped for you.

In:
  • action – a callable. It will be called, wrapped into a new continuation, with the args and kw parameters.
  • args – positional parameters of the callable
  • kw – keywords parameters of the callable
nagare.continuation.get_current()

Return the current execution context

nagare.database module

class nagare.database.DummySession

Bases: object

begin()
clear(**kw)
close(**kw)
configure(**kw)
query(**kw)
remove(**kw)
nagare.database.add_pickle_hooks(mapper, cls)
nagare.database.entity_getstate(entity)

Return the state of an SQLAlchemy entity

In:
  • entity – the SQLAlchemy entity
Return:
  • the state dictionary
nagare.database.entity_setstate(entity, d)

Set the state of an SQLAlchemy entity

In:
  • entity – the newly created and not yet initialized SQLAlchemy entity
  • d – the state dictionary (created by entity_getstate())
nagare.database.set_metadata(metadata, database_uri, database_debug, engine_settings)

Activate the metadatas (bind them to a database engine)

In:
  • metadata – the metadatas
  • database_uri – connection string for the database engine
  • database_debug – debug mode for the database engine
  • engine_settings – dedicated parameters for the used database engine
nagare.database.setup_all()

nagare.editor module

Helpers to validate form datum

class nagare.editor.Editor(target, properties_to_create=())

Bases: object

An editor object act as a buffer between the datum received from a form an the target object.

An editor object has a set of editor properties, each with a possible validating function, and will modified the target object only if all the validating functions are passed ok.

commit(properties_to_commit=(), properties_to_validate=())

Write back the value of the property to the target object, only if they are all valid

In:
  • properties_to_commit – names of properties to check then to write to the target object
  • properties_to_validate – additional names of properties to check
Return:
  • are all the properties valid ?
is_validated(properties_to_validate)

Check the validity of a set of properties

In:
  • properties_to_validate – name of the properties to validate
Return
  • a boolean
class nagare.editor.Property(v=None)

Bases: nagare.var.Var

An editor property

An editor property has:

  • a current value: this value is always set
  • a valid value: this value is only set if the validating function has validated it
  • a validating function: a function that raise an exception if the value is invalid else, return the value to set
  • the message of the last validation error or None if the current value is valid
commit(o, name)

Set the attribute name of the object o with the valid value

In:
  • o – target object
  • name – name of the attribute to set in the target object
set(input)

Set the values

Always set the current value but only the valid value if the validating function return OK

In:
  • input – the input string or cgi.FieldStorage object
validate(f)

Set the validating function

In:
  • f – the validating function. Called with the value to validate. Raise the exception ValueError is the value is invalid. Return the value to be set (i.e a validation function can do conversions too)
Return:
  • self

nagare.i18n module

Internationalization service

class nagare.i18n.DummyTranslation

Bases: object

Identity translation

gettext(msg)
lazy_gettext(msg)
lazy_ngettext(singular, plural, n)
lazy_ugettext(msg)
lazy_ungettext(singular, plural, n)
ngettext(singular, plural, n)
ugettext(msg)
ungettext(singular, plural, n)
class nagare.i18n.LazyProxy(func, *args, **kwargs)

Bases: babel.support.LazyProxy

Picklable babel.support.LazyProxy objects

value

Always evaluate, without any cache

class nagare.i18n.Locale(language='en', territory=None, script=None, variant=None, dirname=None, domain=None, timezone=None, default_timezone=None)

Bases: babel.core.Locale

add_translation_directory(dirname, domain=None)

Associate a directory to a translation domain

In:
  • dirname – the directory
  • domain – the translation domain
format_currency(number, currency, format=None)

Return formatted currency value

>>> Locale('en', 'US').format_currency(1099.98, 'USD')
u'$1,099.98'
>>> Locale('es', 'CO').format_currency(1099.98, 'USD')
u'US$\xa01.099,98'
>>> Locale('de', 'DE').format_currency(1099.98, 'EUR')
u'1.099,98\xa0\u20ac'

The pattern can also be specified explicitly:

>>> Locale('en', 'US').format_currency(1099.98, 'EUR', u'¤¤ #,##0.00')
u'EUR 1,099.98'
format_date(d=None, format='medium')

Return a date formatted according to the given pattern

>>> d = datetime.date(2007, 04, 01)
>>> Locale('en', 'US').format_date(d)
u'Apr 1, 2007'
>>> Locale('de', 'DE').format_date(d, format='full')
u'Sonntag, 1. April 2007'

If you don’t want to use the locale default formats, you can specify a custom date pattern:

>>> Locale('en').format_date(d, "EEE, MMM d, ''yy")
u"Sun, Apr 1, '07"
In:
  • ddate or datetime object; if None, the current date is used
  • format – ‘full’, ‘long’, ‘medium’, or ‘short’, or a custom date/time pattern
Return:
  • the formatted date string
format_datetime(dt=None, format='medium')

Return a date formatted according to the given pattern

>>> dt = datetime.datetime(2007, 04, 01, 15, 30)
>>> Locale('en', 'US').format_datetime(dt)
u'Apr 1, 2007 3:30:00 PM'
>>> from pytz import timezone
>>> dt = datetime.datetime(2007, 04, 01, 15, 30)
>>> Locale('fr', 'FR', timezone=timezone('Europe/Paris'), default_timezone=pytz.UTC).format_datetime(dt, 'full')
u'dimanche 1 avril 2007 17:30:00 HEC'
>>> Locale('en', timezone=timezone('US/Eastern'), default_timezone=pytz.UTC).format_datetime(dt, "yyyy.MM.dd G 'at' HH:mm:ss zzz")
u'2007.04.01 AD at 11:30:00 EDT'
In:
  • dtdatetime object; if None, the current date and time is used
  • format – ‘full’, ‘long’, ‘medium’, or ‘short’, or a custom date/time pattern
Return:
  • The formatted datetime string
format_decimal(number, format=None)

Return the given decimal number formatted

>>> Locale('en', 'US').format_decimal(1.2345)
u'1.234'
>>> Locale('en', 'US').format_decimal(1.2346)
u'1.235'
>>> Locale('en', 'US').format_decimal(-1.2346)
u'-1.235'
>>> Locale('sv', 'SE').format_decimal(1.2345)
u'1,234'
>>> Locale('de').format_decimal(12345)
u'12.345'
format_number(number)

Return the given number formatted

>>> Locale('en', 'US').format_number(1099)
u'1,099'
format_percent(number, format=None)

Return formatted percent value

>>> Locale('en', 'US').format_percent(0.34)
u'34%'
>>> Locale('en', 'US').format_percent(25.1234)
u'2,512%'
>>> Locale('sv', 'SE').format_percent(25.1234)
u'2\xa0512\xa0%'

The format pattern can also be specified explicitly:

>>> Locale('en', 'US').format_percent(25.1234, u'#,##0\u2030')
u'25,123\u2030'
format_scientific(number, format=None)

Return value formatted in scientific notation

>>> Locale('en', 'US').format_scientific(10000)
u'1E4'

The format pattern can also be specified explicitly:

>>> Locale('en', 'US').format_scientific(1234567, u'##0E00')
u'1.23E06'
format_time(t=None, format='medium')

Return a time formatted according to the given pattern

>>> t = datetime.time(15, 30)
>>> Locale('en', 'US').format_time(t)
u'3:30:00 PM'
>>> Locale('de', 'DE').format_time(t, format='short')
u'15:30'

If you don’t want to use the locale default formats, you can specify a custom time pattern:

>>> Locale('en').format_time(t, "hh 'o''clock' a")
u"03 o'clock PM"
In:
  • ttime or datetime object; if None, the current time in UTC is used
  • format – ‘full’, ‘long’, ‘medium’, or ‘short’, or a custom date/time pattern
Returns:
  • the formatted time string
get_currency_name(currency, count=None)

Return the name used for the specified currency

>>> Locale('en', 'US').get_currency_name('USD')
u'US Dollar'
In:
  • currency – the currency code
  • count – If provided the currency name will be pluealized to that number
Return:
  • the currency name
get_currency_symbol(currency)

Return the symbol used for the specified currency

>>> Locale('en', 'US').get_currency_symbol('USD')
u'$'
In:
  • currency – the currency code
Return:
  • the currency symbol
get_date_format(format='medium')

Return the date formatting pattern for the specified format

>>> Locale('en', 'US').get_date_format()
<DateTimePattern u'MMM d, yyyy'>
>>> Locale('de', 'DE').get_date_format('full')
<DateTimePattern u'EEEE, d. MMMM yyyy'>
In:
  • format – ‘full’, ‘long’, ‘medium’ or ‘short’
Return:
  • the date formatting pattern
get_datetime_format(format='medium')

Return the datetime formatting pattern for the specified format

>>> Locale('en', 'US').get_datetime_format()
u'{1} {0}'
In:
  • format – ‘full’, ‘long’, ‘medium’ or ‘short’
Return:
  • the datetime formatting pattern
get_day_names(width='wide', context='format')

Return the day names for the specified format

>>> Locale('en', 'US').get_day_names('wide')[1]
u'Tuesday'
>>> Locale('es').get_day_names('abbreviated')[1]
u'mar'
>>> Locale('de', 'DE').get_day_names('narrow', context='stand-alone')[1]
u'D'
In:
  • width – ‘wide’, ‘abbreviated’ or ‘narrow’
  • context – either ‘format’ or ‘stand-alone’
Return:
  • the day names
get_decimal_symbol()

Return the symbol used to separate decimal fractions

>>> Locale('en', 'US').get_decimal_symbol()
u'.'
get_era_names(width='wide')

Return the era names used for the specified format

>>> Locale('en', 'US').get_era_names('wide')[1]
u'Anno Domini'
>>> Locale('de', 'DE').get_era_names('abbreviated')[1]
u'n. Chr.'
In:
  • width – ‘wide’, ‘abbreviated’ or ‘narrow’
Return:
  • the era names
get_exponential_symbol()

Return the symbol used to separate mantissa and exponent

>>> Locale('en', 'US').get_exponential_symbol()
u'E'
get_group_symbol()

Return the symbol used to separate groups of thousands

>>> Locale('en', 'US').get_group_symbol()
u','
get_minus_sign_symbol()

Return the plus sign symbol

>>> Locale('en', 'US').get_minus_sign_symbol()
u'-'
get_month_names(width='wide', context='format')

Return the month names for the specified format

>>> Locale('en', 'US').get_month_names('wide')[1]
u'January'
>>> Locale('es').get_month_names('abbreviated')[1]
u'ene'
>>> Locale('de', 'DE').get_month_names('narrow', context='stand-alone')[1]
u'J'
In:
  • width – ‘wide’, ‘abbreviated’ or ‘narrow’
  • context – either ‘format’ or ‘stand-alone’
Return:
  • the month names
get_period_names()

Return the names for day periods (AM/PM)

>>> Locale('en', 'US').get_period_names()['am']
u'AM'
get_plus_sign_symbol()

Return the plus sign symbol

>>> Locale('en', 'US').get_plus_sign_symbol()
u'+'
get_quarter_names(width='wide', context='format')

Return the quarter names for the specified format

>>> Locale('en', 'US').get_quarter_names('wide')[1]
u'1st quarter'
>>> Locale('de', 'DE').get_quarter_names('abbreviated')[1]
u'Q1'
In:
  • width – ‘wide’, ‘abbreviated’ or ‘narrow’
  • context – either ‘format’ or ‘stand-alone’
Return:
  • the quarter names
get_time_format(format='medium')

Return the time formatting pattern for the specified format

>>> Locale('en', 'US').get_time_format()
<DateTimePattern u'h:mm:ss a'>
>>> Locale('de', 'DE').get_time_format('full')
<DateTimePattern u'HH:mm:ss v'>
In:
  • format – ‘full’, ‘long’, ‘medium’ or ‘short’
Return:
  • the time formatting pattern
get_timezone_gmt(dt=None, width='long')

Return the timezone associated with the given dt datetime object, formatted as string indicating the offset from GMT

>>> dt = datetime.datetime(2007, 4, 1, 15, 30)
>>> Locale('en').get_timezone_gmt(dt)
u'GMT+00:00'
In:
  • datetime – a datetime object; if None, the current date and time in UTC is used
  • width – either ‘long’ or ‘short’
Return:
  • The timezone
get_timezone_location(dt_or_timezone=None)

Return a representation of the given timezone using “location format”

The result depends on both the local display name of the country and the city associated with the time zone:

>>> from pytz import timezone
>>> tz = timezone('America/St_Johns')
>>> Locale('de', 'DE').get_timezone_location(tz)
u"Kanada (St. John's)"
>>> tz = timezone('America/Mexico_City')
>>> Locale('de', 'DE').get_timezone_location(tz)
u'Mexiko (Mexiko-Stadt)'
In:
  • dt_or_tzinfodatetime or tzinfo object that determines the timezone; if None, the current date and time in UTC is assumed
Return:
  • the timezone representation
get_timezone_name(dt_or_timezone=None, width='long', uncommon=False)

Return the localized display name for the given timezone

In:
  • dt_or_timezone – the timezone, specified using a datetime or tzinfo object
  • width
  • uncommon
>>> from pytz import timezone
>>> dt = datetime.time(15, 30, tzinfo=timezone('America/Los_Angeles'))
>>> Locale('en', 'US').get_timezone_name(dt)
u'Pacific Standard Time'
>>> Locale('en', 'US').get_timezone_name(dt, width='short')
u'PST'
In:
  • dt_or_tzinfo – the datetime or tzinfo object that determines the timezone; if a tzinfo object is used, the resulting display name will be generic, i.e. independent of daylight savings time; if None, the current date in UTC is assumed
  • width – either ‘long’ or ‘short’
  • uncommon – whether even uncommon timezone abbreviations should be used
Return:
  • the localized timezone name
get_translation_directory(domain=None)

Return the directory associated to the domain

In:
  • domain – the translation domain
gettext(msg, domain=None, **kw)

Return the localized translation of a message

In:
  • msg – message to translate
  • domain – translation domain
  • kw – optional values to substitute into the translation
Return:
  • the localized translation, as a 8-bit string encoded with the catalog’s charset encoding
has_translation_directory(domain=None)

Test if a domain has an associated directory

In:
  • domain – the translation domain
Return:
  • bool
lazy_gettext(msg, domain=None, **kw)

Return the lazy localized translation of a message

In:
  • msg – message to translate
  • domain – translation domain
  • kw – optional values to substitute into the translation
Return:
  • the lazy localized translation, as a 8-bit string encoded with the catalog’s charset encoding
lazy_ngettext(singular, plural, n, domain=None, **kw)

Return the lazy plural-forms localized translation of a message

If a translation is found, apply the plural formula to n, and return the resulting translation. If no translation is found, return singular if n is 1; return plural otherwise

In:
  • singular – singular form of the message
  • plural – plural form of the message
  • n – singular or plural form wanted?
  • domain – translation domain
  • kw – optional values to substitute into the translation
Return:
  • the lazy localized translation, as a 8-bit string encoded with the catalog’s charset encoding
lazy_ugettext(msg, domain=None, **kw)

Return the lazy localized translation of a message

In:
  • msg – message to translate
  • domain – translation domain
  • kw – optional values to substitute into the translation
Return:
  • the lazy localized translation, as an unicode string
lazy_ungettext(singular, plural, n, domain=None, **kw)

Return the lazy plural-forms localized translation of a message

If a translation is found, apply the plural formula to n, and return the resulting translation. If no translation is found, return singular if n is 1; return plural otherwise

In:
  • singular – singular form of the message
  • plural – plural form of the message
  • n – singular or plural form wanted?
  • domain – translation domain
  • kw – optional values to substitute into the translation
Return:
  • the lazy localized translation, as an unicode string
ngettext(singular, plural, n, domain=None, **kw)

Return the plural-forms localized translation of a message

If a translation is found, apply the plural formula to n, and return the resulting translation. If no translation is found, return singular if n is 1; return plural otherwise

In:
  • singular – singular form of the message
  • plural – plural form of the message
  • n – singular or plural form wanted?
  • domain – translation domain
  • kw – optional values to substitute into the translation
Return:
  • the localized translation, as a 8-bit string encoded with the catalog’s charset encoding
parse_date(string)

Parse a date from a string

This function uses the date format for the locale as a hint to determine the order in which the date fields appear in the string.

>>> Locale('en', 'US').parse_date('4/1/04')
datetime.date(2004, 4, 1)
>>> Locale('de', 'DE').parse_date('01.04.2004')
datetime.date(2004, 4, 1)
In:
  • string – the string containing the date
Return:
  • a datetime.datetime object
parse_decimal(string)

Parse localized decimal string into a float

>>> Locale('en', 'US').parse_decimal('1,099.98')
1099.98
>>> Locale('de').parse_decimal('1.099,98')
1099.98

When the given string cannot be parsed, an exception is raised:

>>> Locale('de').parse_decimal('2,109,998')
Traceback (most recent call last):
    ...
NumberFormatError: '2,109,998' is not a valid decimal number
parse_number(string)

Parse localized number string into a long integer

>>> Locale('en', 'US').parse_number('1,099')
1099L
>>> Locale('de', 'DE').parse_number('1.099')
1099L

When the given string cannot be parsed, an exception is raised:

>>> Locale('de').parse_number('1.099,98')
Traceback (most recent call last):
    ...
NumberFormatError: '1.099,98' is not a valid number
parse_time(string)

Parse a time from a string

This function uses the time format for the locale as a hint to determine the order in which the time fields appear in the string.

>>> Locale('en', 'US').parse_time('15:30:00')
datetime.time(15, 30)
In:
  • string – the string containing the time
Return:
  • a datetime.time object
to_timezone(dt)

Return a localized datetime object

In:
  • dtdatetime object
Return:
  • new localized datetime object
to_utc(dt)

Return a UTC datetime object

In:
  • dtdatetime object
Return:
  • new localized to UTC datetime object
ugettext(msg, domain=None, **kw)

Return the localized translation of a message

In:
  • msg – message to translate
  • domain – translation domain
  • kw – optional values to substitute into the translation
Return:
  • the localized translation, as an unicode string
ungettext(singular, plural, n, domain=None, **kw)

Return the plural-forms localized translation of a message

If a translation is found, apply the plural formula to n, and return the resulting translation. If no translation is found, return singular if n is 1; return plural otherwise

In:
  • singular – singular form of the message
  • plural – plural form of the message
  • n – singular or plural form wanted?
  • domain – translation domain
  • domain – translation domain
  • kw – optional values to substitute into the translation
Return:
  • the localized translation, as an unicode string
class nagare.i18n.NegotiatedLocale(request, locales, default_locale=(None, None), dirname=None, domain=None, timezone=None, default_timezone=None)

Bases: nagare.i18n.Locale

nagare.i18n.add_child(self, lazy)

Add a lazy string to a tag

In:
  • self – the tag
  • lazy – the lazy string to add
nagare.i18n.format_currency(number, currency, format=None)
nagare.i18n.format_date(d=None, format='medium')
nagare.i18n.format_datetime(dt=None, format='medium')
nagare.i18n.format_decimal(number, format=None)
nagare.i18n.format_number(number)
nagare.i18n.format_percent(number, format=None)
nagare.i18n.format_scientific(number, format=None)
nagare.i18n.format_time(t=None, format='medium')
nagare.i18n.get_currency_name(currency)
nagare.i18n.get_currency_symbol(currency)
nagare.i18n.get_date_format(format='medium')
nagare.i18n.get_datetime_format(format='medium')
nagare.i18n.get_day_names(width='wide', context='format')
nagare.i18n.get_decimal_symbol()
nagare.i18n.get_era_names(width='wide')
nagare.i18n.get_exponential_symbol()
nagare.i18n.get_group_symbol()
nagare.i18n.get_locale()
nagare.i18n.get_minus_sign_symbol()
nagare.i18n.get_month_names(width='wide', context='format')
nagare.i18n.get_period_names()
nagare.i18n.get_plus_sign_symbol()
nagare.i18n.get_quarter_names(width='wide', context='format')
nagare.i18n.get_time_format(format='medium')
nagare.i18n.get_timezone_gmt(dt=None, width='long')
nagare.i18n.get_timezone_location(dt_or_timezone=None)
nagare.i18n.get_timezone_name(dt_or_timezone=None, width='long', uncommon=False)
nagare.i18n.gettext(msg, domain=None, **kw)
nagare.i18n.lazy_gettext(msg, domain=None, **kw)
nagare.i18n.lazy_ngettext(singular, plural, n, domain=None, **kw)
nagare.i18n.lazy_ugettext(msg, domain=None, **kw)
nagare.i18n.lazy_ungettext(singular, plural, n, domain=None, **kw)
nagare.i18n.ngettext(singular, plural, n, domain=None, **kw)
nagare.i18n.parse_date(string)
nagare.i18n.parse_decimal(string)
nagare.i18n.parse_number(string)
nagare.i18n.parse_time(string)
nagare.i18n.py2js(lazy, h)

Generic method to transcode a lazy string to javascript

In:
  • lazy – the lazy string
  • h – the current renderer
Return:
  • transcoded javascript
nagare.i18n.serialize(lazy, content_type, doctype, declaration)

Generic method to generate a text from a lazy string

In:
  • lazy – the lazy string
  • content_type – the rendered content type
  • doctype – the (optional) doctype
  • declaration – is the XML declaration to be outputed ?
Return:
  • a tuple (content_type, content)
nagare.i18n.set_locale(locale)
nagare.i18n.to_timezone(dt)
nagare.i18n.to_utc(dt)
nagare.i18n.ugettext(msg, domain=None, **kw)
nagare.i18n.ungettext(singular, plural, n, domain=None, **kw)

nagare.local module

Scoped objects

Currently:

  • objects scoped to a worker, a handler of a request
  • objects scoped to a request (i.e a scoped cleared on each new request)
class nagare.local.DummyLock

Bases: object

acquire()
release()
class nagare.local.Process

Bases: object

Objects with attributs scoped to the current thread

clear()
create_lock()
class nagare.local.Thread

Bases: thread._local

Objects with attributs scoped to the current thread

clear()
create_lock()

nagare.log module

class nagare.log.ConfigObjToConfigParser(infile=None, options=None, configspec=None, encoding=None, interpolation=True, raise_errors=False, list_values=True, create_empty=False, file_error=False, stringify=True, indent_type=None, default_encoding=None, unrepr=False, write_empty_values=False, _inspec=False)

Bases: configobj.ConfigObj

Output a ConfigParser format from a ConfigObj input

nagare.log.activate()

Use the merging of all the logging configurations to configure the Python logging system

nagare.log.configure(log_conf, app_name=None)

Merge all the applications logging configurations

In:
  • log_conf – an application logging configuration
  • app_name – the name of the application
nagare.log.critical(msg, *args, **kw)
nagare.log.debug(msg, *args, **kw)
nagare.log.error(msg, *args, **kw)
nagare.log.exception(msg, *args)
nagare.log.get_logger(name='.')
nagare.log.info(msg, *args, **kw)
nagare.log.log(level, msg, *args, **kw)
nagare.log.set_logger(name)
nagare.log.warning(msg, *args, **kw)

nagare.partial module

Serializable partial functions

class nagare.partial.Decorator(f, new_f, *args, **kw)

Bases: object

Use a _Partial() to decorate a function

create_partial(o=None)

Create a _Partial() to call new_f

new_f will be called with the parameters:

  • self (None if f is a function)
  • f
  • args, kw
nagare.partial.Partial(__f, *args, **kw)

Don’t double wrap a _Partial() object if not needed

nagare.partial.max_number_of_args(nb)

Limit the number of positional parameters

In:
  • nb - max number of positional parameters passed to f. Other
    positional parameters will be passed as the args tuple

nagare.presentation module

Generic methods to associate views and URLs to objects

exception nagare.presentation.ModelError

Bases: exceptions.LookupError

nagare.presentation.init(self, url, comp, http_method, request)

Generic method to initialized an object from a URL

In:
  • self – the object
  • url – the URL
  • comp – the component
  • http_method – the HTTP method
  • request – the web request object
nagare.presentation.init_for(cls, cond=None)

Decorator helper to register an URL for a class of objects

In:
  • cls – the class
  • cond – a generic condition
Return:
  • a closure
nagare.presentation.render(self, renderer, comp, model)

Generic method to associate views to an object

The views are implementation functions of this generic method

This default implementation raises an exception

In:
  • self – the object
  • renderer – the renderer
  • comp – the component
  • model – the name of the view
nagare.presentation.render_for(cls, model=None)

Decorator helper to register a view for a class of objects

In:
  • cls – the class
  • model – the name of the view
Return:
  • a closure
nagare.presentation.render_for_cond(cond)

Decorator helper to register a view for a given condition

In:
  • cond – the condition
Return:
  • closure

nagare.pyjs module

class nagare.pyjs.AppTranslator(library_dirs=['../library'], parser=None)
findFile(file_name)
translate(module_name, is_app=True)
translateLibraries(library_modules=[])
class nagare.pyjs.Klass(name)
add_function(function_name)
klasses = {}
set_base(base_name)
class nagare.pyjs.PlatformParser(platform_dir='')
copyFunction(target, source)
generatePlatformFilename(file_name)
merge(tree1, tree2)
parseModule(module_name, file_name)
replaceClassMethods(tree, class_name, class_node)
replaceFunction(tree, function_name, function_node)
setPlatform(platform)
exception nagare.pyjs.TranslationError(message, node)

Bases: exceptions.Exception

class nagare.pyjs.Translator(module_name, mod, output)
classattr(node, current_klass)
expr(node, current_klass)
nagare.pyjs.translate(file_name, module_name)

nagare.serializer module

Generate the content to return to the browser

nagare.serializer.serialize(output, content_type, doctype, declaration)

Generic method to generate the content for the browser

In:
  • output – the rendered content
  • content_type – the rendered content type
  • doctype – the (optional) doctype
  • declaration – is the XML declaration to be outputed?
Return:
  • a tuple (content_type, content)

nagare.state module

Helper to mark an object as stateless

nagare.state.stateful(o)

Mark an object as stateful

In:
  • o – the object
Return:
  • o
nagare.state.stateless(o)

Mark an object as stateless

In:
  • o – the object
Return:
  • o

nagare.top module

Add <html><head><body> around a tree

nagare.top.search_element(element_name, l)

Search an element with element_name name as the first element in l

Skip the comments and processing instructions at the start of l

In:
  • element_name – name of the element to search
  • l – list of elements
Return:
  • if found: (position of the next element, element found)
  • else: (0, None)
nagare.top.wrap(content_type, h, content)

Add the tags <html>, <head> and <body> is they don’t exist

In:
  • content_type – the content type to send to the browser
  • h – the current renderer
  • content – the rendered tree
Return:
  • new tree with <html>, <head> and <body>

nagare.util module

Various pre-defined components

class nagare.util.Ask(msg)

Bases: object

Ask the user to enter a line of text

The text entered is answered

classmethod answer(comp, r)
class nagare.util.Confirm(msg)

Bases: object

Display a confirmation message

class nagare.util.View(view)

Bases: object

A differed view

Can be useful to add a view for a component.Task

nagare.util.render(self, h, comp, *args)

The view is a simple form with a text input control

In:
  • h – the renderer
  • comp – the component
  • model – the name of the view
Return:
  • a tree
nagare.util.render_confirm(self, h, comp, *args)

The view is a simple form with the text and a submit button

In:
  • h – the renderer
  • comp – the component
  • model – the name of the view
Return:
  • a tree
nagare.util.render_view(self, h, *args)

To render this object, call the differed view function

In:
  • h – the renderer
Return:
  • a tree

nagare.validator module

Set of validating objects

Suitable to be the validating functions of editor.property objects

class nagare.validator.DualCallable

Bases: type

“A hackish metaclass to allow both direct and deferred calls of methods

For compatibility with the old and new way to built a validation chain.

Examples:

  • Old validation with direct calls: valid = lambda v: IntValidator(v).greater_than(10)
  • New validation with lazy calls: valid = IntValidator().greater_than(10)
class nagare.validator.IntValidator(*args, **kw)

Bases: nagare.validator.Validator

Conversion and validation of integers

greater_or_equal_than(*args, **kw)

Check that the value is greater or equal than a limit

In:
  • max – the limit
  • msg – message to raise
Return:
  • self
greater_than(*args, **kw)

Check that the value is greater than a limit

In:
  • max – the limit
  • msg – message to raise
Return:
  • self
lesser_or_equal_than(*args, **kw)

Check that the value is lesser or equal than a limit

In:
  • max – the limit
  • msg – message to raise
Return:
  • self
lesser_than(*args, **kw)

Check that the value is lesser than a limit

In:
  • max – the limit
  • msg – message to raise
Return:
  • self
to_int(*args, **kw)

Return the already validated value or call now all the deferred methods

In:
  • v – optional value to validate
Return:
  • the final result of all the calls
class nagare.validator.StringValidator(*args, **kw)

Bases: nagare.validator.Validator

Conversion and validation of string

isalnum(*args, **kw)
isalpha(*args, **kw)
isdigit(*args, **kw)
islower(*args, **kw)
isspace(*args, **kw)
isupper(*args, **kw)
length_equal(*args, **kw)

Check that the value has an exact length

In:
  • v – the length
  • msg – message to raise
Return:
  • self
longer_or_equal_than(*args, **kw)

Check that the value is longer or equal than a limit

In:
  • min – the limit
  • msg – message to raise
Return:
  • self
longer_than(*args, **kw)

Check that the value is longer than a limit

In:
  • min – the limit
  • msg – message to raise
Return:
  • self
match(*args, **kw)

Check that the value respects a format given as a regexp

In:
  • r – the regexp
  • msg – message to raise
Return:
  • self
not_empty(*args, **kw)

Check that the value is not empty

In:
  • msg – message to raise
Return:
  • self
shorter_or_equal_than(*args, **kw)

Check that the value is shorter or equal than a limit

In:
  • max – the limit
  • msg – message to raise
Return:
  • self
shorter_than(*args, **kw)

Check that the value is shorter than a limit

In:
  • max – the limit
  • msg – message to raise
Return:
  • self
to_int(*args, **kw)

Return the value, converted to an integer

In:
  • base – base for the conversion
Return:
  • the integer value
to_string(*args, **kw)

Return the already validated value or call now all the deferred methods

In:
  • v – optional value to validate
Return:
  • the final result of all the calls
class nagare.validator.Validator(*args, **kw)

Bases: nagare.validator.ValidatorBase

Base class for the validation objects

class nagare.validator.ValidatorBase

Bases: object

“A hackish base class to allow both direct and deferred calls of methods

For compatibility with the old and new way to built a validation chain.

Examples:

  • Old validation with direct calls: valid = lambda v: IntValidator(v).greater_than(10)
  • New validation with lazy calls: valid = IntValidator().greater_than(10)
nagare.validator.to_int

alias of IntValidator

nagare.validator.to_string

alias of StringValidator

nagare.var module

Variables with a functional interface:

  • v() – return the value of v
  • v(x) – set the value of v to x

For example:

v = v + 1 becomes v(v()+1)

Handy into the lambda expressions

class nagare.var.Var(v=None)

Bases: object

Functional variables

get()

Return the value

Return:
  • the value
render(renderer)

When directly put into a XML tree, render its value

In:
  • renderer – the current renderer
Return:
  • the variable value
set(v)

Set the value

Return:
  • the value

nagare.wsgi module

A WSGIApp object is an intermediary object between a publisher and the root component of the application

A WSGIApp conforms to the WSGI interface and has a component factory. So, each time the WSGIApp receives a request without a session id or with an expired session id, it creates a new root component and a new session.

class nagare.wsgi.Request(environ, charset=None, unicode_errors=None, decode_param_names=None, **kw)

Bases: webob.request.Request

create_redirect_response(location=None)
is_xhr
class nagare.wsgi.Response(accept)

Bases: webob.response.Response

class nagare.wsgi.WSGIApp(root_factory)

Bases: object

create_renderer(async, session, request, response)

Create the initial renderer (the root of all the used renderers)

In:
  • async – is an XHR request ?
  • session – the session
  • request – the web request object
  • response – the web response object
create_request(environ)

Create the webob.Request object

In:
  • environ – dictionary of the received elements from the browser
Return:
  • a webob.Request object
create_response(request, accept)

Create the webob.Response object

In:
  • request – the webob.Request object
  • accept – the Accept HTTP header to use
Return:
  • a webob.Response object
create_root(*args, **kw)

Create the application root component

Return:
  • the root component
on_after_post(request, response, ids)

Generate a redirection after a POST

In:
  • request – the web request object
  • response – the web response object
  • ids – identifiers to put into the generated redirection URL
Return:
  • a webob.exc object, used to generate the response to the browser
on_back(request, response, h, output)

The user used the back button

In:
  • request – the web request object
  • response – the web response object
  • h – the current renderer
  • output – the tree for the refreshed page
Return:
  • a tree
on_bad_http_method(request, response)

A HTTP request other than a GET or PUT was received

In:
  • request – the web request object
  • response – the web response object
Return:
  • raise a webob.exc object, used to generate the response to the browser
on_callback_lookuperror(request, response, async)

A callback was not found

In:
  • request – the web request object
  • response – the web response object
  • async – is an XHR request ?
on_exception(request, response)

Method called when an exception occurs

In:
  • request – the web request object
  • response – the web response object
Return:
  • a webob response object
on_expired_session(request, response)

The session or state id received is expired

In:
  • request – the web request object
  • response – the web response object
Return:
  • raise a webob.exc object, used to generate the response to the browser
on_incomplete_url(request, response)

An URL without an application name was received

In:
  • request – the web request object
  • response – the web response object
Return:
  • raise a webob.exc object, used to generate the response to the browser
on_invalid_session(request, response)

The secure id received is invalid

In:
  • request – the web request object
  • response – the web response object
Return:
  • raise a webob.exc object, used to generate the response to the browser
on_session_expired(request, response)

The session or state id received is expired

In:
  • request – the web request object
  • response – the web response object
Return:
  • raise a webob.exc object, used to generate the response to the browser
renderer_factory

alias of Renderer

request_factory

alias of Request

response_factory

alias of Response

set_config(config_filename, config, error)

Read the configuration parameters

In:
  • config_filename – the path to the configuration file
  • config – the ConfigObj object, created from the configuration file
  • error – the function to call in case of configuration errors
set_data_path(data_path)

Register the directory of the data

In:
  • data_path – the directory where the data of the application are located
set_databases(databases)

Register the databases properties

In:
  • databases – the SQLAlchemy metadata objects and the database engines settings
set_default_locale(locale)

Register the default locale

In:
  • locale – the default locale
set_locale(locale)

Set the locale of the request scope

In:
  • locale – the locale
set_project(name)

The application distribution name

In:
  • project_name – name of the distutils distribution where the app is located
set_publisher(publisher)

Register the publisher

In:
  • publisher – the publisher of the application
set_sessions_manager(sessions_manager)

Register the sessions manager

In:
  • sessions_manager – the sessions manager
set_static_path(static_path)

Register the directory of the static contents

In:
  • static_path – the directory where the static contents of the application are located
set_static_url(static_url)

Register the url of the static contents

In:
  • static_url – the url of the static contents of the application
start()

Call after each process start

start_request(root, request, response)

A new request is received, setup its dedicated environment

In:
  • root – the application root component
  • request – the web request object
  • response – the web response object
nagare.wsgi.create_WSGIApp(app, with_component=True)

Helper function to create a WSGIApp

If app is not a WSGIApp, it’s wrap into a WSGIApp. And, if with_component is True, each time a new root object is created, it’s automatically wrap into a component.Component.

In:
  • app – the application root component factory
  • with_component – wrap a new root object into a component

Module contents