• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python model.DBSession类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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


示例16: save

    def save(self, id, engine_type=None, **kwargs):
        if id == 'new':
            assert engine_type is not None, 'engine_type must be specified when saving a new StorageEngine.'

        engine = self.fetch_engine(id, engine_type)
        form = engine.settings_form

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

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

        return save_engine_params(id, **kwargs)
开发者ID:GitReadysoft,项目名称:mediadrop,代码行数:19,代码来源:storage.py


示例17: 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
        # didn't get direct SQL expression to work with SQLAlchemy
        # player_table = sql.func.max(player_table.c.priority)
        query = sql.select([sql.func.max(players_table.c.priority)])
        max_priority = DBSession.execute(query).first()[0]
        if max_priority is None:
            max_priority = -1
        prefs.priority = max_priority + 1
        prefs.created_on = datetime.now()
        prefs.modified_on = datetime.now()
        prefs.data = cls.default_data
        DBSession.add(prefs)
        DBSession.commit()
开发者ID:njZhuMin,项目名称:mediacore-community,代码行数:19,代码来源:players.py


示例18: _to_python

    def _to_python(self, value, state):
        id = request.environ["pylons.routes_dict"]["id"]

        query = DBSession.query(Group).filter_by(group_name=value)
        if id != "new":
            query = query.filter(Group.group_id != id)

        if query.count() != 0:
            raise Invalid(_("Group name already exists"), value, state)
        return value
开发者ID:micheg,项目名称:mediadrop,代码行数:10,代码来源:groups.py


示例19: update_enabled_players

def update_enabled_players():
    """Ensure that the encoding status of all media is up to date with the new
    set of enabled players.

    The encoding status of Media objects is dependent on there being an
    enabled player that supports that format. Call this method after changing
    the set of enabled players, to ensure encoding statuses are up to date.
    """
    from mediadrop.model import DBSession, Media
    media = DBSession.query(Media)
    for m in media:
        m.update_status()
开发者ID:knyar,项目名称:mediadrop,代码行数:12,代码来源:players.py


示例20: save_media_obj

    def save_media_obj(self, name, email, title, description, tags, uploaded_file, url):
        # create our media object as a status-less placeholder initially
        media_obj = Media()
        media_obj.author = Author(name, email)
        media_obj.title = title
        media_obj.slug = get_available_slug(Media, title)
        media_obj.description = description
        if request.settings['wording_display_administrative_notes']:
            media_obj.notes = request.settings['wording_administrative_notes']
        media_obj.set_tags(tags)

        # Give the Media object an ID.
        DBSession.add(media_obj)
        DBSession.flush()

        # Create a MediaFile object, add it to the media_obj, and store the file permanently.
        media_file = add_new_media_file(media_obj, file=uploaded_file, url=url)

        # The thumbs may have been created already by add_new_media_file
        if not has_thumbs(media_obj):
            create_default_thumbs_for(media_obj)

        media_obj.update_status()
        DBSession.flush()

        return media_obj
开发者ID:anitahitouch,项目名称:mediadrop,代码行数:26,代码来源:upload.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python model.Media类代码示例发布时间:2022-05-27
下一篇:
Python model.fetch_row函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap