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

Python meta.DBSession类代码示例

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

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



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

示例1: init_model

def init_model(engine):
    """Call me before using any of the tables or classes in the model."""
    DBSession.configure(bind=engine)
    from mediacore.model import meta

    meta.metadata.bind = engine
    meta.engine = engine
开发者ID:vinces1979,项目名称:mediacore,代码行数:7,代码来源:__init__.py


示例2: _update_settings

    def _update_settings(self, values):
        """Modify the settings associated with the given dictionary."""
        for name, value in values.iteritems():
            setting = tmpl_context.settings[name]
            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:kidrane,项目名称:mediacore-community,代码行数:29,代码来源:base.py


示例3: bulk

    def bulk(self, type=None, ids=None, **kwargs):
        """Perform bulk operations on media items

        :param type: The type of bulk action to perform (delete)
        :param ids: A list of IDs.

        """
        if not ids:
            ids = []
        elif not isinstance(ids, list):
            ids = [ids]


        if type == 'delete':
            Category.query.filter(Category.id.in_(ids)).delete(False)
            DBSession.commit()
            success = True
        else:
            success = False

        return dict(
            success = success,
            ids = ids,
            parent_options = unicode(category_form.c['parent_id'].display()),
        )
开发者ID:BlendedLearningCollaborative,项目名称:mediacore-community,代码行数:25,代码来源:categories.py


示例4: increment_views

    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,代码行数:30,代码来源:media.py


示例5: _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.display_name = original_filename
    media_file.container = guess_container_format(file_ext)
    media_file.type = guess_media_type(media_file.container)

    # Small files are stored in memory and do not have a tmp file w/ fileno
    if hasattr(file, 'fileno'):
        media_file.size = os.fstat(file.fileno())[6]
    else:
        # The file may contain multi-byte characters, so we must seek instead of count chars
        file.seek(0, os.SEEK_END)
        media_file.size = file.tell()
        file.seek(0)

    # 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.file_name = file_name

    return media_file
开发者ID:86me,项目名称:mediacore,代码行数:33,代码来源:upload.py


示例6: save_fields

def save_fields(**result):
    """Save SEO settings to the database on a Media item save.

    When the :attr:`mediacore.plugin.events.Admin.MediaController.save`
    event is triggered it receives the dict of values returned by
    :meth:`mediacore.controllers.admin.media.MediaController.save`.

    The SEO values are extracted from tmpl_context.form_values and if
    a value was entered it is saved. If a valid setting was found, but
    it does not have a value, we remove it form the given media item.

    :param result: A dict of form values for the Media item
    :param type: dict
    :returns: A dict of form values for the Media item
    :rtpye: dict

    """

    media = Media.query.get(result['media_id'])
    for key, value in tmpl_context.form_values['seo'].iteritems():
        meta_key = u'seo_%s' % key
        if value:
            media.meta[meta_key] = value
        elif meta_key in media.meta:
            DBSession.delete(media._meta[meta_key])
    return result
开发者ID:mediadrop,项目名称:seo-plugin,代码行数:26,代码来源:mediacore_plugin.py


示例7: attach_and_store_media_file

def attach_and_store_media_file(media, media_file, file):
    """Given a Media object, a MediaFile object, and a file handle,
    attaches the MediaFile to the Media object, and saves the file to permanent
    storage.

    Adds the MediaFile to the database.
    """
    # Small files are stored in memory and do not have a tmp file w/ fileno
    if hasattr(file, 'fileno'):
        media_file.size = os.fstat(file.fileno())[6]
    else:
        # The file may contain multi-byte characters, so we must seek instead of count chars
        file.seek(0, os.SEEK_END)
        media_file.size = file.tell()
        file.seek(0)

    # 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, media_file.container)
    file_url = store_media_file(file, file_name)

    if file_url:
        # The file has been stored remotely
        media_file.url = file_url
    else:
        # The file is stored locally and we just need its name
        media_file.file_name = file_name
开发者ID:RadioErewan,项目名称:mediacore,代码行数:33,代码来源:mediafiles.py


示例8: restore_necessary_files

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,代码行数:32,代码来源:backup_restore.py


示例9: _autocommit_commit

def _autocommit_commit(req):
    try:
        DBSession.commit()
    except:
        _autocommit_rollback(req)
        raise
    else:
        _autocommit_fire_callbacks(req, req.commit_callbacks)
开发者ID:greentv,项目名称:mediacore,代码行数:8,代码来源:decorators.py


示例10: backup_files

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,代码行数:58,代码来源:backup_restore.py


示例11: _autocommit_commit

def _autocommit_commit(req):
    from mediacore.model.meta import DBSession
    try:
        DBSession.commit()
    except:
        _autocommit_rollback(req)
        raise
    else:
        _autocommit_fire_callbacks(req, req.commit_callbacks)
开发者ID:Jpoudrier,项目名称:mediacore-community,代码行数:9,代码来源:decorators.py


示例12: setUp

 def setUp(self):
     super(DBTestCase, self).setUp()
     self.env_dir = self._create_environment_folders()
     self.pylons_config = setup_environment_and_database(self.env_dir, 
         enabled_plugins=self.enabled_plugins)
     add_default_data()
     DBSession.commit()
     
     config.push_process_config(self.pylons_config)
开发者ID:Jpoudrier,项目名称:mediacore-community,代码行数:9,代码来源:db_testcase.py


示例13: disassociate_video_id

 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,代码行数:9,代码来源:__init__.py


示例14: podcast_from_feed

def podcast_from_feed(d, tags=False, save_files=False):
    # Assume not explicit
    explicit = False
    if 'itunes_explicit' in d['feed']:
        explicit = bool(d['feed']['itunes_explicit'])

    image = None
    if 'image' in d['feed']:
        image = d['feed']['image']['href']

    title = u''
    if 'title' in d['feed']:
        title = d['feed']['title']

    description = u''
    if 'summary' in d['feed']:
        description = d['feed']['summary']

    subtitle = u''
    if 'subtitle' in d['feed']:
        subtitle = d['feed']['subtitle']

    slug = slugify(title)
    author_name = u"PLACEHOLDER NAME"
    author_email = u"[email protected]"

    podcast = Podcast()
    podcast.slug = get_available_slug(Podcast, slug, podcast)
    podcast.title = title
    podcast.subtitle = subtitle
    podcast.author = Author(author_name, author_email)
    podcast.description = description
    podcast.explicit = explicit

    DBSession.add(podcast)
    DBSession.flush()

    # Create thumbs from image, or default thumbs
    created_images = False
    if image:
        temp_imagefile = tempfile.TemporaryFile()
        imagefile = urllib2.urlopen(image)
        temp_imagefile.write(imagefile.read())
        temp_imagefile.seek(0)
        filename = urlparse.urlparse(image)[2]
        create_thumbs_for(podcast, temp_imagefile, filename)
        created_images = True

    if not created_images:
        create_default_thumbs_for(podcast)

    # Now add all of the entries
    for entry in d['entries']:
        media = media_from_entry(entry, tags, save_files)
        media.podcast = podcast

    return podcast
开发者ID:MechanisM,项目名称:mediacore,代码行数:57,代码来源:rss_import.py


示例15: example

 def example(cls, **kwargs):
     defaults = dict(
         name = u'baz_users',
         display_name = u'Baz Users',
     )
     defaults.update(kwargs)
     group = Group(**defaults)
     DBSession.add(group)
     DBSession.flush()
     return group
开发者ID:axxis7,项目名称:mediacore-community,代码行数:10,代码来源:auth.py


示例16: import_videos_from_feed

 def import_videos_from_feed(self, feed):
     for entry in feed.entry:
         youtube_id = self.id_for_entry(entry)
         if not self._should_import_video(youtube_id):
             continue
         media = self._import_video(entry)
         self._video_notifcation(youtube_id)
         if media:
             DBSession.add(media)
             DBSession.flush()
开发者ID:mediadrop,项目名称:youtube-import-plugin,代码行数:10,代码来源:core.py


示例17: fetch_and_create_multi_setting

def fetch_and_create_multi_setting(key, value):
    multisettings = MultiSetting.query\
        .filter(MultiSetting.key==key)\
        .all()
    for ms in multisettings:
        if ms.value == value:
            return ms
    ms = MultiSetting(key, value)
    DBSession.add(ms)
    return ms
开发者ID:MechanisM,项目名称:mediacore,代码行数:10,代码来源:settings.py


示例18: update_status

    def update_status(self, id, update_button=None, publish_on=None, **values):
        """Update the publish status for the given media.

        :param id: Media ID
        :type id: ``int``
        :param update_status: The text of the submit button which indicates
            that the :attr:`~mediacore.model.media.Media.status` should change.
        :type update_status: ``unicode`` or ``None``
        :param publish_on: A date to set to
            :attr:`~mediacore.model.media.Media.publish_on`
        :type publish_on: :class:`datetime.datetime` or ``None``
        :rtype: JSON dict
        :returns:
            success
                bool
            message
                Error message, if unsuccessful
            status_form
                Rendered XHTML for the status form, updated to reflect the
                changes made.

        """
        media = fetch_row(Media, id)
        new_slug = None

        # Make the requested change assuming it will be allowed
        if update_button == _('Review Complete'):
            media.reviewed = True
        elif update_button == _('Publish Now'):
            media.publishable = True
            media.publish_on = publish_on or datetime.now()
            media.update_popularity()
            # Remove the stub prefix if the user wants the default media title
            if media.slug.startswith('_stub_'):
                new_slug = get_available_slug(Media, media.slug[len('_stub_'):])
                media.slug = new_slug
        elif publish_on:
            media.publish_on = publish_on
            media.update_popularity()

        # Verify the change is valid by re-determining the status
        media.update_status()
        DBSession.flush()

        if request.is_xhr:
            # Return the rendered widget for injection
            status_form_xhtml = unicode(update_status_form.display(
                action=url_for(action='update_status'), media=media))
            return dict(
                success = True,
                status_form = status_form_xhtml,
                slug = new_slug,
            )
        else:
            redirect(action='edit')
开发者ID:RadioErewan,项目名称:mediacore,代码行数:55,代码来源:media.py


示例19: save_thumb

    def save_thumb(self, id, thumb, **kwargs):
        """Save a thumbnail uploaded with :class:`~mediacore.forms.admin.ThumbForm`.

        :param id: Media ID. If ``"new"`` a new Media stub is created with
            :func:`~mediacore.model.media.create_media_stub`.
        :type id: ``int`` or ``"new"``
        :param file: The uploaded file
        :type file: :class:`cgi.FieldStorage` or ``None``
        :rtype: JSON dict
        :returns:
            success
                bool
            message
                Error message, if unsuccessful
            id
                The :attr:`~mediacore.model.media.Media.id` which is
                important if a new media has just been created.

        """
        if id == 'new':
            media = create_media_stub()
        else:
            media = fetch_row(Media, id)

        try:
            # Create thumbs
            img = Image.open(thumb.file)

            if id == 'new':
                DBSession.add(media)
                DBSession.flush()

            # TODO: Allow other formats?
            for key, xy in config['thumb_sizes'][media._thumb_dir].iteritems():
                thumb_path = helpers.thumb_path(media, key)
                thumb_img = helpers.resize_thumb(img, xy)
                thumb_img.save(thumb_path)

            # Backup the original image just for kicks
            backup_type = os.path.splitext(thumb.filename)[1].lower()[1:]
            backup_path = helpers.thumb_path(media, 'orig', ext=backup_type)
            backup_file = open(backup_path, 'w+b')
            thumb.file.seek(0)
            shutil.copyfileobj(thumb.file, backup_file)
            thumb.file.close()
            backup_file.close()

            success = True
            message = None
        except IOError:
            success = False
            message = 'Unsupported image type'
        except Exception, e:
            success = False
            message = e.message
开发者ID:GunioRobot,项目名称:mediacore,代码行数:55,代码来源:media.py


示例20: fetch_and_create_tags

def fetch_and_create_tags(tag_names):
    """Return a list of Tag instances that match the given names.

    Tag names that don't yet exist are created automatically and
    returned alongside the results that did already exist.

    If you try to create a new tag that would have the same slug
    as an already existing tag, the existing tag is used instead.

    :param tag_names: The display :attr:`Tag.name`
    :type tag_names: list
    :returns: A list of :class:`Tag` instances.
    :rtype: :class:`TagList` instance

    """
    results = TagList()
    lower_names = [name.lower() for name in tag_names]
    slugs = [slugify(name) for name in lower_names]

    # Grab all the tags that exist already, whether its the name or slug
    # that matches. Slugs can be changed by the tag settings UI so we can't
    # rely on each tag name evaluating to the same slug every time.
    results = Tag.query.filter(sql.or_(func.lower(Tag.name).in_(lower_names),
                                       Tag.slug.in_(slugs))).all()

    # Filter out any tag names that already exist (case insensitive), and
    # any tag names evaluate to slugs that already exist.
    for tag in results:
        # Remove the match from our three lists until its completely gone
        while True:
            try:
                try:
                    index = slugs.index(tag.slug)
                except ValueError:
                    index = lower_names.index(tag.name.lower())
                tag_names.pop(index)
                lower_names.pop(index)
                slugs.pop(index)
            except ValueError:
                break

    # Any remaining tag names need to be created.
    if tag_names:
        # We may still have multiple tag names which evaluate to the same slug.
        # Load it into a dict so that duplicates are overwritten.
        uniques = dict((slug, name) for slug, name in izip(slugs, tag_names))
        # Do a bulk insert to create the tag rows.
        new_tags = [{'name': n, 'slug': s} for s, n in uniques.iteritems()]
        DBSession.execute(tags.insert(), new_tags)
        DBSession.flush()
        # Query for our newly created rows and append them to our result set.
        results += Tag.query.filter(Tag.slug.in_(uniques.keys())).all()

    return results
开发者ID:AshKash,项目名称:mediacore-community,代码行数:54,代码来源:tags.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python config._cfg函数代码示例发布时间:2022-05-27
下一篇:
Python model.Media类代码示例发布时间: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