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


Python DBSession.query方法代码示例

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


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

示例1: restore_necessary_files

# 需要导入模块: from mediacore.model.meta import DBSession [as 别名]
# 或者: from mediacore.model.meta.DBSession import query [as 别名]
def restore_necessary_files():
    # Restore the appropriate media files and thumbnail files
    # for any media currently in the database.
    # Use the python models to do this.
    if not deleted_dir:
        return

    filename_pairs = []
    for media in DBSession.query(Media).all():
        for thumb in thumb_paths(media).values():
            filename_pairs.append((
                thumb.replace(m_img_dir, m_deleted_dir),
                thumb
            ))
        for file in media.files:
            if file.file_path:
                filename_pairs.append((
                    file.file_path.replace(media_dir, m_deleted_dir),
                    file.file_path
                ))
    for podcast in DBSession.query(Podcast).all():
        for thumb in thumb_paths(podcast).values():
            filename_pairs.append((
                thumb.replace(p_img_dir, p_deleted_dir),
                thumb
            ))

    for src, dest in filename_pairs:
        if os.path.exists(src):
            if DEBUG:
                print "Moving %s to %s" % (src, dest)
            shutil.move(src, dest)
开发者ID:RadioErewan,项目名称:mediacore,代码行数:34,代码来源:backup_restore.py

示例2: fetch_and_create_tags

# 需要导入模块: from mediacore.model.meta import DBSession [as 别名]
# 或者: from mediacore.model.meta.DBSession import query [as 别名]
def fetch_and_create_tags(tag_names):
    # copy the tag_names list
    new_tag_names = tag_names[:]

    # find tag names that already exist (case insensitive match)
    # and remove those names from our list
    lower_case_tags = [t.lower() for t in new_tag_names]
    existing_tags = DBSession.query(Tag).\
        filter(
            func.lower(Tag.name).in_(lower_case_tags)
        ).all()
    for t in existing_tags:
        for n in new_tag_names[:]:
            if n.lower() == t.name.lower():
                new_tag_names.remove(n)
                break

    # create the tags that don't yet exist
    if new_tag_names:
        new_tags = [{'name': n, 'slug': slugify(n)} for n in new_tag_names]
        DBSession.connection().execute(tags.insert(), new_tags)
        DBSession.flush()
        existing_tags += DBSession.query(Tag)\
            .filter(
                Tag.slug.in_([t['slug'] for t in new_tags])
            ).all()

    return existing_tags
开发者ID:86me,项目名称:mediacore,代码行数:30,代码来源:tags.py

示例3: increment_views

# 需要导入模块: from mediacore.model.meta import DBSession [as 别名]
# 或者: from mediacore.model.meta.DBSession import query [as 别名]
    def increment_views(self):
        """Increment the number of views in the database.

        We avoid concurrency issues by incrementing JUST the views and
        not allowing modified_on to be updated automatically.

        """
        if self.id is None:
            self.views += 1
            return self.views

        # Don't raise an exception should concurrency problems occur.
        # Views will not actually be incremented in this case, but thats
        # relatively unimportant compared to rendering the page for the user.
        # We may be able to remove this after we improve our triggers to not
        # issue an UPDATE on media_fulltext unless one of its columns are
        # actually changed. Even when just media.views is updated, all the
        # columns in the corresponding media_fulltext row are updated, and
        # media_fulltext's MyISAM engine must lock the whole table to do so.
        transaction = DBSession.begin_nested()
        try:
            DBSession.query(self.__class__)\
                .filter(self.__class__.id == self.id)\
                .update({self.__class__.views: self.__class__.views + 1})
            transaction.commit()
        except exc.OperationalError, e:
            transaction.rollback()
            # (OperationalError) (1205, 'Lock wait timeout exceeded, try restarting the transaction')
            if not '1205' in e.message:
                raise
开发者ID:RadioErewan,项目名称:mediacore,代码行数:32,代码来源:media.py

示例4: backup_files

# 需要导入模块: from mediacore.model.meta import DBSession [as 别名]
# 或者: from mediacore.model.meta.DBSession import query [as 别名]
def backup_files(dump_dir):
    # Backup all files (media files, thumbs) referenced by an object in the DB
    # to the provided dump_dir.

    # TODO: display errors when file operations fail

    if dump_dir == "/":
        return 1, "Dump Files directory should never be the root directory, '/'"

    # normalize dirname
    dump_dir = dump_dir.rstrip(os.sep) + os.sep

    # These are the directories we will write to.
    media_thumb_dir = dump_dir + Media._thumb_dir
    podcast_thumb_dir = dump_dir + Podcast._thumb_dir
    media_files_dir = dump_dir + "media_files"

    # Initialize our default paths to backup
    default_images = ["news.jpg", "newm.jpg", "newl.jpg"]
    media_thumbs = [m_img_dir + os.sep + img for img in default_images]
    podcast_thumbs = [p_img_dir + os.sep + img for img in default_images]
    media_files = []

    # Add the media thumbs and media files
    for media in DBSession.query(Media).all():
        file_paths = [file_path(f) for f in media.files]
        media_files += [fp for fp in file_paths if fp]
        media_thumbs += thumb_paths(media).values()

    # Add the podcast thumbs
    for podcast in DBSession.query(Podcast).all():
        podcast_thumbs += thumb_paths(podcast).values()

    # Ensure the necessary directories exist.
    assert os.path.isdir(dump_dir)
    for subdir in (media_thumb_dir, media_files_dir, podcast_thumb_dir):
        if not os.path.exists(subdir):
            os.mkdir(subdir)
        assert os.path.isdir(subdir)
        empty_dir(subdir)

    # Copy over all of the files:
    sources_dests = (
        (media_thumbs, media_thumb_dir),
        (media_files, media_files_dir),
        (podcast_thumbs, podcast_thumb_dir),
    )
    for sources, dest_dir in sources_dests:
        for src in sources:
            if DEBUG:
                print "Copying %s to %s%s" % (src, dest_dir, os.sep)
            shutil.copy2(src, dest_dir)

    return (
        0,
        "%d thumbnails and %d media files successfully backed up"
        % (len(media_thumbs) + len(podcast_thumbs), len(media_files)),
    )
开发者ID:nguyennamtien,项目名称:mediacore,代码行数:60,代码来源:backup_restore.py

示例5: remove_unnecessary_files

# 需要导入模块: from mediacore.model.meta import DBSession [as 别名]
# 或者: from mediacore.model.meta.DBSession import query [as 别名]
def remove_unnecessary_files():
    # Move all media files and thumbnail files into 'deleted' folder.
    # XXX: don't run if deleted_dir is not set!
    if not deleted_dir:
        return

    for media in DBSession.query(Media).all():
        file_paths = thumb_paths(media).values()
        for f in media.files:
            file_paths.append(f.file_path)
        helpers.delete_files(file_paths, 'media')

    for podcast in DBSession.query(Podcast).all():
        file_paths = thumb_paths(podcast).values()
        helpers.delete_files(file_paths, 'podcasts')
开发者ID:RadioErewan,项目名称:mediacore,代码行数:17,代码来源:backup_restore.py

示例6: insert_settings

# 需要导入模块: from mediacore.model.meta import DBSession [as 别名]
# 或者: from mediacore.model.meta.DBSession import query [as 别名]
def insert_settings(defaults):
    """Insert the given setting if they don't exist yet.

    XXX: Does not include any support for MultiSetting. This approach
         won't work for that. We'll need to use sqlalchemy-migrate.

    :type defaults: list
    :param defaults: Key and value pairs
    :rtype: list
    :returns: Any settings that have just been created.
    """
    inserted = []
    existing_settings = set(x[0] for x in DBSession.query(Setting.key) \
                                     .filter(Setting.key \
                                     .in_(key for key, value in defaults)))

    for key, value in defaults:
        if key in existing_settings:
            continue
        transaction = DBSession.begin_nested()
        try:
            s = Setting(key, value)
            DBSession.add(s)
            transaction.commit()
            inserted.append(s)
        except IntegrityError:
            transaction.rollback()
    if inserted:
        DBSession.commit()
    return inserted
开发者ID:dbooth,项目名称:mediacore,代码行数:32,代码来源:settings.py

示例7: get_available_slug

# 需要导入模块: from mediacore.model.meta import DBSession [as 别名]
# 或者: from mediacore.model.meta.DBSession import query [as 别名]
def get_available_slug(mapped_class, string, ignore=None, slug_attr='slug', slug_length=SLUG_LENGTH):
    """Return a unique slug based on the provided string.

    Works by appending an int in sequence starting with 2:

        1. awesome-stuff
        2. awesome-stuff-2
        3. awesome-stuff-3

    :param mapped_class: The ORM-controlled model that the slug is for
    :param string: A title, name, etc
    :type string: unicode
    :param ignore: A record which doesn't count as a collision
    :type ignore: Int ID, ``mapped_class`` instance or None
    :returns: A unique slug
    :rtype: unicode
    """
    if isinstance(ignore, mapped_class):
        ignore = ignore.id
    elif ignore is not None:
        ignore = int(ignore)

    new_slug = slug = slugify(string)
    appendix = 2
    while DBSession.query(mapped_class.id)\
            .filter(getattr(mapped_class, slug_attr) == new_slug)\
            .filter(mapped_class.id != ignore)\
            .first():
        str_appendix = u'-%s' % appendix
        max_substr_len = slug_length - len(str_appendix)
        new_slug = slug[:max_substr_len] + str_appendix
        appendix += 1

    return new_slug
开发者ID:wafe,项目名称:mediadrop,代码行数:36,代码来源:__init__.py

示例8: panda_retry

# 需要导入模块: from mediacore.model.meta import DBSession [as 别名]
# 或者: from mediacore.model.meta.DBSession import query [as 别名]
 def panda_retry(self, file_id, encoding_id, **kwargs):
     media_file = fetch_row(MediaFile, file_id)
     storage = DBSession.query(PandaStorage).first()
     storage.panda_helper().retry_transcode(media_file, encoding_id)
     return dict(
         success = True,
     )
开发者ID:mediadrop,项目名称:panda-plugin,代码行数:9,代码来源:media.py

示例9: disassociate_video_id

# 需要导入模块: from mediacore.model.meta import DBSession [as 别名]
# 或者: from mediacore.model.meta.DBSession import query [as 别名]
 def disassociate_video_id(self, media_file, video_id):
     # Create a meta_key for this MediaCore::MediaFile -> Panda::Video pairing.
     # This is sort of a perversion of the meta table, but hey, it works.
     meta_key = u"%s%s" % (META_VIDEO_PREFIX, video_id)
     mfm = DBSession.query(MediaFilesMeta)\
             .filter(MediaFilesMeta.media_files_id==media_file.id)\
             .filter(MediaFilesMeta.key==meta_key)
     for x in mfm:
         DBSession.delete(x)
开发者ID:mediadrop,项目名称:panda-plugin,代码行数:11,代码来源:__init__.py

示例10: main

# 需要导入模块: from mediacore.model.meta import DBSession [as 别名]
# 或者: from mediacore.model.meta.DBSession import query [as 别名]
def main(parser, options, args):
	for engine in DBSession.query(AmazonS3Storage):
        bucket = engine.connect_to_bucket()
        key = Key(bucket)
        key.key = 'crossdomain.xml'
        key.set_contents_from_string(CONTENTS, {'Content-Type': 'application/xml'})
        key.set_acl('public-read')

    sys.exit(0)

if __name__ == "__main__":
    main(cmd.parser, cmd.options, cmd.args)
开发者ID:seanbradley,项目名称:mediacore_aws,代码行数:14,代码来源:upload-crossdomain-xml.py

示例11: comments_save

# 需要导入模块: from mediacore.model.meta import DBSession [as 别名]
# 或者: from mediacore.model.meta.DBSession import query [as 别名]
    def comments_save(self, **kwargs):
        """Save :class:`~mediacore.forms.admin.settings.CommentsForm`."""
        old_vulgarity_filter = c.settings['vulgarity_filtered_words'].value

        self._save(comments_form, values=kwargs)

        # Run the filter now if it has changed
        if old_vulgarity_filter != c.settings['vulgarity_filtered_words'].value:
            for comment in DBSession.query(Comment):
                comment.body = filter_vulgarity(comment.body)

        redirect(action='comments')
开发者ID:AshKash,项目名称:mediacore-community,代码行数:14,代码来源:settings.py

示例12: index

# 需要导入模块: from mediacore.model.meta import DBSession [as 别名]
# 或者: from mediacore.model.meta.DBSession import query [as 别名]
    def index(self, page=1, search=None, media_filter=None, **kwargs):
        """List comments 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 media_filter: Optional media ID to filter by
        :type media_filter: int or None
        :rtype: dict
        :returns:
            comments
                The list of :class:`~mediacore.model.comments.Comment` instances
                for this page.
            edit_form
                The :class:`mediacore.forms.admin.comments.EditCommentForm` instance,
                to be rendered for each instance in ``comments``.
            search
                The given search term, if any
            search_form
                The :class:`~mediacore.forms.admin.SearchForm` instance
            media_filter
                The given podcast ID to filter by, if any
            media_filter_title
                The media title for rendering if a ``media_filter`` was specified.

        """
        comments = Comment.query.trash(False)\
            .order_by(Comment.reviewed.asc(),
                      Comment.created_on.desc())

        # This only works since we only have comments on one type of content.
        # It will need re-evaluation if we ever add others.
        comments = comments.options(orm.eagerload('media'))

        if search is not None:
            comments = comments.search(search)

        media_filter_title = media_filter
        if media_filter is not None:
            comments = comments.filter(Comment.media.has(Media.id == media_filter))
            media_filter_title = DBSession.query(Media.title).get(media_filter)
            media_filter = int(media_filter)

        return dict(
            comments = comments,
            edit_form = edit_form,
            media_filter = media_filter,
            media_filter_title = media_filter_title,
            search = search,
            search_form = search_form,
        )
开发者ID:AshKash,项目名称:mediacore-community,代码行数:54,代码来源:comments.py

示例13: index

# 需要导入模块: from mediacore.model.meta import DBSession [as 别名]
# 或者: from mediacore.model.meta.DBSession import query [as 别名]
    def index(self, page=1, **kw):
        """List podcasts with pagination.

        :param page: Page number, defaults to 1.
        :type page: int
        :rtype: Dict
        :returns:
            podcasts
                The list of :class:`~mediacore.model.podcasts.Podcast`
                instances for this page.
        """
        podcasts = DBSession.query(Podcast).options(orm.undefer("media_count")).order_by(Podcast.title)
        return dict(podcasts=podcasts)
开发者ID:greentv,项目名称:mediacore,代码行数:15,代码来源:podcasts.py

示例14: index

# 需要导入模块: from mediacore.model.meta import DBSession [as 别名]
# 或者: from mediacore.model.meta.DBSession import query [as 别名]
    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.admin.media.PodcastFilterForm` instance.

        """
        media = Media.query.options(orm.undefer('comment_count_published'))

        if search:
            media = media.admin_search(search)
        else:
            media = media.order_by_status()\
                         .order_by(Media.publish_on.desc(),
                                   Media.modified_on.desc())

        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:GunioRobot,项目名称:mediacore,代码行数:53,代码来源:media.py

示例15: panda_update

# 需要导入模块: from mediacore.model.meta import DBSession [as 别名]
# 或者: from mediacore.model.meta.DBSession import query [as 别名]
    def panda_update(self, media_id=None, file_id=None, video_id=None, **kwargs):
        if file_id:
            media_file = fetch_row(MediaFile, file_id)
            media_files = [media_file]
        elif media_id:
            media = fetch_row(Media, media_id)
            media_files = media.files

        storage = DBSession.query(PandaStorage).first()

        for media_file in media_files:
            storage.panda_helper().video_status_update(media_file, video_id)

        redirect(controller='/admin/media', action='edit', id=media_id)
开发者ID:seanbradley,项目名称:mediacore_panda,代码行数:16,代码来源:media.py


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