MoinMoin package

Subpackages

Submodules

MoinMoin.app module

MoinMoin - wsgi application setup and related code

Use create_app(config) to create the WSGI application (using Flask).

MoinMoin.app.before_wiki()[source]

Setup environment for wiki requests, start timers.

MoinMoin.app.create_app(config=None, create_index=False, create_storage=False)[source]

simple wrapper around create_app_ext() for flask-script

MoinMoin.app.create_app_ext(flask_config_file=None, flask_config_dict=None, moin_config_class=None, warn_default=True, **kwargs)[source]

Factory for moin wsgi apps

Parameters:
  • flask_config_file – a flask config file name (may have a MOINCFG class), if not given, a config pointed to by MOINCFG env var will be loaded (if possible).
  • flask_config_dict – a dict used to update flask config (applied after flask_config_file was loaded [if given])
  • moin_config_class – if you give this, it’ll be instantiated as app.cfg, otherwise it’ll use MOINCFG from flask config. If that also is not there, it’ll use the DefaultConfig built into MoinMoin.
  • warn_default – emit a warning if moin falls back to its builtin default config (maybe user forgot to specify MOINCFG?)
  • kwargs – if you give additional keyword args, the keys/values will get patched into the moin configuration class (before its instance is created)
MoinMoin.app.deinit_backends(app)[source]
MoinMoin.app.destroy_app(app)[source]
MoinMoin.app.init_backends(app)[source]

initialize the backends

MoinMoin.app.setup_user()[source]

Try to retrieve a valid user object from the request, be it either through the session or through a login.

MoinMoin.app.teardown_wiki(response)[source]

Teardown environment of wiki requests, stop timers.

MoinMoin.conftest module

MoinMoin Testing Framework

All test modules must be named test_modulename to be included in the test suite. If you are testing a package, name the test module test_package_module.

Tests that require a certain configuration, like section_numbers = 1, must use a Config class to define the required configuration within the test class.

class MoinMoin.conftest.Module(fspath, parent=None, config=None, session=None)[source]

Bases: _pytest.python.Module

run(*args, **kwargs)[source]
MoinMoin.conftest.app(app_ctx)[source]
MoinMoin.conftest.app_ctx(cfg)[source]
MoinMoin.conftest.cfg()[source]
MoinMoin.conftest.pytest_pycollect_makemodule(path, parent)[source]
MoinMoin.conftest.pytest_report_header(config)[source]

MoinMoin.error module

MoinMoin errors / exception classes

exception MoinMoin.error.CompositeError(message)[source]

Bases: MoinMoin.error.Error

Base class for exceptions containing an exception

Do not use this class but its more specific sub classes.

Useful for hiding low level error inside high level user error, while keeping the inner error information for debugging.

Example:

class InternalError(CompositeError):
    ''' Raise for internal errors '''

try:
    # code that might fail...
except HairyLowLevelError:
    raise InternalError("Sorry, internal error occurred")

When showing a traceback, both InternalError traceback and HairyLowLevelError traceback are available.

exceptions()[source]

Return a list of all inner exceptions

exception MoinMoin.error.ConfigurationError(message)[source]

Bases: MoinMoin.error.FatalError

Raise when fatal misconfiguration is found

exception MoinMoin.error.Error(message)[source]

Bases: exceptions.Exception

Base class for moin moin errors

Use this class when you raise errors or create sub classes that may be used to display non ASCII error message.

Standard errors work safely only with strings using ascii or unicode. This class can be used safely with both strings using CHARSET and unicode.

You can init this class with either unicode or string using CHARSET encoding. On output, the class will convert the string to unicode or the unicode to string, using CHARSET.

When you want to render an error, use unicode() or str() as needed.

exception MoinMoin.error.FatalError(message)[source]

Bases: MoinMoin.error.CompositeError

Base class for fatal error we can’t handle

Do not use this class but its more specific sub classes.

exception MoinMoin.error.InternalError(message)[source]

Bases: MoinMoin.error.FatalError

Raise when internal fatal error is found

MoinMoin.forms module

MoinMoin - Flatland widgets

General Flatland widgets containing hints for the templates.

MoinMoin.forms.AnyInteger

alias of Integer

class MoinMoin.forms.BackReference(value=Unspecified, **kw)[source]

Bases: MoinMoin.forms.List

Back references built from Whoosh query.

set(query, **query_args)[source]
MoinMoin.forms.Checkbox

alias of Boolean

MoinMoin.forms.DateTime

alias of DateTimeUNIX

class MoinMoin.forms.DateTimeUNIX(value=Unspecified, **kw)[source]

Bases: flatland.schema.scalars.DateTime

A DateTime that uses a UNIX timestamp instead of datetime as internal representation of DateTime.

adapt(value)[source]

Coerces value to a native UNIX timestamp.

If value is an instance of int and it is a correct UNIX timestamp, returns it unchanged. Otherwise uses DateTime superclass to parse it.

serialize(value)[source]

Serializes value to string.

MoinMoin.forms.Email

alias of String

class MoinMoin.forms.Enum(value=Unspecified, **kw)[source]

Bases: flatland.schema.scalars.Enum

An Enum with a convenience class method out_of.

classmethod out_of(choice_specs, sort_by=None)[source]

A convenience class method to build Enum with extra data attached to each valid value.

Parameters:
  • choice_specs – An iterable of tuples. The elements are collected into the choice_specs property; the tuples’ first elements become the valid values of the Enum. e.g. for choice_specs = [(v1, ...), (v2, ...), ... ], the valid values are v1, v2, ...
  • sort_by – If not None, sort choice_specs by the sort_by’th element.
MoinMoin.forms.File

alias of FileStorage

MoinMoin.forms.Hidden

alias of String

MoinMoin.forms.InlineCheckbox

alias of Boolean

MoinMoin.forms.JSON

alias of String

MoinMoin.forms.MultiSelect

alias of Array

MoinMoin.forms.MultilineText

alias of String

class MoinMoin.forms.MyJoinedString(value=Unspecified, **kw)[source]

Bases: flatland.schema.compound.JoinedString

A JoinedString that offers the list of children (not the joined string) as value property.

u
value
exception MoinMoin.forms.NameNotValidError[source]

Bases: exceptions.ValueError

The name is not valid.

MoinMoin.forms.Names

alias of MyJoinedString

MoinMoin.forms.Natural

alias of Integer

MoinMoin.forms.OpenID

alias of String

MoinMoin.forms.OptionalMultilineText

alias of String

MoinMoin.forms.OptionalText

alias of String

MoinMoin.forms.Password

alias of String

alias of MyJoinedString

alias of List

MoinMoin.forms.ReadonlyStringList

alias of List

class MoinMoin.forms.Reference(value=Unspecified, **kw)[source]

Bases: MoinMoin.forms.Enum

A metadata property that points to another item selected out of the Results of a search query.

to(query, query_args={})[source]
MoinMoin.forms.RequiredMultilineText

alias of String

MoinMoin.forms.RequiredPassword

alias of String

MoinMoin.forms.RequiredText

alias of String

MoinMoin.forms.Search

alias of String

MoinMoin.forms.Select

alias of Enum

MoinMoin.forms.SelectSubmit

alias of Enum

MoinMoin.forms.SmallNatural

alias of Integer

MoinMoin.forms.Subscriptions

alias of SubscriptionsJoinedString

class MoinMoin.forms.SubscriptionsJoinedString(value=Unspecified, **kw)[source]

Bases: flatland.schema.compound.JoinedString

A JoinedString that offers the list of children as value property and also appends the name of the item to the end of ITEMID subscriptions.

u
value
MoinMoin.forms.Tags

alias of MyJoinedString

MoinMoin.forms.Text

alias of String

MoinMoin.forms.URL

alias of String

class MoinMoin.forms.ValidJSON(**kw)[source]

Bases: flatland.validation.base.Validator

Validator for JSON

invalid_itemid_msg = l'Itemid not a proper UUID'
invalid_json_msg = l'Invalid JSON.'
invalid_namespace_msg = ''
validate(element, state)[source]
validitemid(itemid)[source]
validnamespace(current_namespace)[source]
class MoinMoin.forms.ValidName(**kw)[source]

Bases: flatland.validation.base.Validator

Validator for Name

invalid_name_msg = ''
validate(element, state)[source]
class MoinMoin.forms.ValidReference(**kw)[source]

Bases: flatland.validation.base.Validator

Validator for Reference

invalid_reference_msg = l'Invalid Reference.'
validate(element, state)[source]
MoinMoin.forms.YourEmail

alias of String

MoinMoin.forms.YourOpenID

alias of String

MoinMoin.forms.validate_name(meta, itemid)[source]

Check whether the names are valid. Will just return, if they are valid, will raise a NameNotValidError if not.

MoinMoin.log module

MoinMoin - init “logging” system

WARNING

logging must be configured VERY early, before the code in log.getLogger gets executed. Thus, logging is configured either by:

  1. an environment variable MOINLOGGINGCONF that contains the path/filename of a logging configuration file - this method overrides all following methods (except if it can’t read or use that configuration, then it will use c))
  2. by an explicit call to MoinMoin.log.load_config(‘logging.conf’) - you need to do this very early or a) or c) will happen before
  3. by using a builtin fallback logging conf

If logging is not yet configured, log.getLogger will do an implicit configuration call - then a) or c) is done.

Usage (for wiki server admins)

Either use something like this in some shell script: MOINLOGGINGCONF=/path/to/logging.conf export MOINLOGGINGCONF

Or, modify your server adaptor script (e.g. moin.cgi) to do this:

from MoinMoin import log
log.load_config('wiki/config/logging/logfile') # XXX please fix this path!

You have to fix that path to use a logging configuration matching your needs (we provide some examples in the path given there, it is relative to the uncompressed moin distribution archive - if you use some moin package, you maybe find it under /usr/share/moin/). It is likely that you also have to edit the sample logging configurations we provide (e.g. to fix the logfile location).

Usage (for developers)

If you write code for moin, do this at top of your module:

from MoinMoin import log
logging = log.getLogger(__name__)

This will create a logger with ‘MoinMoin.your.module’ as name. The logger can optionally get configured in the logging configuration. If you don’t configure it, some upperlevel logger (e.g. the root logger) will do the logging.

class MoinMoin.log.EmailHandler(toaddrs=[], subject=u'')[source]

Bases: logging.Handler

A custom handler class which sends email for each logging event using wiki mail configuration

emit(record)[source]

Emit a record.

Send the record to the specified addresses

MoinMoin.log.getLogger(name)[source]

wrapper around logging.getLogger, so we can do some more stuff:

  • preprocess logger name
  • patch loglevel constants into logger object, so it can be used instead of the logging module
MoinMoin.log.load_config(conf_fname=None)[source]

load logging config from conffile

MoinMoin.user module

MoinMoin - User Accounts

TODO: Currently works on unprotected user backend

This module contains functions to access user accounts (list all users, get some specific user). User instances are used to access the user profile of some specific user (name, password, email, bookmark, trail, settings, ...).

class MoinMoin.user.User(uid=None, name='', password=None, auth_username='', trusted=False, **kw)[source]

Bases: object

A MoinMoin User

add_trail(item_name)[source]

Add item name to trail.

Parameters:item_name – the item name (unicode) to add to the trail
apply_recovery_token(token, newpass)[source]
avatar(size=30)[source]
bookmark

Get bookmark timestamp.

Return type:int / None
Returns:bookmark timestamp or None
create_or_update(changed=False)[source]

Create or update a user profile

Parameters:changed – bool, set this to True if you updated the user profile values
exists()[source]

Do we have a user profile for this user?

Return type:bool
Returns:true, if we have a user account
generate_recovery_token()[source]
generate_session_token(save=True)[source]

Generate new session token and key pair. Used to validate sessions.

getText(text)[source]

translate a text to the language of this user

get_session_token()[source]

Get current session token. If there is no token, generate a new one.

get_trail()[source]

Return list of recently visited item names.

Return type:list
Returns:item names (unicode) in trail
has_invalidated_password()[source]

Check if the password hash of this user is invalid.

is_current_user()[source]

Check if this user object is the user doing the current request

is_quicklinked_to(pagelist)[source]

Check if user quicklink matches any page in pagelist.

Parameters:pagelist – list of pages to check for quicklinks
Return type:bool
Returns:if user has quicklinked any page in pagelist
is_subscribed_to(item)[source]

Check if user is subscribed to the following item

Parameters:item – Item object
Return type:bool
Returns:if user is subscribed to the item
language
load_from_id(itemid, password=None)[source]

Load user account data from disk.

Parameters:password – If not None, then the given password must match the password in the user account file.
logout_session(all_browsers=True)[source]

Terminate session in all browsers unless all_browsers is set to False

mail_email_verification()[source]

Mail a user a link to verify his email address.

mail_password_recovery(cleartext_passwd=None, subject=None, text=None)[source]

Mail a user who forgot his password a message enabling him to login again.

name0

Adds a page to the user quicklinks

Add links as interwiki names.

Parameters:pagename (unicode) – page name
Return type:bool
Returns:if pagename was added

Remove a page from user quicklinks

Remove interwiki name from quicklinks.

Parameters:pagename (unicode) – page name
Return type:bool
Returns:if pagename was removed
save(force=False)[source]

Save user account data to user account file on disk.

set_password(password, is_encrypted=False, salt=None)[source]

Set or update the password (hash) stored for this user.

Parameters:
  • password – the new password (or pw hash) giving an empty string or None as password will invalidate the stored password hash (meaning that it will not match against any given password)
  • is_encrypted – if False (default), the password is given as plaintext and will be “encrypted” (hashed) before getting stored. if True, the already “encrypted” password hash is given in param password and will be stored “as is” - this is mainly useful for tests.
  • salt – if None (default), passlib will generate and use a random salt. Otherwise, the given salt will be used - this is mainly useful for tests.
subscribe(keyword, value, namespace=None)[source]

Subscribe to a wiki page.

The user can subscribe in 5 different ways:

  • by itemid - ITEMID:<itemid value>
  • by item name - NAME:<namespace>:<name value>
  • by a tagname - TAGS:<namespace>:<tag value>
  • by a prefix name - NAMEPREFIX:<namespace>:<name prefix>
  • by a regular expression - NAMERE:<namespace>:<name regexp>
Parameters:
  • keyword – the keyword (itemid, name, tags, nameprefix, namere) by which the type of the subscription is determined
  • value – the subscription value (itemid, name, tag, regexp or nameprefix value)
  • namespace – the namespace of the subscription; itemid keyword doesn’t require a namespace
Return type:

bool

Returns:

if user was subscribed

unsubscribe(keyword, value, namespace=None, item=None)[source]

Unsubscribe from a wiki page.

Same as for subscribing, user can also unsubscribe in 5 ways. The unsubscribe action doesn’t guarantee that user will not receive any notification for this item, since user can be subscribed by some other patterns that match current item.

Parameters:
  • keyword – the keyword (itemid, name, tags, nameprefix, namere) by which the type of the subscription is determined
  • value – the subscription value (itemid, name, tag, regexp or nameprefix value)
  • namespace – the namespace of the subscription; itemid keyword doesn’t require a namespace
  • item – Item object to check if the user is still subscribed
Return type:

bool

Returns:

if user was unsubscribed

validate_recovery_token(token)[source]
validate_session(token)[source]

Check if the session token is valid.

Invalid session tokens happen for these cases:

  1. there are multiple sessions (different machines, different browsers) open for same user. the user then changes the password in one of these, which creates a new session key in the profile also, which invalidates all sessions everywhere else for this user.
  2. the user profile is gone (e.g. due to erasing the storage), then a invalid session key will be read from the profile (from cfg.user_defaults) that will never validate against the session key read from the session.
class MoinMoin.user.UserProfile(**q)[source]

Bases: object

A User Profile

load(**q)[source]

load a user profile, the query q can use any indexed (unique) field

save(force=False)[source]

save a user profile (if it was changed since loading it)

Note: if mutable profile values were modified, you need to use
force=True because these changes are not detected!
stored
MoinMoin.user.assemble_subscription(keyword, value, namespace=None)[source]

Create a valid subscription string

Parameters:
  • keyword – the keyword (itemid, name, tags, nameprefix, namere) by which the type of the subscription is determined
  • value – the subscription value (itemid, name, tag, regexp or nameprefix value)
  • namespace – the namespace of the subscription
Returns:

subscription string

MoinMoin.user.create_user(username, password, email, validate=True, is_encrypted=False, verify_email=False, **meta)[source]

Create a new user

Parameters:
  • username – unique user name
  • password – user’s password - see also is_encrypted param
  • email – unique email address
  • validate – if True (default) will validate username, password, email and the uniqueness of the user created
  • is_encrypted – if False (default) defines that the password is in plaintext, when True - password was already encrypted
  • meta – a dictionary of key-value pairs that represent user metadata and will be stored into user profile metadata
Verify_email:

if True email is saved in user.profile[EMAIL_UNVALIDATED], else email is saved in user.profile[EMAIL]

MoinMoin.user.get_editor(userid, addr, hostname)[source]

Return a tuple of type id and string or Page object representing the user that did the edit.

The type id is one of ‘ip’ (DNS or numeric IP), ‘email’ (email addr), ‘interwiki’ (Interwiki homepage) or ‘anon’ (‘’).

MoinMoin.user.get_user_backend()[source]
MoinMoin.user.isValidName(name)[source]

Validate user name

Parameters:name – user name, unicode
MoinMoin.user.normalizeName(name)[source]

Make normalized user name

Prevent impersonating another user with names containing leading, trailing or multiple whitespace, or using invisible unicode characters.

Prevent creating user page as sub page, because ‘/’ is not allowed in user names.

Prevent using ‘:’ and ‘,’ which are reserved by acl.

Parameters:name – user name, unicode
Return type:unicode
Returns:user name that can be used in acl lines
MoinMoin.user.search_users(**q)[source]

Searches for a users with given query keys/values

MoinMoin.user.update_user_query(**q)[source]

MoinMoin.wikiutil module

MoinMoin - Wiki Utility Functions

MoinMoin.wikiutil.AbsItemName(context, itemname)[source]

Return the absolute item name for a (possibly) relative item name.

Parameters:
  • context – name of the item where “itemname” appears on
  • itemname – the (possibly relative) item name
Return type:

unicode

Returns:

the absolute item name

MoinMoin.wikiutil.ParentItemName(itemname)[source]

Return the parent item name.

Parameters:itemname – the absolute item name (unicode)
Return type:unicode
Returns:the parent item name (or empty string for toplevel items)
MoinMoin.wikiutil.RelItemName(context, itemname)[source]

Return the relative item name for some context.

Parameters:
  • context – name of the item where “itemname” appears on
  • itemname – the absolute item name
Return type:

unicode

Returns:

the relative item name

MoinMoin.wikiutil.anchor_name_from_text(text)[source]

Generate an anchor name from the given text. This function generates valid HTML IDs matching: [A-Za-z][A-Za-z0-9:_.-]*

Note: this transformation has a special feature: when you feed it with a valid ID/name, it will return it without modification (identity transformation).

MoinMoin.wikiutil.clean_input(text, max_len=201)[source]

Clean input: replace CR, LF, TAB by whitespace delete control chars

Parameters:text – unicode text to clean (if we get str, we decode)
Return type:unicode
Returns:cleaned text
MoinMoin.wikiutil.containsConflictMarker(text)[source]

Returns true if there is a conflict marker in the text.

MoinMoin.wikiutil.drawing2fname(drawing)[source]
MoinMoin.wikiutil.file_headers(filename=None, content_type=None, content_length=None)[source]

Compute http headers for sending a file

Parameters:
  • filename – filename for autodetecting content_type (unicode, default: None)
  • content_type – content-type header value (str, default: autodetect from filename)
  • content_length – for content-length header (int, default:None)
MoinMoin.wikiutil.getUnicodeIndexGroup(name)[source]

Return a group letter for name, which must be a unicode string. Currently supported: Hangul Syllables (U+AC00 - U+D7AF)

Parameters:name – a string
Return type:string
Returns:group letter or None
MoinMoin.wikiutil.get_hostname(addr)[source]

Looks up the DNS hostname for some IP address.

Parameters:addr – IP address to look up (str)
Returns:host dns name (unicode) or None (if lookup is disallowed or failed)
MoinMoin.wikiutil.isGroupItem(itemname)[source]

Is this a name of group item?

Parameters:itemname – the item name
Return type:bool
Returns:True if item is a group item
MoinMoin.wikiutil.is_URL(arg, schemes=['http', 'https', 'ftp', 'file', 'mailto', 'nntp', 'news', 'ssh', 'telnet', 'irc', 'ircs', 'xmpp', 'mumble', 'webcal', 'ed2k', 'apt', 'rootz', 'gopher', 'notes', 'rtp', 'rtsp', 'rtcp'])[source]

Return True if arg is a URL (with a scheme given in the schemes list).

Note: there are not that many requirements for generic URLs, basically the only mandatory requirement is the ‘:’ between scheme and rest. Scheme itself could be anything, also the rest (but we only support some schemes, as given in URI_SCHEMES, so it is a bit less ambiguous).

MoinMoin.wikiutil.normalize_pagename(name, cfg)[source]

Normalize page name

Prevent creating page names with invisible characters or funny whitespace that might confuse the users or abuse the wiki, or just does not make sense.

Restrict even more group pages, so they can be used inside acl lines.

Parameters:name – page name, unicode
Return type:unicode
Returns:decoded and sanitized page name
MoinMoin.wikiutil.split_anchor(pagename)[source]

Split a pagename that (optionally) has an anchor into the real pagename and the anchor part. If there is no anchor, it returns an empty string for the anchor.

Note: if pagename contains a # (as part of the pagename, not as anchor),
you can use a trick to make it work nevertheless: just append a # at the end: “C##” returns (“C#”, “”) “Problem #1#” returns (“Problem #1”, “”)
TODO: We shouldn’t deal with composite pagename#anchor strings, but keep
it separate. Current approach: [[pagename#anchor|label|attr=val,&qarg=qval]] Future approach: [[pagename|label|attr=val,&qarg=qval,#anchor]] The future approach will avoid problems when there is a # in the pagename part (and no anchor). Also, we need to append #anchor at the END of the generated URL (AFTER the query string).

Module contents

MoinMoin - a wiki engine in Python.