当前位置: 首页>>代码示例>>Python>>正文


Python orm.state函数代码示例

本文整理汇总了Python中ming.orm.state函数的典型用法代码示例。如果您正苦于以下问题:Python state函数的具体用法?Python state怎么用?Python state使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了state函数的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: register_neighborhood_project

 def register_neighborhood_project(self, neighborhood, users, allow_register=False):
     from allura import model as M
     shortname = '--init--'
     name = 'Home Project for %s' % neighborhood.name
     p = M.Project(neighborhood_id=neighborhood._id,
                   shortname=shortname,
                   name=name,
                   short_description='',
                   description=(
                       'You can edit this description in the admin page'),
                   homepage_title = '# ' + name,
                   last_updated = datetime.utcnow(),
                   is_nbhd_project=True,
                   is_root=True)
     try:
         p.configure_project(
             users=users,
             is_user_project=False,
             apps=[
                 ('Wiki', 'wiki', 'Wiki'),
                 ('admin', 'admin', 'Admin')])
     except:
         ThreadLocalORMSession.close_all()
         log.exception('Error registering project %s' % p)
         raise
     if allow_register:
         role_auth = M.ProjectRole.authenticated(p)
         security.simple_grant(p.acl, role_auth._id, 'register')
         state(p).soil()
     return p
开发者ID:srcclrapache1,项目名称:incubator-allura,代码行数:30,代码来源:plugin.py

示例2: commit

 def commit(self, update_stats=True):
     '''Save off a snapshot of the artifact and increment the version #'''
     self.version += 1
     try:
         ip_address = request.headers.get('X_FORWARDED_FOR', request.remote_addr)
         ip_address = ip_address.split(',')[0].strip()
     except:
         ip_address = '0.0.0.0'
     data = dict(
         artifact_id=self._id,
         artifact_class='%s.%s' % (
             self.__class__.__module__,
             self.__class__.__name__),
         version=self.version,
         author=dict(
             id=c.user._id,
             username=c.user.username,
             display_name=c.user.get_pref('display_name'),
             logged_ip=ip_address),
         timestamp=datetime.utcnow(),
         data=state(self).clone())
     ss = self.__mongometa__.history_class(**data)
     session(ss).insert_now(ss, state(ss))
     log.info('Snapshot version %s of %s',
              self.version, self.__class__)
     if update_stats:
         if self.version > 1:
             g.statsUpdater.modifiedArtifact(
                 self.type_s, self.mod_date, self.project, c.user)
         else :
             g.statsUpdater.newArtifact(
                 self.type_s, self.mod_date, self.project, c.user)
     return ss
开发者ID:johnsca,项目名称:incubator-allura,代码行数:33,代码来源:artifact.py

示例3: commit

 def commit(self):
     """Save off a snapshot of the artifact and increment the version #"""
     self.version += 1
     try:
         ip_address = request.headers.get("X_FORWARDED_FOR", request.remote_addr)
         ip_address = ip_address.split(",")[0].strip()
     except:
         ip_address = "0.0.0.0"
     data = dict(
         artifact_id=self._id,
         artifact_class="%s.%s" % (self.__class__.__module__, self.__class__.__name__),
         version=self.version,
         author=dict(
             id=c.user._id,
             username=c.user.username,
             display_name=c.user.get_pref("display_name"),
             logged_ip=ip_address,
         ),
         timestamp=datetime.utcnow(),
         data=state(self).clone(),
     )
     ss = self.__mongometa__.history_class(**data)
     session(ss).insert_now(ss, state(ss))
     log.info("Snapshot version %s of %s", self.version, self.__class__)
     return ss
开发者ID:pombredanne,项目名称:SourceForge-Allura,代码行数:25,代码来源:artifact.py

示例4: create_thumbnail

    def create_thumbnail(self, attachment, att_cls):
        if attachment.is_image():
            base.log.info("Processing image attachment '%s'",
                          attachment.filename)
            doc = state(attachment).document.deinstrumented_clone()
            del doc['_id']
            del doc['file_id']
            doc['type'] = 'thumbnail'
            count = att_cls.query.find(doc).count()
            if count == 1:
                base.log.info(
                    "Thumbnail already exists for '%s' - skipping", attachment.filename)
                return
            elif count > 1:
                base.log.warning(
                    "There are %d thumbnails for '%s' - consider clearing them with --force", count, attachment.filename)
                return

            image = PIL.Image.open(attachment.rfile())
            del doc['content_type']
            del doc['filename']
            att_cls.save_thumbnail(attachment.filename, image,
                                   attachment.content_type, att_cls.thumbnail_size, doc, square=True)
            base.log.info("Created thumbnail for '%s'", attachment.filename)
            self.created_thumbs += 1
开发者ID:AsylumCorp,项目名称:incubator-allura,代码行数:25,代码来源:rethumb.py

示例5: make_slug

 def make_slug(self):
     base = BlogPost.make_base_slug(self.title, self.timestamp)
     self.slug = base
     while True:
         try:
             session(self).insert_now(self, state(self))
             return self.slug
         except DuplicateKeyError:
             self.slug = base + '-%.3d' % randint(0, 999)
开发者ID:joequant,项目名称:allura,代码行数:9,代码来源:blog.py

示例6: upsert

 def upsert(cls, **kw):
     obj = cls.query.get(**kw)
     if obj is not None: return obj
     try:
         obj = cls(**kw)
         session(obj).insert_now(obj, state(obj))
     except pymongo.errors.DuplicateKeyError:
         session(obj).expunge(obj)
         obj = cls.query.get(**kw)
     return obj
开发者ID:pombredanne,项目名称:SourceForge-Allura,代码行数:10,代码来源:auth.py

示例7: commit

 def commit(self, update_stats=True):
     '''Save off a snapshot of the artifact and increment the version #'''
     try:
         ip_address = utils.ip_address(request)
     except:
         ip_address = '0.0.0.0'
     data = dict(
         artifact_id=self._id,
         artifact_class='%s.%s' % (
             self.__class__.__module__,
             self.__class__.__name__),
         author=dict(
             id=c.user._id,
             username=c.user.username,
             display_name=c.user.get_pref('display_name'),
             logged_ip=ip_address),
         data=state(self).clone())
     while True:
         self.version += 1
         data['version'] = self.version
         data['timestamp'] = datetime.utcnow()
         ss = self.__mongometa__.history_class(**data)
         try:
             session(ss).insert_now(ss, state(ss))
         except pymongo.errors.DuplicateKeyError:
             log.warning('Trying to create duplicate version %s of %s',
                         self.version, self.__class__)
             session(ss).expunge(ss)
             continue
         else:
             break
     log.debug('Snapshot version %s of %s',
               self.version, self.__class__)
     if update_stats:
         if self.version > 1:
             g.statsUpdater.modifiedArtifact(
                 self.type_s, self.mod_date, self.project, c.user)
         else:
             g.statsUpdater.newArtifact(
                 self.type_s, self.mod_date, self.project, c.user)
     return ss
开发者ID:apache,项目名称:allura,代码行数:41,代码来源:artifact.py

示例8: reply

 def reply(self):
     new_id = h.gen_message_id()
     slug, full_slug = self.make_slugs(self)
     new_args = dict(
         state(self).document,
         _id=new_id,
         slug=slug,
         full_slug=full_slug,
         parent_id=self._id,
         timestamp=datetime.utcnow(),
         author_id=c.user._id)
     return self.__class__(**new_args)
开发者ID:johnsca,项目名称:incubator-allura,代码行数:12,代码来源:artifact.py

示例9: test_create

 def test_create(self):
     doc = self.Basic()
     assert state(doc).status == 'new'
     self.session.flush()
     assert state(doc).status == 'clean'
     doc.a = 5
     assert state(doc).status == 'dirty'
     self.session.flush()
     assert state(doc).status == 'clean'
     c = doc.c
     c.e = 5
     assert state(doc).status == 'dirty', state(doc).status
     assert repr(state(doc)).startswith('<ObjectState')
开发者ID:terrasea,项目名称:ming,代码行数:13,代码来源:test_mapper.py

示例10: make_slug

 def make_slug(self):
     slugsafe = ''.join(
         ch.lower()
         for ch in self.title.replace(' ', '-')
         if ch.isalnum() or ch == '-')
     base = '%s/%s' % (
         self.timestamp.strftime('%Y/%m'),
         slugsafe)
     self.slug = base
     while True:
         try:
             session(self).insert_now(self, state(self))
             return self.slug
         except DuplicateKeyError:
             self.slug = base + '-%.3d' % randint(0,999)
             return self.slug
开发者ID:Bitergia,项目名称:AlluraBitergiaMetrics,代码行数:16,代码来源:metrics.py

示例11: set_tool_data

 def set_tool_data(self, tool, **kw):
     d = self.tool_data.setdefault(tool, {})
     d.update(kw)
     state(self).soil()
开发者ID:apache,项目名称:incubator-allura,代码行数:4,代码来源:project.py

示例12: bootstrap


#.........这里部分代码省略.........
        [Neighborhood administration](/u/admin)

        [[projects show_total=yes]]
        '''))
    set_nbhd_wiki_content(p_adobe, dedent('''
        This is the "Adobe" neighborhood.  It is just an example of having projects in a different neighborhood.

        [Neighborhood administration](/adobe/admin)

        [[projects show_total=yes]]
        '''))

    ThreadLocalORMSession.flush_all()
    ThreadLocalORMSession.close_all()

    # add the adobe icon
    file_name = 'adobe_icon.png'
    file_path = os.path.join(
        allura.__path__[0], 'public', 'nf', 'images', file_name)
    M.NeighborhoodFile.from_path(file_path, neighborhood_id=n_adobe._id)

    # Add some test users
    for unum in range(10):
        make_user('Test User %d' % unum)

    log.info('Creating basic project categories')
    cat1 = M.ProjectCategory(name='clustering', label='Clustering')

    cat2 = M.ProjectCategory(name='communications', label='Communications')
    cat2_1 = M.ProjectCategory(
        name='synchronization', label='Synchronization', parent_id=cat2._id)
    cat2_2 = M.ProjectCategory(
        name='streaming', label='Streaming', parent_id=cat2._id)
    cat2_3 = M.ProjectCategory(name='fax', label='Fax', parent_id=cat2._id)
    cat2_4 = M.ProjectCategory(name='bbs', label='BBS', parent_id=cat2._id)

    cat3 = M.ProjectCategory(name='database', label='Database')
    cat3_1 = M.ProjectCategory(
        name='front_ends', label='Front-Ends', parent_id=cat3._id)
    cat3_2 = M.ProjectCategory(
        name='engines_servers', label='Engines/Servers', parent_id=cat3._id)

    log.info('Registering "regular users" (non-root) and default projects')
    # since this runs a lot for tests, separate test and default users and
    # do the minimal needed
    if asbool(conf.get('load_test_data')):
        u_admin = make_user('Test Admin')
        u_admin.preferences = dict(email_address='[email protected]')
        u_admin.email_addresses = ['[email protected]']
        u_admin.set_password('foo')
        u_admin.claim_address('[email protected]')
    else:
        u_admin = make_user('Admin 1', username='admin1')
        # Admin1 is almost root, with admin access for Users and Projects
        # neighborhoods
        p_projects.add_user(u_admin, ['Admin'])
        p_users.add_user(u_admin, ['Admin'])

        p_allura = n_projects.register_project('allura', u_admin, 'Allura')
    u1 = make_user('Test User')
    p_adobe1 = n_adobe.register_project('adobe-1', u_admin, 'Adobe project 1')
    p_adobe.add_user(u_admin, ['Admin'])
    p0 = n_projects.register_project('test', u_admin, 'Test Project')
    p1 = n_projects.register_project('test2', u_admin, 'Test 2')
    p0._extra_tool_status = ['alpha', 'beta']

    sess = session(M.Neighborhood)  # all the sessions are the same
    for x in (n_adobe, n_projects, n_users, p_projects, p_users, p_adobe):
        # Ming doesn't detect substructural changes in newly created objects
        # (vs loaded from DB)
        state(x).status = 'dirty'
        # TODO: Hope that Ming can be improved to at least avoid stuff below
        sess.flush(x)

    ThreadLocalORMSession.flush_all()

    if asbool(conf.get('load_test_data')):
        if asbool(conf.get('cache_test_data')):
            cache_test_data()
    else:  # pragma no cover
        # regular first-time setup
        p0.add_user(u_admin, ['Admin'])
        log.info('Registering initial apps')
        with h.push_config(c, user=u_admin):
            for ep_name, app in g.entry_points['tool'].iteritems():
                if not app.installable:
                    continue
                p0.install_app(ep_name)

    # reload our p0 project so that p0.app_configs is accurate with all the
    # newly installed apps
    ThreadLocalORMSession.flush_all()
    ThreadLocalORMSession.close_all()
    p0 = M.Project.query.get(_id=p0._id)
    sub = p0.new_subproject('sub1', project_name='A Subproject')
    with h.push_config(c, user=u_admin):
        sub.install_app('wiki')

    ThreadLocalORMSession.flush_all()
    ThreadLocalORMSession.close_all()
开发者ID:AsylumCorp,项目名称:incubator-allura,代码行数:101,代码来源:bootstrap.py

示例13: bootstrap


#.........这里部分代码省略.........
        file_name = "adobe_icon.png"
        file_path = os.path.join(allura.__path__[0], "public", "nf", "images", file_name)
        M.NeighborhoodFile.from_path(file_path, neighborhood_id=n_adobe._id)

    ThreadLocalORMSession.flush_all()
    ThreadLocalORMSession.close_all()

    if create_test_data:
        # Add some test users
        for unum in range(10):
            make_user("Test User %d" % unum)

    log.info("Creating basic project categories")
    M.ProjectCategory(name="clustering", label="Clustering")
    cat2 = M.ProjectCategory(name="communications", label="Communications")
    M.ProjectCategory(name="synchronization", label="Synchronization", parent_id=cat2._id)
    M.ProjectCategory(name="streaming", label="Streaming", parent_id=cat2._id)
    M.ProjectCategory(name="fax", label="Fax", parent_id=cat2._id)
    M.ProjectCategory(name="bbs", label="BBS", parent_id=cat2._id)

    cat3 = M.ProjectCategory(name="database", label="Database")
    M.ProjectCategory(name="front_ends", label="Front-Ends", parent_id=cat3._id)
    M.ProjectCategory(name="engines_servers", label="Engines/Servers", parent_id=cat3._id)

    if create_test_data:
        log.info('Registering "regular users" (non-root) and default projects')
        # since this runs a lot for tests, separate test and default users and
        # do the minimal needed
        if asbool(conf.get("load_test_data")):
            u_admin = make_user("Test Admin")
            u_admin.preferences = dict(email_address="[email protected]")
            u_admin.email_addresses = ["[email protected]"]
            u_admin.set_password("foo")
            u_admin.claim_address("[email protected]")
            ThreadLocalORMSession.flush_all()

            admin_email = M.EmailAddress.get(email="[email protected]")
            admin_email.confirmed = True
        else:
            u_admin = make_user("Admin 1", username="admin1")
            # Admin1 is almost root, with admin access for Users and Projects
            # neighborhoods
            p_projects.add_user(u_admin, ["Admin"])
            p_users.add_user(u_admin, ["Admin"])

            n_projects.register_project("allura", u_admin, "Allura")
        make_user("Test User")
        n_adobe.register_project("adobe-1", u_admin, "Adobe project 1")
        p_adobe.add_user(u_admin, ["Admin"])
        p0 = n_projects.register_project("test", u_admin, "Test Project")
        n_projects.register_project("test2", u_admin, "Test 2")
        p0._extra_tool_status = ["alpha", "beta"]

    sess = session(M.Neighborhood)  # all the sessions are the same
    _list = (n_projects, n_users, p_projects, p_users)
    if create_test_data:
        _list += (n_adobe, p_adobe)
    for x in _list:
        # Ming doesn't detect substructural changes in newly created objects
        # (vs loaded from DB)
        state(x).status = "dirty"
        # TODO: Hope that Ming can be improved to at least avoid stuff below
        sess.flush(x)

    ThreadLocalORMSession.flush_all()

    if asbool(conf.get("load_test_data")):
        if asbool(conf.get("cache_test_data")):
            cache_test_data()
    else:  # pragma no cover
        # regular first-time setup

        create_trove_categories = CreateTroveCategoriesCommand("create_trove_categories")
        create_trove_categories.run([""])

        if create_test_data:
            p0.add_user(u_admin, ["Admin"])
            log.info("Registering initial apps")
            with h.push_config(c, user=u_admin):
                p0.install_apps(
                    [
                        {"ep_name": ep_name}
                        for ep_name, app in g.entry_points["tool"].iteritems()
                        if app._installable(tool_name=ep_name, nbhd=n_projects, project_tools=[])
                    ]
                )

    ThreadLocalORMSession.flush_all()
    ThreadLocalORMSession.close_all()

    if create_test_data:
        # reload our p0 project so that p0.app_configs is accurate with all the
        # newly installed apps
        p0 = M.Project.query.get(_id=p0._id)
        sub = p0.new_subproject("sub1", project_name="A Subproject")
        with h.push_config(c, user=u_admin):
            sub.install_app("wiki")

    ThreadLocalORMSession.flush_all()
    ThreadLocalORMSession.close_all()
开发者ID:joequant,项目名称:allura,代码行数:101,代码来源:bootstrap.py

示例14:

#       distributed with this work for additional information
#       regarding copyright ownership.  The ASF licenses this file
#       to you under the Apache License, Version 2.0 (the
#       "License"); you may not use this file except in compliance
#       with the License.  You may obtain a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#       Unless required by applicable law or agreed to in writing,
#       software distributed under the License is distributed on an
#       "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
#       KIND, either express or implied.  See the License for the
#       specific language governing permissions and limitations
#       under the License.

'''Merge all the OldProjectRole collections in into a ProjectRole collection.
'''
import logging

from ming.orm import session, state
from allura import model as M

log = logging.getLogger(__name__)

log.info('Moving project roles in database %s to main DB', M.Project.database_uri())
for opr in M.OldProjectRole.query.find():
    pr = M.ProjectRole(**state(opr).document)
session(opr).clear()
session(pr).flush()
session(pr).clear()
开发者ID:jekatgithub,项目名称:incubator-allura,代码行数:30,代码来源:003-migrate_project_roles.py


注:本文中的ming.orm.state函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。