Commits

Thomas Waldmann committed 10e20c8

replace literal strings by constants from constants.keys

Comments (0)

Files changed (13)

MoinMoin/apps/frontend/views.py

     with flaskg.storage.indexer.ix[LATEST_REVS].searcher() as searcher:
         # The search process should be as fast as possible so use
         # the indexer low-level documents instead of high-level Revisions.
-        doc = searcher.document(name_exact=item_name)
+        doc = searcher.document(**{NAME_EXACT: item_name})
         if not doc:
             return set()
         transcluded_names = set(doc[ITEMTRANSCLUSIONS])
                         if set(form['name'].value) != set(flaskg.user.name):
                             new_names = set(form['name'].value) - set(flaskg.user.name)
                             for name in new_names:
-                                if user.search_users(name_exact=name):
+                                if user.search_users(**{NAME_EXACT: name}):
                                     # duplicate name
                                     response['flash'].append((_("The username %(name)r is already in use.", name=name),
                                                               "error"))
                                     success = False
                     if part == 'notification':
                         if (form['email'].value != flaskg.user.email and
-                            user.search_users(email=form['email'].value) and app.cfg.user_email_unique):
+                            user.search_users(**{EMAIL: form['email'].value}) and app.cfg.user_email_unique):
                             # duplicate email
                             response['flash'].append((_('This email is already in use'), 'error'))
                             success = False

MoinMoin/config/default.py

 from MoinMoin.i18n import _, L_, N_
 from MoinMoin import error
 from MoinMoin.constants.rights import ACL_RIGHTS_CONTENTS, ACL_RIGHTS_FUNCTIONS
+from MoinMoin.constants.keys import *
 from MoinMoin import datastruct
 from MoinMoin.auth import MoinAuth
 from MoinMoin.util import plugins
 
         plugins._loadPluginModule(self)
 
-        if self.user_defaults['timezone'] is None:
-            self.user_defaults['timezone'] = self.timezone_default
-        if self.user_defaults['theme_name'] is None:
-            self.user_defaults['theme_name'] = self.theme_default
+        if self.user_defaults[TIMEZONE] is None:
+            self.user_defaults[TIMEZONE] = self.timezone_default
+        if self.user_defaults[THEME_NAME] is None:
+            self.user_defaults[THEME_NAME] = self.theme_default
         # Note: do not assign user_defaults['locale'] = locale_default
         # to give browser language detection a chance.
         try:
   # ==========================================================================
   'user': ('User Preferences', None, (
     ('user_defaults',
-      dict(
-        name=[],
-        display_name=None,
-        email=None,
-        openid=None,
-        css_url=None,
-        mailto_author=False,
-        edit_on_doubleclick=True,
-        scroll_page_after_edit=True,
-        show_comments=False,
-        want_trivial=False,
-        enc_password=u'',  # empty value == invalid hash
-        disabled=False,
-        bookmarks={},
-        quicklinks=[],
-        subscribed_items=[],
-        email_subscribed_events=[
+     {
+        NAME: [],
+        DISPLAY_NAME: None,
+        EMAIL: None,
+        OPENID: None,
+        CSS_URL: None,
+        MAILTO_AUTHOR: False,
+        EDIT_ON_DOUBLECLICK: True,
+        SCROLL_PAGE_AFTER_EDIT: True,
+        SHOW_COMMENTS: False,
+        WANT_TRIVIAL: False,
+        ENC_PASSWORD: u'',  # empty value == invalid hash
+        DISABLED: False,
+        BOOKMARKS: {},
+        QUICKLINKS: [],
+        SUBSCRIBED_ITEMS: [],
+        EMAIL_SUBSCRIBED_EVENTS: [
             # XXX PageChangedEvent.__name__
             # XXX PageRenamedEvent.__name__
             # XXX PageDeletedEvent.__name__
             # XXX PageCopiedEvent.__name__
             # XXX PageRevertedEvent.__name__
         ],
-        theme_name=None,  # None -> use cfg.theme_default
-        edit_rows=0,
-        results_per_page=0,
-        locale=None,  # None -> do browser language detection, otherwise just use this locale
-        timezone=None,  # None -> use cfg.timezone_default
-      ),
+        THEME_NAME: None,  # None -> use cfg.theme_default
+        EDIT_ROWS: 0,
+        RESULTS_PER_PAGE: 0,
+        LOCALE: None,  # None -> do browser language detection, otherwise just use this locale
+        TIMEZONE: None,  # None -> use cfg.timezone_default
+     },
      'Default attributes of the user object'),
   )),
   # ==========================================================================

MoinMoin/constants/keys.py

 CSS_URL = "css_url"
 EDIT_ROWS = "edit_rows"
 RESULTS_PER_PAGE = "results_per_page"
+WANT_TRIVIAL = "want_trivial"
+EMAIL_SUBSCRIBED_EVENTS = "email_subscribed_events"
 DISABLED = "disabled"
 
 # in which backend is some revision stored?

MoinMoin/items/_tests/test_Content.py

 from MoinMoin._tests import become_trusted, update_item
 from MoinMoin.items import Item
 from MoinMoin.items.content import Content, ApplicationXTar, Binary, Text, Image, TransformableBitmapImage, MarkupItem
-from MoinMoin.constants.keys import CONTENTTYPE
+from MoinMoin.constants.keys import CONTENTTYPE, TAGS
 
 
 class TestContent(object):
         item_name1 = u'Template_Item1'
         item1 = Item.create(item_name1)
         contenttype1 = u'text/plain'
-        meta = {CONTENTTYPE: contenttype1, 'tags': ['template']}
+        meta = {CONTENTTYPE: contenttype1, TAGS: ['template']}
         item1._save(meta)
         item1 = Item.create(item_name1)
 
         item_name2 = u'Template_Item2'
         item2 = Item.create(item_name2)
         contenttype1 = u'text/plain'
-        meta = {CONTENTTYPE: contenttype1, 'tags': ['template']}
+        meta = {CONTENTTYPE: contenttype1, TAGS: ['template']}
         item2._save(meta)
         item2 = Item.create(item_name2)
 
         item_name3 = u'Template_Item3'
         item3 = Item.create(item_name3)
         contenttype2 = u'image/png'
-        meta = {CONTENTTYPE: contenttype2, 'tags': ['template']}
+        meta = {CONTENTTYPE: contenttype2, TAGS: ['template']}
         item3._save(meta)
         item3 = Item.create(item_name3)
         # two items of same content type

MoinMoin/items/_tests/test_Item.py

 
 from MoinMoin._tests import become_trusted, update_item
 from MoinMoin.items import Item, NonExistent, IndexEntry, MixedIndexEntry
-from MoinMoin.constants.keys import ITEMTYPE, CONTENTTYPE, NAME, COMMENT
+from MoinMoin.constants.keys import ITEMTYPE, CONTENTTYPE, NAME, NAME_OLD, COMMENT, ACTION, ADDRESS
 
 
 def build_index(basename, relnames):
     def test_meta_filter(self):
         name = u'Test_item'
         contenttype = u'text/plain;charset=utf-8'
-        meta = {'test_key': 'test_val', CONTENTTYPE: contenttype, NAME: [u'test_name'], 'address': u'1.2.3.4'}
+        meta = {'test_key': 'test_val', CONTENTTYPE: contenttype, NAME: [u'test_name'], ADDRESS: u'1.2.3.4'}
         item = Item.create(name)
         result = Item.meta_filter(item, meta)
         # keys like NAME, ITEMID, REVID, DATAID are filtered
         # item and its contents before renaming
         item = Item.create(name)
         assert item.name == u'Test_Item'
-        assert item.meta['comment'] == u'saved it'
+        assert item.meta[COMMENT] == u'saved it'
         new_name = u'Test_new_Item'
         item.rename(new_name, comment=u'renamed')
         # item at original name and its contents after renaming
         # item at new name and its contents after renaming
         item = Item.create(new_name)
         assert item.name == u'Test_new_Item'
-        assert item.meta['name_old'] == [u'Test_Item']
-        assert item.meta['comment'] == u'renamed'
+        assert item.meta[NAME_OLD] == [u'Test_Item']
+        assert item.meta[COMMENT] == u'renamed'
         assert item.content.data == u'test_data'
 
     def test_rename_acts_only_in_active_name_in_case_there_are_several_names(self):
         # item at new name and its contents after renaming
         item = Item.create(u'Renamed_Page')
         assert item.name == u'Renamed_Page'
-        assert item.meta['name_old'] == [u'Page']
-        assert item.meta['comment'] == u'renamed'
+        assert item.meta[NAME_OLD] == [u'Page']
+        assert item.meta[COMMENT] == u'renamed'
         assert item.content.data == u'Page 1'
 
         item = Item.create(u'Renamed_Page/Child')
         assert item.name == u'Renamed_Page/Child'
-        assert item.meta['name_old'] == [u'Page/Child']
-        assert item.meta['comment'] == u'renamed'
+        assert item.meta[NAME_OLD] == [u'Page/Child']
+        assert item.meta[COMMENT] == u'renamed'
         assert item.content.data == u'this is child'
 
         item = Item.create(u'Renamed_Page/Child/Another')
         assert item.name == u'Renamed_Page/Child/Another'
-        assert item.meta['name_old'] == [u'Page/Child/Another']
-        assert item.meta['comment'] == u'renamed'
+        assert item.meta[NAME_OLD] == [u'Page/Child/Another']
+        assert item.meta[COMMENT] == u'renamed'
         assert item.content.data == u'another child'
 
     def test_rename_recursion_with_multiple_names_and_children(self):
         # item and its contents before deleting
         item = Item.create(name)
         assert item.name == u'Test_Item2'
-        assert item.meta['comment'] == u'saved it'
+        assert item.meta[COMMENT] == u'saved it'
         item.delete(u'deleted')
         # item and its contents after deletion
         item = Item.create(name)
         item = Item.create(name)
         item.revert(u'revert')
         item = Item.create(name)
-        assert item.meta['action'] == u'REVERT'
+        assert item.meta[ACTION] == u'REVERT'
 
     def test_modify(self):
         name = u'Test_Item'

MoinMoin/script/migration/moin19/import19.py

 from ._utils19 import quoteWikinameFS, unquoteWikiname, split_body
 from ._logfile19 import LogFile
 
-from MoinMoin.constants.keys import (ACL, CONTENTTYPE, NAME, NAME_OLD, REVERTED_TO, ACTION, ADDRESS, HOSTNAME,
-                                     USERID, MTIME, EXTRA, COMMENT, TAGS, SIZE, HASH_ALGORITHM, ITEMID, REVID)
+from MoinMoin.constants.keys import *
 from MoinMoin.constants.contenttypes import CONTENTTYPE_USER
 
 UID_OLD = 'old_user_id'  # dynamic field *_id, so we don't have to change schema
     def _process_usermeta(self, metadata):
         # stuff we want to have stored as boolean:
         bool_defaults = [  # taken from cfg.checkbox_defaults
-            ('show_comments', 'False'),
-            ('edit_on_doubleclick', 'True'),
-            ('scroll_page_after_edit', 'True'),
-            ('want_trivial', 'False'),
-            ('mailto_author', 'False'),
-            ('disabled', 'False'),
+            (SHOW_COMMENTS, 'False'),
+            (EDIT_ON_DOUBLECLICK, 'True'),
+            (SCROLL_PAGE_AFTER_EDIT, 'True'),
+            (WANT_TRIVIAL, 'False'),
+            (MAILTO_AUTHOR, 'False'),
+            (DISABLED, 'False'),
         ]
         for key, default in bool_defaults:
             metadata[key] = metadata.get(key, default) in ['True', 'true', '1']
 
         # stuff we want to have stored as integer:
         int_defaults = [
-            ('edit_rows', '0'),
+            (EDIT_ROWS, '0'),
         ]
         for key, default in int_defaults:
             metadata[key] = int(metadata.get(key, default))
         metadata[MTIME] = int(float(metadata.get('last_saved', '0')))
 
         # rename aliasname to display_name:
-        metadata['display_name'] = metadata.get('aliasname')
+        metadata[DISPLAY_NAME] = metadata.get('aliasname')
 
         # rename subscribed_pages to subscribed_items
-        metadata['subscribed_items'] = metadata.get('subscribed_pages', [])
+        metadata[SUBSCRIBED_ITEMS] = metadata.get('subscribed_pages', [])
 
         # convert bookmarks from usecs (and str) to secs (int)
-        metadata['bookmarks'] = [(interwiki, int(long(bookmark) / 1000000))
-                                 for interwiki, bookmark in metadata.get('bookmarks', {}).items()]
+        metadata[BOOKMARKS] = [(interwiki, int(long(bookmark) / 1000000))
+                               for interwiki, bookmark in metadata.get('bookmarks', {}).items()]
 
         # stuff we want to get rid of:
         kill = ['aliasname',  # renamed to display_name
 
         # finally, remove some empty values (that have empty defaults anyway or
         # make no sense when empty):
-        empty_kill = ['aliasname', 'display_name', 'bookmarks', 'enc_password',
-                      'language', 'css_url', 'email', ]  # XXX check subscribed_items, quicklinks
+        empty_kill = ['aliasname', DISPLAY_NAME, BOOKMARKS, ENC_PASSWORD,
+                      'language', CSS_URL, EMAIL, ]  # XXX check subscribed_items, quicklinks
         for key in empty_kill:
             if key in metadata and metadata[key] in [u'', tuple(), {}, [], ]:
                 del metadata[key]
 
         # moin2 only supports passlib generated hashes, drop everything else
         # (users need to do pw recovery in case they are affected)
-        pw = metadata.get('enc_password')
+        pw = metadata.get(ENC_PASSWORD)
         if pw is not None:
             if pw.startswith('{PASSLIB}'):
                 # take it, but strip the prefix as moin2 does not use that any more
-                metadata['enc_password'] = pw[len('{PASSLIB}'):]
+                metadata[ENC_PASSWORD] = pw[len('{PASSLIB}'):]
             else:
                 # drop old, unsupported (and also more or less unsafe) hashing scheme
-                del metadata['enc_password']
+                del metadata[ENC_PASSWORD]
 
         # TODO quicklinks and subscribed_items - check for non-interwiki elements and convert them to interwiki
 

MoinMoin/security/__init__.py

 from flask import abort
 
 from MoinMoin.constants import rights
+from MoinMoin.constants.keys import NAME_EXACT
 from MoinMoin import user
 from MoinMoin.i18n import _, L_, N_
 from MoinMoin.util.pysupport import AutoNe
             that means that there is a valid user account present.
             works for subscription emails.
         """
-        if user.search_users(name_exact=name):  # is a user with this name known?
+        if user.search_users(**{NAME_EXACT: name}):  # is a user with this name known?
             return rightsdict.get(dowhat)
         return None
 

MoinMoin/storage/middleware/_tests/test_serialization.py

 from ..routing import Backend as RoutingBackend
 from ..serialization import serialize, deserialize
 
+from MoinMoin.constants.keys import NAME, CONTENTTYPE
+
 from MoinMoin.storage.backends.stores import MutableBackend
 from MoinMoin.storage.stores.memory import BytesStore, FileStore
 
 
 contents = [
-    (u'Foo', {'name': [u'Foo', ], 'contenttype': u'text/plain'}, ''),
-    (u'Foo', {'name': [u'Foo', ], 'contenttype': u'text/plain'}, '2nd'),
-    (u'Subdir', {'name': [u'Subdir', ], 'contenttype': u'text/plain'}, ''),
-    (u'Subdir/Foo', {'name': [u'Subdir/Foo', ], 'contenttype': u'text/plain'}, ''),
-    (u'Subdir/Bar', {'name': [u'Subdir/Bar', ], 'contenttype': u'text/plain'}, ''),
+    (u'Foo', {NAME: [u'Foo', ], CONTENTTYPE: u'text/plain'}, ''),
+    (u'Foo', {NAME: [u'Foo', ], CONTENTTYPE: u'text/plain'}, '2nd'),
+    (u'Subdir', {NAME: [u'Subdir', ], CONTENTTYPE: u'text/plain'}, ''),
+    (u'Subdir/Foo', {NAME: [u'Subdir/Foo', ], CONTENTTYPE: u'text/plain'}, ''),
+    (u'Subdir/Bar', {NAME: [u'Subdir/Bar', ], CONTENTTYPE: u'text/plain'}, ''),
 ]
 
 
 def test_serialize_deserialize(source, target):
     i = 0
     for name, meta, data in contents:
-        item = source[u'name']
+        item = source[name]
         item.store_revision(dict(meta, mtime=i), StringIO(data))
         i += 1
 

MoinMoin/storage/middleware/indexing.py

         """
         Return item with <name> (may be a new or existing item).
         """
-        return Item(self, name_exact=name)
+        return Item(self, **{NAME_EXACT: name})
 
     def get_item(self, **query):
         """
         """
         self.indexer = indexer
         self.backend = self.indexer.backend
-        self._name = query.get('name_exact')
+        self._name = query.get(NAME_EXACT)
         if latest_doc is None:
             # we need to call the method without acl check to avoid endless recursion:
             latest_doc = self.indexer._document(**query)
         """
         parent_ids = set()
         for parent_name in self.parentnames:
-            rev = self.indexer._document(idx_name=LATEST_REVS, name_exact=parent_name)
+            rev = self.indexer._document(idx_name=LATEST_REVS, **{NAME_EXACT: parent_name})
             if rev:
                 parent_ids.add(rev[ITEMID])
         return parent_ids

MoinMoin/storage/middleware/protecting.py

 from whoosh.util import lru_cache
 
 from MoinMoin.constants.rights import (CREATE, READ, PUBREAD, WRITE, DESTROY, ACL_RIGHTS_CONTENTS)
-from MoinMoin.constants.keys import ALL_REVS, LATEST_REVS
+from MoinMoin.constants.keys import ALL_REVS, LATEST_REVS, NAME_EXACT, ITEMID
 
 from MoinMoin.security import AccessControlList
 
         """
 
         if itemid is not None:
-            item = self.get_item(itemid=itemid)
+            q = {ITEMID: itemid}
         elif fqname is not None:
             # itemid might be None for new, not yet stored items,
             # but we have fqname then
-            item = self.get_item(name_exact=fqname)
+            q = {NAME_EXACT: fqname}
         else:
             raise ValueError("need itemid or fqname")
+        item = self.get_item(**q)
         acl = item.acl
         fqname = item.fqname
         if acl is not None:

MoinMoin/storage/middleware/serialization.py

 
 4 bytes length of meta (m)
 m bytes metadata (json serialization, utf-8 encoded)
-        (the metadata contains the data length d in meta['size'])
+        (the metadata contains the data length d in meta[SIZE])
 d bytes binary data
 ... (repeat for all meta/data)
 4 bytes 00 (== length of next meta -> there is none, this is the end)
 
 from werkzeug.wsgi import LimitedStream
 
+from MoinMoin.constants.keys import NAME, ITEMTYPE, SIZE
+
 
 def serialize(backend, dst):
     dst.writelines(serialize_iter(backend))
         meta_str = src.read(meta_size)
         text = meta_str.decode('utf-8')
         meta = json.loads(text)
-        name = meta.get('name')
+        name = meta.get(NAME)
         if isinstance(name, unicode):
             # if we encounter single names, make a list of names:
-            meta['name'] = [name, ]
-        if 'itemtype' not in meta:
+            meta[NAME] = [name, ]
+        if ITEMTYPE not in meta:
             # temporary hack to upgrade serialized item files:
-            meta['itemtype'] = u'default'
-        data_size = meta[u'size']
+            meta[ITEMTYPE] = u'default'
+        data_size = meta[SIZE]
         curr_pos = src.tell()
         limited = LimitedStream(src, data_size)
         backend.store(meta, limited)

MoinMoin/storage/middleware/validation.py

 
 UserMetaSchema = DuckDict.named('UserMetaSchema').of(
     String.named(keys.CONTENTTYPE).validated_by(user_contenttype_validator),
-    String.named('email').using(optional=True),
-    String.named('openid').using(optional=True),
-    String.named('enc_password').using(optional=True),
-    String.named('recoverpass_key').using(optional=True),
-    String.named('theme_name').using(optional=True),
-    String.named('timezone').using(optional=True),
-    String.named('locale').using(optional=True),
-    String.named('css_url').using(optional=True),
-    Integer.named('results_per_page').using(optional=True),
-    Integer.named('edit_rows').using(optional=True),
-    Boolean.named('disabled').using(optional=True),
-    Boolean.named('want_trivial').using(optional=True),
-    Boolean.named('show_comments').using(optional=True),
-    Boolean.named('edit_on_doubleclick').using(optional=True),
-    Boolean.named('scroll_page_after_edit').using(optional=True),
-    Boolean.named('mailto_author').using(optional=True),
-    List.named('quicklinks').of(String.named('quicklinks')).using(optional=True),
-    List.named('subscribed_items').of(String.named('subscribed_item')).using(optional=True),
-    List.named('email_subscribed_events').of(String.named('email_subscribed_event')).using(optional=True),
+    String.named(keys.EMAIL).using(optional=True),
+    String.named(keys.OPENID).using(optional=True),
+    String.named(keys.ENC_PASSWORD).using(optional=True),
+    String.named(keys.RECOVERPASS_KEY).using(optional=True),
+    String.named(keys.THEME_NAME).using(optional=True),
+    String.named(keys.TIMEZONE).using(optional=True),
+    String.named(keys.LOCALE).using(optional=True),
+    String.named(keys.CSS_URL).using(optional=True),
+    Integer.named(keys.RESULTS_PER_PAGE).using(optional=True),
+    Integer.named(keys.EDIT_ROWS).using(optional=True),
+    Boolean.named(keys.DISABLED).using(optional=True),
+    Boolean.named(keys.WANT_TRIVIAL).using(optional=True),
+    Boolean.named(keys.SHOW_COMMENTS).using(optional=True),
+    Boolean.named(keys.EDIT_ON_DOUBLECLICK).using(optional=True),
+    Boolean.named(keys.SCROLL_PAGE_AFTER_EDIT).using(optional=True),
+    Boolean.named(keys.MAILTO_AUTHOR).using(optional=True),
+    List.named(keys.QUICKLINKS).of(String.named('quicklinks')).using(optional=True),
+    List.named(keys.SUBSCRIBED_ITEMS).of(String.named('subscribed_item')).using(optional=True),
+    List.named(keys.EMAIL_SUBSCRIBED_EVENTS).of(String.named('email_subscribed_event')).using(optional=True),
     #TODO: DuckDict.named('bookmarks').using(optional=True),
     *common_meta
 )
 space between words. Group page name is not allowed.""", name=username)
 
     # Name required to be unique. Check if name belong to another user.
-    if validate and search_users(name_exact=username):
+    if validate and search_users(**{NAME_EXACT: username}):
         return _("This user name already belongs to somebody else.")
 
     # XXX currently we just support creating with 1 name:
     """ Searches for a users with given query keys/values """
     # Since item name is a list, it's possible a list have been passed as parameter.
     # No problem, since user always have just one name (TODO: validate single name for user)
-    if q.get('name_exact') and isinstance(q.get('name_exact'), list):
-        q['name_exact'] = q['name_exact'][0]
+    if q.get(NAME_EXACT) and isinstance(q.get(NAME_EXACT), list):
+        q[NAME_EXACT] = q[NAME_EXACT][0]
     q = update_user_query(**q)
     backend = get_user_backend()
     docs = backend.documents(**q)
 
         itemid = uid
         if not itemid and auth_username:
-            users = search_users(name_exact=auth_username)
+            users = search_users(**{NAME_EXACT: auth_username})
             if users:
                 itemid = users[0].meta[ITEMID]
         if not itemid and _name and _name != 'anonymous':
-            users = search_users(name_exact=_name)
+            users = search_users(**{NAME_EXACT: _name})
             if users:
                 itemid = users[0].meta[ITEMID]
         if itemid: