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


Python model.DBSession类代码示例

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


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

示例1: edit

    def edit(self, id, engine_type=None, **kwargs):
        """Display the :class:`~mediacore.lib.storage.StorageEngine` for editing or adding.

        :param id: Storage ID
        :type id: ``int`` or ``"new"``
        :rtype: dict
        :returns:

        """
        if id != "new":
            engine = fetch_row(StorageEngine, id)
        else:
            types = dict((cls.engine_type, cls) for cls in StorageEngine)
            engine_cls = types.get(engine_type, None)
            if not engine_cls:
                redirect(controller="/admin/storage", action="index")
            engine = engine_cls()

            if not engine.settings_form:
                # XXX: If this newly created storage engine has no settings,
                #      just save it. This isn't RESTful (as edit is a GET
                #      action), but it simplifies the creation process.
                DBSession.add(engine)
                redirect(controller="/admin/storage", action="index")

        return {
            "engine": engine,
            "form": engine.settings_form,
            "form_action": url_for(action="save", engine_type=engine_type),
            "form_values": kwargs,
        }
开发者ID:greentv,项目名称:mediacore,代码行数:31,代码来源:storage.py

示例2: _add_new_media_file

def _add_new_media_file(media, original_filename, file):
    # FIXME: I think this will raise a KeyError if the uploaded
    #        file doesn't have an extension.
    file_ext = os.path.splitext(original_filename)[1].lower()[1:]

    # set the file paths depending on the file type
    media_file = MediaFile()
    media_file.type = file_ext
    media_file.url = 'dummy_url' # model requires that url not NULL
    media_file.is_original = True
    media_file.enable_player = media_file.is_playable
    media_file.enable_feed = not media_file.is_embeddable
    media_file.size = os.fstat(file.fileno())[6]

    # update media relations
    media.files.append(media_file)

    # add the media file (and its media, if new) to the database to get IDs
    DBSession.add(media_file)
    DBSession.flush()

    # copy the file to its permanent location
    file_name = '%d_%d_%s.%s' % (media.id, media_file.id, media.slug, file_ext)
    file_url = _store_media_file(file, file_name)
    media_file.url = file_url

    return media_file
开发者ID:SergeyLashin,项目名称:mediacore,代码行数:27,代码来源:media.py

示例3: index

    def index(self, page=1, **kwargs):
        """List podcasts and podcast media.

        Our custom paginate decorator allows us to have fewer podcast episodes
        display on the first page than on the rest with the ``items_first_page``
        param. See :class:`mediacore.lib.custompaginate.CustomPage`.

        :param page: Page number, defaults to 1.
        :type page: int
        :rtype: dict
        :returns:
            podcasts
                The :class:`~mediacore.model.podcasts.Podcast` instance
            episodes
                The list of :class:`~mediacore.model.media.Media` instances
                for this page.

        """
        episodes = (
            DBSession.query(Media)
            .filter(Media.podcast_id != None)
            .order_by(Media.publish_on.desc())
            .options(orm.undefer("comment_count_published"))
        )
        episodes = self._filter(episodes)

        podcasts = DBSession.query(Podcast).options(orm.undefer("published_media_count")).all()

        return dict(podcasts=podcasts, episodes=episodes)
开发者ID:SergeyLashin,项目名称:mediacore,代码行数:29,代码来源:podcasts.py

示例4: _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:Jpoudrier,项目名称:mediacore-community,代码行数:32,代码来源:base.py

示例5: 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 mediacore.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:BlendedLearningCollaborative,项目名称:mediacore-community,代码行数:27,代码来源:upgrade_from_v09_preserve_facebook_xid_comments.py

示例6: rate

    def rate(self, slug, rating=1, **kwargs):
        """Rate up or down the given media.

        :param slug: The media :attr:`~mediacore.model.media.Media.slug`
        :param rating: ``1`` or ``0`` if the rating is up or down.
        :rtype: JSON dict
        :returns:
            succcess
                bool
            upRating
                Pluralized count of up raters, "# people" or "1 person"
            downRating
                Pluralized count of down raters, "# people" or "1 person"

        """
        media = fetch_row(Media, slug=slug)

        if rating > 0:
            media.rating.add_vote(1)
        else:
            media.rating.add_vote(0)
        DBSession.add(media)

        if request.is_xhr:
            return dict(
                success = True,
                upRating = helpers.text.plural(media.rating.sum, 'person', 'people'),
                downRating = None,
            )
        else:
            redirect(action='view')
开发者ID:SergeyLashin,项目名称:mediacore,代码行数:31,代码来源:media.py

示例7: comment

    def comment(self, slug, **values):
        """Post a comment from :class:`~mediacore.forms.media.PostCommentForm`.

        :param slug: The media :attr:`~mediacore.model.media.Media.slug`
        :returns: Redirect to :meth:`view` page for media.

        """
        if tmpl_context.form_errors:
            if request.is_xhr:
                return dict(
                    success = False,
                    errors = tmpl_context.form_errors
                )
            else:
                redirect(action='view')

        media = fetch_row(Media, slug=slug)
        c = Comment()
        c.status = 'unreviewed'
        c.author = AuthorWithIP(values['name'], None, request.environ['REMOTE_ADDR'])
        c.subject = 'Re: %s' % media.title
        c.body = helpers.clean_xhtml(values['body'])

        media.comments.append(c)
        DBSession.add(media)
        email.send_comment_notification(media, c)

        if request.is_xhr:
            return dict(success = True)
        else:
            redirect(action='view')
开发者ID:SergeyLashin,项目名称:mediacore,代码行数:31,代码来源:media.py

示例8: comment

    def comment(self, slug, name="", email=None, body="", **kwargs):
        """Post a comment from :class:`~mediacore.forms.comments.PostCommentForm`.

        :param slug: The media :attr:`~mediacore.model.media.Media.slug`
        :returns: Redirect to :meth:`view` page for media.

        """

        def result(success, message=None, comment=None):
            if request.is_xhr:
                result = dict(success=success, message=message)
                if comment:
                    result["comment"] = render("comments/_list.html", {"comment_to_render": comment}, method="xhtml")
                return result
            elif success:
                return redirect(action="view")
            else:
                return self.view(slug, name=name, email=email, body=body, **kwargs)

        akismet_key = request.settings["akismet_key"]
        if akismet_key:
            akismet = Akismet(agent=USER_AGENT)
            akismet.key = akismet_key
            akismet.blog_url = request.settings["akismet_url"] or url_for("/", qualified=True)
            akismet.verify_key()
            data = {
                "comment_author": name.encode("utf-8"),
                "user_ip": request.environ.get("REMOTE_ADDR"),
                "user_agent": request.environ.get("HTTP_USER_AGENT", ""),
                "referrer": request.environ.get("HTTP_REFERER", "unknown"),
                "HTTP_ACCEPT": request.environ.get("HTTP_ACCEPT"),
            }

            if akismet.comment_check(body.encode("utf-8"), data):
                return result(False, _(u"Your comment has been rejected."))

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

        c = Comment()

        name = filter_vulgarity(name)
        c.author = AuthorWithIP(name, email, request.environ["REMOTE_ADDR"])
        c.subject = "Re: %s" % media.title
        c.body = filter_vulgarity(body)

        require_review = request.settings["req_comment_approval"]
        if not require_review:
            c.reviewed = True
            c.publishable = True

        media.comments.append(c)
        DBSession.flush()
        send_comment_notification(media, c)

        if require_review:
            message = _("Thank you for your comment! We will post it just as " "soon as a moderator approves it.")
            return result(True, message=message)
        else:
            return result(True, comment=c)
开发者ID:jamielkl,项目名称:mediacore-community,代码行数:60,代码来源:media.py

示例9: index

    def index(self, page=1, search=None, podcast_filter=None, **kwargs):
        """List media with pagination and filtering.

        :param page: Page number, defaults to 1.
        :type page: int
        :param search: Optional search term to filter by
        :type search: unicode or None
        :param podcast_filter: Optional podcast to filter by
        :type podcast_filter: int or None
        :rtype: dict
        :returns:
            media
                The list of :class:`~mediacore.model.media.Media` instances
                for this page.
            search
                The given search term, if any
            search_form
                The :class:`~mediacore.forms.admin.SearchForm` instance
            podcast_filter
                The given podcast ID to filter by, if any
            podcast_filter_title
                The podcast name for rendering if a ``podcast_filter`` was specified.
            podcast_filter_form
                The :class:`~mediacore.forms.media.PodcastFilterForm` instance.


        """
        media = DBSession.query(Media)\
            .filter(Media.status.excludes('trash'))\
            .options(orm.undefer('comment_count_published'))\
            .options(orm.undefer('comment_count_unreviewed'))\
            .order_by(Media.status.desc(),
                      Media.publish_on.desc(),
                      Media.modified_on.desc())

        if search is not None:
            like_search = '%' + search + '%'
            media = media.filter(sql.or_(
                Media.title.like(like_search),
                Media.description.like(like_search),
                Media.notes.like(like_search),
                Media.tags.any(Tag.name.like(like_search)),
            ))

        podcast_filter_title = podcast_filter
        if podcast_filter == 'Unfiled':
            media = media.filter(~Media.podcast.has())
        elif podcast_filter is not None and podcast_filter != 'All Media':
            media = media.filter(Media.podcast.has(Podcast.id == podcast_filter))
            podcast_filter_title = DBSession.query(Podcast.title).get(podcast_filter)
            podcast_filter = int(podcast_filter)

        return dict(
            media = media,
            podcast_filter = podcast_filter,
            podcast_filter_title = podcast_filter_title,
            podcast_filter_form = podcast_filter_form,
            search = search,
            search_form = search_form,
        )
开发者ID:SergeyLashin,项目名称:mediacore,代码行数:60,代码来源:mediaadmin.py

示例10: save

    def save(self, id, delete, category='topics', **kwargs):
        """Save changes or create a topic or tag.

        See :class:`~mediacore.forms.categories.EditCategoryForm` for POST vars.

        :param id: Topic or tag ID
        :param category: ``topics`` or ``tags``
        :param delete: If true the category is deleted rather than saved.
        :type delete: bool
        :rtype: JSON dict
        :returns:
            success
                bool
            category
                ``topics`` or ``tags``

        """
        model = self.select_model(category)
        item = fetch_row(model, id)

        if delete:
            DBSession.delete(item)
            item = None
        else:
            item.name = kwargs['name']
            item.slug = get_available_slug(model, kwargs['slug'], item)

            DBSession.add(item)

        if request.is_xhr:
            return dict(success=True, category=item)
        else:
            redirect(action='index', category=category)
开发者ID:SergeyLashin,项目名称:mediacore,代码行数:33,代码来源:categoryadmin.py

示例11: 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:BlendedLearningCollaborative,项目名称:mediacore-community,代码行数:8,代码来源:media_test.py

示例12: _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:dummyanni,项目名称:Bachelor-Thesis,代码行数:9,代码来源:filtering_restricted_items_test.py

示例13: 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:dummyanni,项目名称:Bachelor-Thesis,代码行数:9,代码来源:group_based_permissions_policy_test.py

示例14: view

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

        :param slug: The :attr:`~mediacore.models.media.Media.slug` to lookup
        :param podcast_slug: The :attr:`~mediacore.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:`~mediacore.model.media.Media` instance for display.
            related_media
                A list of :class:`~mediacore.model.media.Media` instances that
                rank as topically related to the given media item.
            comments
                A list of :class:`~mediacore.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:`~mediacore.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:wafe,项目名称:mediadrop,代码行数:56,代码来源:media.py

示例15: _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 = MediaCorePermissionSystem.permissions_for_user(admin, config)
     assert_true(perm.contains_permission(u'admin'))
     assert_false(perm.contains_permission(u'edit'))
     return admin
开发者ID:dummyanni,项目名称:Bachelor-Thesis,代码行数:10,代码来源:login_test.py


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