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


Python DBSession.flush方法代码示例

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


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

示例1: comment

# 需要导入模块: from mediacore.model import DBSession [as 别名]
# 或者: from mediacore.model.DBSession import flush [as 别名]
    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,代码行数:62,代码来源:media.py

示例2: save_media_obj

# 需要导入模块: from mediacore.model import DBSession [as 别名]
# 或者: from mediacore.model.DBSession import flush [as 别名]
    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:AshKash,项目名称:mediacore-community,代码行数:28,代码来源:upload.py

示例3: _update_settings

# 需要导入模块: from mediacore.model import DBSession [as 别名]
# 或者: from mediacore.model.DBSession import flush [as 别名]
    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,代码行数:34,代码来源:base.py

示例4: save

# 需要导入模块: from mediacore.model import DBSession [as 别名]
# 或者: from mediacore.model.DBSession import flush [as 别名]
    def save(self, id, email_address, display_name, login_details, delete=None, **kwargs):
        """Save changes or create a new :class:`~mediacore.model.auth.User` instance.

        :param id: User ID. If ``"new"`` a new user is created.
        :type id: ``int`` or ``"new"``
        :returns: Redirect back to :meth:`index` after successful save.

        """
        user = fetch_row(User, id)

        if delete:
            DBSession.delete(user)
            redirect(action="index", id=None)

        user.display_name = display_name
        user.email_address = email_address
        user.user_name = login_details["user_name"]

        password = login_details["password"]
        if password is not None and password != "":
            user.password = password

        if login_details["group"]:
            group = fetch_row(Group, login_details["group"])
            user.groups = [group]
        else:
            user.groups = []

        DBSession.add(user)
        DBSession.flush()
        redirect(action="index", id=None)
开发者ID:SergeyLashin,项目名称:mediacore,代码行数:33,代码来源:useradmin.py

示例5: _add_new_media_file

# 需要导入模块: from mediacore.model import DBSession [as 别名]
# 或者: from mediacore.model.DBSession import flush [as 别名]
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,代码行数:29,代码来源:media.py

示例6: _create_user_without_groups

# 需要导入模块: from mediacore.model import DBSession [as 别名]
# 或者: from mediacore.model.DBSession import flush [as 别名]
 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,代码行数:11,代码来源:filtering_restricted_items_test.py

示例7: test_can_restrict_query_if_user_does_not_have_the_required_permission

# 需要导入模块: from mediacore.model import DBSession [as 别名]
# 或者: from mediacore.model.DBSession import flush [as 别名]
 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,代码行数:11,代码来源:group_based_permissions_policy_test.py

示例8: save_album_art

# 需要导入模块: from mediacore.model import DBSession [as 别名]
# 或者: from mediacore.model.DBSession import flush [as 别名]
    def save_album_art(self, id, album_art, **kwargs):
        """Save album art uploaded with :class:`~mediacore.forms.media.AlbumArtForm`.

        :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, incl_trash=True)

        im_path = os.path.join(config.image_dir, 'media/%s%s.%s')

        try:
            # Create thumbnails
            im = Image.open(album_art.file)

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

            # TODO: Allow other formats?
            for key, dimensions in config.album_art_sizes.iteritems():
                file_path = im_path % (media.id, key, 'jpg')
                im.resize(dimensions, 1).save(file_path)

            # Backup the original image just for kicks
            orig_type = os.path.splitext(album_art.filename)[1].lower()[1:]
            backup_file = open(im_path % (media.id, 'orig', orig_type), 'w')
            copyfileobj(album_art.file, backup_file)
            album_art.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:SergeyLashin,项目名称:mediacore,代码行数:56,代码来源:mediaadmin.py

示例9: fetch_and_create_tags

# 需要导入模块: from mediacore.model import DBSession [as 别名]
# 或者: from mediacore.model.DBSession import flush [as 别名]
def fetch_and_create_tags(tag_names):
    tag_dict = dict()
    for t in tag_names:
        tag_dict[slugify(t)] = t

    existing_tags = DBSession.query(Tag).filter(Tag.slug.in_(tag_dict.keys())).all()
    existing_slugs = [t.slug for t in existing_tags]
    new_slugs = [s for s in tag_dict.keys() if s not in existing_slugs]
    new_tags = [{'name': tag_dict[s], 'slug': s} for s in new_slugs]

    if new_tags:
        DBSession.connection().execute(tags.insert(), new_tags)
        DBSession.flush()
        existing_tags += DBSession.query(Tag).filter(Tag.slug.in_(new_slugs)).all()
    return existing_tags
开发者ID:SergeyLashin,项目名称:mediacore,代码行数:17,代码来源:tags.py

示例10: delete

# 需要导入模块: from mediacore.model import DBSession [as 别名]
# 或者: from mediacore.model.DBSession import flush [as 别名]
    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:BlendedLearningCollaborative,项目名称:mediacore-community,代码行数:19,代码来源:players.py

示例11: rate

# 需要导入模块: from mediacore.model import DBSession [as 别名]
# 或者: from mediacore.model.DBSession import flush [as 别名]
    def rate(self, slug, up=None, down=None, **kwargs):
        """Say 'I like this' for the given media.

        :param slug: The media :attr:`~mediacore.model.media.Media.slug`
        :rtype: unicode
        :returns:
            The new number of likes

        """
        # we have to check if current user is anonymous or authenticated
        userid = check_user_authentication(request)
        if not userid:
            log.warn('Anonymous user cannot rate media')
            raise HTTPUnauthorized().exception
            
        media = fetch_row(Media, slug=slug)
        
        # check if current user has already voted this media object
        votes = Vote.query.get_votes(media_id=media.id, user_name = userid)
        if votes.count():
            # if true redirect to 'view'
            log.warn('User %s already voted this media')
            redirect(action='view')

        # create new vote object mapping current media and user
        vote = Vote()
        vote.media_id = media.id
        vote.user_name = userid

        # Give the Vote object an ID.
        DBSession.add(vote)
        DBSession.flush()

        if up:
            vote.increment_likes()
            media.increment_likes()
        elif down:
            vote.increment_dislikes()
            media.increment_dislikes()
        
        if request.is_xhr:
            return u''
        else:
            redirect(action='view')
开发者ID:abstract-open-solutions,项目名称:mediacore,代码行数:46,代码来源:media.py

示例12: reorder_file

# 需要导入模块: from mediacore.model import DBSession [as 别名]
# 或者: from mediacore.model.DBSession import flush [as 别名]
    def reorder_file(self, id, file_id, budge_infront_id, **kwargs):
        """Change the position of the given file relative to the 2nd file.

        :param file_id: The file to move
        :type file_id: ``int``
        :param budge_infront_id: The file whos position the first file takes.
            All files behind/after this file are bumped back as well.
        :type budge_infront_id: ``int`` or ``None``
        :rtype: JSON dict
        :returns:
            success
                bool

        """
        media = fetch_row(Media, id, incl_trash=True)
        media.reposition_file(file_id, budge_infront_id)
        DBSession.add(media)
        DBSession.flush()
        return dict(success=True)
开发者ID:SergeyLashin,项目名称:mediacore,代码行数:21,代码来源:mediaadmin.py

示例13: update_status

# 需要导入模块: from mediacore.model import DBSession [as 别名]
# 或者: from mediacore.model.DBSession import flush [as 别名]
    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, incl_trash=True)

        # Make the requested change assuming it will be allowed
        if update_button == 'Review Complete':
            media.status.discard('unreviewed')
        elif update_button == 'Publish Now':
            media.status.discard('draft')
            media.status.add('publish')
            media.publish_on = publish_on or datetime.now()
        elif publish_on:
            media.publish_on = publish_on

        try:
            # Verify the change is valid by re-determining the status
            media.update_status()
            DBSession.add(media)
            DBSession.flush()
            data = dict(success=True)
        except Exception, e:
            data = dict(success=False, message=e.message)
开发者ID:SergeyLashin,项目名称:mediacore,代码行数:44,代码来源:mediaadmin.py

示例14: save

# 需要导入模块: from mediacore.model import DBSession [as 别名]
# 或者: from mediacore.model.DBSession import flush [as 别名]
    def save(self, email, legal_wording, default_wording, **kwargs):
        """Save :class:`~mediacore.forms.settings.SettingsForm`.

        Redirects back to :meth:`edit` after successful editing.

        """
        settings = self._fetch_keyed_settings()
        settings['email_media_uploaded'].value = email['media_uploaded']
        settings['email_comment_posted'].value = email['comment_posted']
        settings['email_support_requests'].value = email['support_requests']
        settings['email_send_from'].value = email['send_from']
#        settings['ftp_server'].value = ftp['server']
#        settings['ftp_username'].value = ftp['username']
#        if ftp['password'] is not None and ftp['password'] != '':
#            settings['ftp_password'].value = ftp['password']
#        settings['ftp_upload_path'].value = ftp['upload_path']
#        settings['ftp_download_url'].value = ftp['download_url']
        settings['wording_user_uploads'].value = legal_wording['user_uploads']
        settings['wording_additional_notes'].value = default_wording['additional_notes']

        DBSession.add_all(settings.values())
        DBSession.flush()
        redirect(action='edit')
开发者ID:SergeyLashin,项目名称:mediacore,代码行数:25,代码来源:settingadmin.py

示例15: save

# 需要导入模块: from mediacore.model import DBSession [as 别名]
# 或者: from mediacore.model.DBSession import flush [as 别名]
    def save(self, id, slug, title, author_name, author_email,
             description, notes, details, podcast, tags, topics, delete=None, **kwargs):
        """Save changes or create a new :class:`~mediacore.model.media.Media` instance.

        Form handler the :meth:`edit` action and the
        :class:`~mediacore.forms.media.MediaForm`.

        Redirects back to :meth:`edit` after successful editing
        and :meth:`index` after successful deletion.

        """
        media = fetch_row(Media, id, incl_trash=True)

        if delete:
            media.status.add('trash')
            DBSession.add(media)
            DBSession.flush()
            redirect(action='index', id=None)

        if id == 'new':
            media.status = 'draft,unencoded,unreviewed'

        media.slug = get_available_slug(Media, slug, media)
        media.title = title
        media.author = Author(author_name, author_email)
        media.description = helpers.clean_admin_xhtml(description)
        media.notes = notes
        media.duration = helpers.duration_to_seconds(details['duration'])
        media.podcast_id = podcast
        media.set_tags(tags)
        media.set_topics(topics)

        media.update_status()
        DBSession.add(media)
        DBSession.flush()

        redirect(action='edit', id=media.id)
开发者ID:SergeyLashin,项目名称:mediacore,代码行数:39,代码来源:mediaadmin.py


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