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


Python model.DBSession类代码示例

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


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

示例1: _update_settings

    def _update_settings(self, values):
        """Modify the settings associated with the given dictionary."""
        for name, value in values.iteritems():
            if name in tmpl_context.settings:
                setting = tmpl_context.settings[name]
            else:
                setting = Setting(key=name, value=value)
            if value is None:
                value = u''
            else:
                value = unicode(value)
            if setting.value != value:
                setting.value = value
                DBSession.add(setting)
        DBSession.flush()

        # Clear the settings cache unless there are multiple processes.
        # We have no way of notifying the other processes that they need
        # to clear their caches too, so we've just gotta let it play out
        # until all the caches expire.
        if not request.environ.get('wsgi.multiprocess', False):
            app_globals.settings_cache.clear()
        else:
            # uWSGI provides an automagically included module
            # that we can use to call a graceful restart of all
            # the uwsgi processes.
            # http://projects.unbit.it/uwsgi/wiki/uWSGIReload
            try:
                import uwsgi
                uwsgi.reload()
            except ImportError:
                pass
开发者ID:JaydenChou,项目名称:mediadrop,代码行数:32,代码来源:base.py

示例2: inject_in_db

 def inject_in_db(cls, enable_player=False):
     from mediadrop.model import DBSession
     from mediadrop.model.players import players as players_table, PlayerPrefs
     
     prefs = PlayerPrefs()
     prefs.name = cls.name
     prefs.enabled = enable_player
     
     # MySQL does not allow referencing the same table in a subquery
     # (i.e. insert, max): http://stackoverflow.com/a/14302701/138526
     # Therefore we need to alias the table in max
     current_max_query = sql.select([sql.func.max(players_table.alias().c.priority)])
     # sql.func.coalesce == "set default value if func.max does "
     # In case there are no players in the database the current max is NULL. With
     # coalesce we can set a default value.
     new_priority_query = sql.func.coalesce(
         current_max_query.as_scalar()+1,
         1
     )
     prefs.priority = new_priority_query
     
     prefs.created_on = datetime.now()
     prefs.modified_on = datetime.now()
     prefs.data = cls.default_data
     DBSession.add(prefs)
     DBSession.commit()
开发者ID:knyar,项目名称:mediadrop,代码行数:26,代码来源:players.py

示例3: main

def main(parser, options, args):
    app_globs = app_globals._current_obj()
    app_id = app_globals.settings['facebook_appid']
    if not app_id:
        print 'No Facebook app_id configured, exiting'
        sys.exit(3)
    
    app_secret = options.app_secret
    fb = FacebookAPI(app_id, app_secret)
    
    from mediadrop.model import DBSession, Media
    # eager loading of 'meta' to speed up later check.
    all_media = Media.query.options(joinedload('_meta')).all()
    
    print 'Checking all media for existing Facebook comments'
    progress = ProgressBar(maxval=len(all_media)).start()
    for i, media in enumerate(all_media):
        progress.update(i+1)
        if 'facebook-comment-xid' not in media.meta:
            continue
        if not fb.has_xid_comments(media):
            continue
        media.meta[u'facebook-comment-xid'] = unicode(media.id)
        DBSession.add(media)
        DBSession.commit()

    progress.finish()
开发者ID:JaydenChou,项目名称:mediadrop,代码行数:27,代码来源:upgrade_from_v09_preserve_facebook_xid_comments.py

示例4: create_new_user

def create_new_user(username, config):
    from mediadrop.model import DBSession, User, fetch_row, Group

    user = User.by_user_name(username)

    if user is None:
        try:
            print "MIDDLEWARE"
            print config
            l = ldap.initialize(config['ldap_url'])        
            l.simple_bind_s(config['ldap_binddn'], config['ldap_pw'])
            filter = '(samaccountname=%s)' % username
            r = l.search_s(config['ldap_base'],ldap.SCOPE_SUBTREE, filter, ['displayname', 'mail'])
            l.unbind_s()

            user_attrs = {}
            for dn, entry in r:
                for attr, v in entry.iteritems():
                    user_attrs[attr] = v[0]
        except ldap.LDAPError:
            l.unbind_s()

        new_user = fetch_row(User, "new")
        new_user.display_name = user_attrs['displayName']
        new_user.email_address = user_attrs['mail']
        new_user.user_name = username
        query = DBSession.query(Group).filter(Group.group_name.in_(['authenticated']))
        new_user.groups = list(query.all())

        DBSession.add(new_user)
        DBSession.commit()
开发者ID:mkrysiak,项目名称:mediadrop,代码行数:31,代码来源:middleware.py

示例5: add_external_file

 def add_external_file(self, media, url=u"http://site.example/videos.mp4"):
     previous_files = len(media.files)
     media_file = add_new_media_file(media, url=url)
     # add_new_media_file will set media_file.media AND media.files.append
     # so we have two files for the media until the session is refreshed.
     DBSession.refresh(media)
     assert_length(previous_files + 1, media.files)
     return media_file
开发者ID:hotbaby,项目名称:mediadrop,代码行数:8,代码来源:media_test.py

示例6: _create_user_without_groups

 def _create_user_without_groups(self):
     user = User()
     user.user_name = u"joe"
     user.email_address = u"[email protected]"
     user.display_name = u"Joe"
     user.groups = []
     DBSession.add(user)
     DBSession.flush()
     return user
开发者ID:njZhuMin,项目名称:mediacore-community,代码行数:9,代码来源:filtering_restricted_items_test.py

示例7: test_can_restrict_query_if_user_does_not_have_the_required_permission

 def test_can_restrict_query_if_user_does_not_have_the_required_permission(self):
     query = Media.query
     permission = u'view'
     perm = self.perm()
     view_permission = DBSession.query(Permission).filter(Permission.permission_name == permission).one()
     view_permission.groups = []
     DBSession.flush()
     
     assert_none(self.policy.access_condition_for_query(query, permission, perm))
开发者ID:SmallsLIVE,项目名称:mediadrop,代码行数:9,代码来源:group_based_permissions_policy_test.py

示例8: view

    def view(self, slug, podcast_slug=None, **kwargs):
        """Display the media player, info and comments.

        :param slug: The :attr:`~mediadrop.models.media.Media.slug` to lookup
        :param podcast_slug: The :attr:`~mediadrop.models.podcasts.Podcast.slug`
            for podcast this media belongs to. Although not necessary for
            looking up the media, it tells us that the podcast slug was
            specified in the URL and therefore we reached this action by the
            preferred route.
        :rtype dict:
        :returns:
            media
                The :class:`~mediadrop.model.media.Media` instance for display.
            related_media
                A list of :class:`~mediadrop.model.media.Media` instances that
                rank as topically related to the given media item.
            comments
                A list of :class:`~mediadrop.model.comments.Comment` instances
                associated with the selected media item.
            comment_form_action
                ``str`` comment form action
            comment_form_values
                ``dict`` form values
            next_episode
                The next episode in the podcast series, if this media belongs to
                a podcast, another :class:`~mediadrop.model.media.Media`
                instance.

        """
        media = fetch_row(Media, slug=slug)
        request.perm.assert_permission(u'view', media.resource)

        if media.podcast_id is not None:
            # Always view podcast media from a URL that shows the context of the podcast
            if url_for() != url_for(podcast_slug=media.podcast.slug):
                redirect(podcast_slug=media.podcast.slug)

        try:
            media.increment_views()
            DBSession.commit()
        except OperationalError:
            DBSession.rollback()

        if request.settings['comments_engine'] == 'facebook':
            response.facebook = Facebook(request.settings['facebook_appid'])

        related_media = viewable_media(Media.query.related(media))[:6]
        # TODO: finish implementation of different 'likes' buttons
        #       e.g. the default one, plus a setting to use facebook.
        return dict(
            media = media,
            related_media = related_media,
            comments = media.comments.published().all(),
            comment_form_action = url_for(action='comment'),
            comment_form_values = kwargs,
        )
开发者ID:FelixSchwarz,项目名称:mediadrop-test-renames,代码行数:56,代码来源:media.py

示例9: _create_user_with_admin_permission_only

 def _create_user_with_admin_permission_only(self):
     admin_perm = DBSession.query(Permission).filter(Permission.permission_name == u'admin').one()
     second_admin_group = Group.example(name=u'Second admin group')
     admin_perm.groups.append(second_admin_group)
     admin = User.example(groups=[second_admin_group])
     DBSession.commit()
     perm = MediaDropPermissionSystem.permissions_for_user(admin, config)
     assert_true(perm.contains_permission(u'admin'))
     assert_false(perm.contains_permission(u'edit'))
     return admin
开发者ID:knyar,项目名称:mediadrop,代码行数:10,代码来源:login_test.py

示例10: delete

    def delete(self, id, **kwargs):
        """Delete a StorageEngine.

        :param id: Storage ID.
        :type id: ``int``
        :returns: Redirect back to :meth:`index` after successful delete.
        """
        engine = fetch_row(StorageEngine, id)
        files = engine.files
        for f in files:
            engine.delete(f.unique_id)
        DBSession.delete(engine)
        redirect(action='index', id=None)
开发者ID:GitReadysoft,项目名称:mediadrop,代码行数:13,代码来源:storage.py

示例11: test_can_fake_logged_in_user

    def test_can_fake_logged_in_user(self):
        admin = DBSession.query(User).filter(User.user_name == u"admin").one()
        assert_true(admin.has_permission(u"admin"))
        self.init_fake_request()
        self.set_authenticated_user(admin)

        assert_true(has_permission(u"admin"))
开发者ID:micheg,项目名称:mediadrop,代码行数:7,代码来源:request_mixin_test.py

示例12: save

    def save(self, id, **kwargs):
        player = fetch_row(PlayerPrefs, id)
        form = player.settings_form

        if id == 'new':
            DBSession.add(player)

        @validate(form, error_handler=self.edit)
        def save(id, **kwargs):
            # Allow the form to modify the player directly
            # since each can have radically different fields.
            save_func = getattr(form, 'save_data')
            save_func(player, **tmpl_context.form_values)
            redirect(controller='/admin/players', action='index')

        return save(id, **kwargs)
开发者ID:FelixSchwarz,项目名称:mediadrop-test-renames,代码行数:16,代码来源:players.py

示例13: index

    def index(self, page=1, **kwargs):
        """List storage engines with pagination.

        :rtype: Dict
        :returns:
            engines
                The list of :class:`~mediadrop.lib.storage.StorageEngine`
                instances for this page.

        """
        engines = DBSession.query(StorageEngine)\
            .options(orm.undefer('file_count'),
                     orm.undefer('file_size_sum'))\
            .all()
        engines = list(sort_engines(engines))
        existing_types = set(ecls.engine_type for ecls in engines)
        addable_engines = [
            ecls
            for ecls in StorageEngine
            if not ecls.is_singleton or ecls.engine_type not in existing_types
        ]

        return {
            'engines': engines,
            'addable_engines': addable_engines,
        }
开发者ID:GitReadysoft,项目名称:mediadrop,代码行数:26,代码来源:storage.py

示例14: permissions_for_request

 def permissions_for_request(cls, environ, config):
     identity = environ.get('repoze.who.identity', {})
     user_id = identity.get('repoze.who.userid')
     user = None
     if user_id is not None:
         user = DBSession.query(User).filter(User.id==user_id).first()
     return cls.permissions_for_user(user, config)
开发者ID:FelixSchwarz,项目名称:mediadrop-test-renames,代码行数:7,代码来源:permission_system.py

示例15: delete

    def delete(self, id, **kwargs):
        """Delete a PlayerPref.

        After deleting the PlayerPref, cleans up the players table,
        ensuring that each Player class is represented--if the deleted
        PlayerPref is the last example of that Player class, creates a new
        disabled PlayerPref for that Player class with the default settings.

        :param id: Player ID.
        :type id: ``int``
        :returns: Redirect back to :meth:`index` after successful delete.
        """
        player = fetch_row(PlayerPrefs, id)
        DBSession.delete(player)
        DBSession.flush()
        cleanup_players_table()
        redirect(action='index', id=None)
开发者ID:FelixSchwarz,项目名称:mediadrop-test-renames,代码行数:17,代码来源:players.py


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