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


Python helpers.url_for函数代码示例

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


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

示例1: post_login

 def post_login(self, came_from=None, **kwargs):
     if not request.identity:
         # The FriendlyForm plugin will always issue a redirect to 
         # /login/continue (post login url) even for failed logins.
         # If 'came_from' is a protected page (i.e. /admin) we could just 
         # redirect there and the login form will be displayed again with
         # our login error message.
         # However if the user tried to login from the front page, this 
         # mechanism doesn't work so go to the login method directly here.
         self._increase_number_of_failed_logins()
         return self.login(came_from=came_from)
     if came_from:
         url_mapper = request.environ['routes.url'].mapper
         target = dispatch_info_for_url(came_from, url_mapper)
         if not is_url_for_mediadrop_domain(came_from):
             log.debug('no redirect to %r because target url does match our hostname (prevents parameter base redirection attacks)' % came_from)
             came_from = None
         elif (target is not None) and getattr(target.action, '_request_method', None) not in ('GET', None):
             log.debug('no redirect to %r because target url does not allow GET requests' % came_from)
             came_from = None
         if came_from:
             redirect(came_from)
     # It is important to return absolute URLs (if app mounted in subdirectory)
     if request.perm.contains_permission(u'edit') or request.perm.contains_permission(u'admin'):
         redirect(url_for('/admin', qualified=True))
     redirect(url_for('/', qualified=True))
开发者ID:knyar,项目名称:mediadrop,代码行数:26,代码来源:login.py

示例2: 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

示例3: index

    def index(self, page=1, show='latest', q=None, tag=None, **kwargs):
        """List media with pagination.

        The media paginator may be accessed in the template with
        :attr:`c.paginators.media`, see :class:`webhelpers.paginate.Page`.

        :param page: Page number, defaults to 1.
        :type page: int
        :param show: 'latest', 'popular' or 'featured'
        :type show: unicode or None
        :param q: A search query to filter by
        :type q: unicode or None
        :param tag: A tag slug to filter for
        :type tag: unicode or None
        :rtype: dict
        :returns:
            media
                The list of :class:`~mediadrop.model.media.Media` instances
                for this page.
            result_count
                The total number of media items for this query
            search_query
                The query the user searched for, if any

        """
        media = Media.query.published()

        media, show = helpers.filter_library_controls(media, show)

        if q:
            media = media.search(q, bool=True)

        if tag:
            tag = fetch_row(Tag, slug=tag)
            media = media.filter(Media.tags.contains(tag))

        if (request.settings['rss_display'] == 'True') and (not (q or tag)):
            if show == 'latest':
                response.feed_links.extend([
                    (url_for(controller='/sitemaps', action='latest'), _(u'Latest RSS')),
                ])
            elif show == 'featured':
                response.feed_links.extend([
                    (url_for(controller='/sitemaps', action='featured'), _(u'Featured RSS')),
                ])

        media = viewable_media(media)
        return dict(
            media = media,
            result_count = media.count(),
            search_query = q,
            show = show,
            tag = tag,
        )
开发者ID:FelixSchwarz,项目名称:mediadrop-test-renames,代码行数:54,代码来源:media.py

示例4: save

    def save(self, id, slug, title, author_name, author_email,
             description, notes, podcast, tags, categories,
             delete=None, **kwargs):
        """Save changes or create a new :class:`~mediadrop.model.media.Media` instance.

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

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

        """
        media = fetch_row(Media, id)

        if delete:
            self._delete_media(media)
            redirect(action='index', id=None)

        if not slug:
            slug = slugify(title)
        elif slug.startswith('_stub_'):
            slug = slug[len('_stub_'):]
        if slug != media.slug:
            media.slug = get_available_slug(Media, slug, media)
        media.title = title
        media.author = Author(author_name, author_email)
        media.description = description
        media.notes = notes
        media.podcast_id = podcast
        media.set_tags(tags)
        media.set_categories(categories)

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

        if id == 'new' and not has_thumbs(media):
            create_default_thumbs_for(media)

        if request.is_xhr:
            status_form_xhtml = unicode(update_status_form.display(
                action=url_for(action='update_status', id=media.id),
                media=media))

            return dict(
                media_id = media.id,
                values = {'slug': slug},
                link = url_for(action='edit', id=media.id),
                status_form = status_form_xhtml,
            )
        else:
            redirect(action='edit', id=media.id)
开发者ID:knyar,项目名称:mediadrop,代码行数:52,代码来源:media.py

示例5: explore

    def explore(self, **kwargs):
        """Display the most recent 15 media.

        :rtype: Dict
        :returns:
            latest
                Latest media
            popular
                Latest media

        """
        media = Media.query.published()

        latest = media.order_by(Media.publish_on.desc())
        popular = media.order_by(Media.popularity_points.desc())

        featured = None
        is_featured_item_enabled = request.settings['appearance_enable_featured_items'] or request.settings['appearance_enable_cooliris']
        if is_featured_item_enabled:
            featured_cat = helpers.get_featured_category()
            if featured_cat:
                featured = viewable_media(latest.in_category(featured_cat)).first()
            if not featured:
                featured = viewable_media(popular).first()

        nr_latest_items = 8
        if is_featured_item_enabled:
            nr_popular_items = max(nr_latest_items - 3, 0)
        else:
            nr_popular_items = nr_latest_items
        popular = viewable_media(popular.exclude(featured))[:nr_popular_items]
        latest = viewable_media(latest.exclude(featured, popular))[:nr_latest_items]
        if request.settings['sitemaps_display'] == 'True':
            response.feed_links.extend([
                (url_for(controller='/sitemaps', action='google'), _(u'Sitemap XML')),
                (url_for(controller='/sitemaps', action='mrss'), _(u'Sitemap RSS')),
            ])
        if request.settings['rss_display'] == 'True':
            response.feed_links.extend([
                (url_for(controller='/sitemaps', action='latest'), _(u'Latest RSS')),
            ])

        return dict(
            featured = featured,
            latest = latest,
            popular = popular,
            categories = Category.query.populated_tree(),
        )
开发者ID:FelixSchwarz,项目名称:mediadrop-test-renames,代码行数:48,代码来源:media.py

示例6: view

    def view(self, slug, page=1, show='latest', **kwargs):
        """View a podcast and the media that belongs to it.

        :param slug: A :attr:`~mediadrop.model.podcasts.Podcast.slug`
        :param page: Page number, defaults to 1.
        :type page: int
        :rtype: dict
        :returns:
            podcast
                A :class:`~mediadrop.model.podcasts.Podcast` instance.
            episodes
                A list of :class:`~mediadrop.model.media.Media` instances
                that belong to the ``podcast``.
            podcasts
                A list of all the other podcasts

        """
        podcast = fetch_row(Podcast, slug=slug)
        episodes = podcast.media.published()

        episodes, show = helpers.filter_library_controls(episodes, show)

        episodes = viewable_media(episodes)
        
        if request.settings['rss_display'] == 'True':
            response.feed_links.append(
               (url_for(action='feed'), podcast.title)
            )

        return dict(
            podcast = podcast,
            episodes = episodes,
            result_count = episodes.count(),
            show = show,
        )
开发者ID:GitReadysoft,项目名称:mediadrop,代码行数:35,代码来源:podcasts.py

示例7: tindex

    def tindex(self, **kwargs):
        """Display the upload form.

        :rtype: Dict
        :returns:
            legal_wording
                XHTML legal wording for rendering
            support_email
                An help contact address
            upload_form
                The :class:`~mediadrop.forms.uploader.UploadForm` instance
            form_values
                ``dict`` form values, if any

        """
        support_emails = request.settings['email_support_requests']
        support_emails = email.parse_email_string(support_emails)
        support_email = support_emails and support_emails[0] or None

        return dict(
            legal_wording = request.settings['wording_user_uploads'],
            support_email = support_email,
            upload_form = UploadForm(
                action = url_for(controller='/upload', action='tsubmit'),
            ),
            form_values = kwargs,
        )
开发者ID:anitahitouch,项目名称:mediadrop,代码行数:27,代码来源:upload.py

示例8: edit

    def edit(self, id, **kwargs):
        """Display the :class:`~mediadrop.forms.admin.groups.GroupForm` for editing or adding.

        :param id: Group ID
        :type id: ``int`` or ``"new"``
        :rtype: dict
        :returns:
            user
                The :class:`~mediadrop.model.auth.Group` instance we're editing.
            user_form
                The :class:`~mediadrop.forms.admin.groups.GroupForm` instance.
            user_action
                ``str`` form submit url
            group_values
                ``dict`` form values

        """
        group = fetch_row(Group, id)

        if tmpl_context.action == "save" or id == "new":
            # Use the values from error_handler or GET for new groups
            group_values = kwargs
        else:
            permission_ids = map(lambda permission: permission.permission_id, group.permissions)
            group_values = dict(
                display_name=group.display_name, group_name=group.group_name, permissions=permission_ids
            )

        return dict(group=group, group_form=group_form, group_action=url_for(action="save"), group_values=group_values)
开发者ID:njZhuMin,项目名称:mediacore-community,代码行数:29,代码来源:groups.py

示例9: submit_async

    def submit_async(self, **kwargs):
        """Ajax form validation and/or submission.

        This is the save handler for :class:`~mediadrop.forms.media.UploadForm`.

        When ajax is enabled this action is called for each field as the user
        fills them in. Although the entire form is validated, the JS only
        provides the value of one field at a time,

        :param validate: A JSON list of field names to check for validation
        :parma \*\*kwargs: One or more form field values.
        :rtype: JSON dict
        :returns:
            :When validating one or more fields:

            valid
                bool
            err
                A dict of error messages keyed by the field names

            :When saving an upload:

            success
                bool
            redirect
                If valid, the redirect url for the upload successful page.

        """
        if "validate" in kwargs:
            # we're just validating the fields. no need to worry.
            fields = json.loads(kwargs["validate"])
            err = {}
            for field in fields:
                if field in tmpl_context.form_errors:
                    err[field] = tmpl_context.form_errors[field]

            data = dict(valid=len(err) == 0, err=err)
        else:
            # We're actually supposed to save the fields. Let's do it.
            if len(tmpl_context.form_errors) != 0:
                # if the form wasn't valid, return failure
                tmpl_context.form_errors["success"] = False
                data = tmpl_context.form_errors
            else:
                # else actually save it!
                kwargs.setdefault("name")

                media_obj = self.save_media_obj(
                    kwargs["name"],
                    kwargs["email"],
                    kwargs["title"],
                    kwargs["description"],
                    None,
                    kwargs["file"],
                    kwargs["url"],
                )
                email.send_media_notification(media_obj)
                data = dict(success=True, redirect=url_for(action="success"))

        return data
开发者ID:njZhuMin,项目名称:mediacore-community,代码行数:60,代码来源:upload.py

示例10: save

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

        See :class:`~mediadrop.forms.admin.settings.categories.CategoryForm` for POST vars.

        :param id: Category ID
        :param delete: If true the category is to be deleted rather than saved.
        :type delete: bool
        :rtype: JSON dict
        :returns:
            success
                bool

        """
        if tmpl_context.form_errors:
            if request.is_xhr:
                return dict(success=False, errors=tmpl_context.form_errors)
            else:
                # TODO: Add error reporting for users with JS disabled?
                return redirect(action="edit")

        cat = fetch_row(Category, id)

        if delete:
            DBSession.delete(cat)
            data = dict(success=True, id=cat.id, parent_options=unicode(category_form.c["parent_id"].display()))
        else:
            cat.name = kwargs["name"]
            cat.slug = get_available_slug(Category, kwargs["slug"], cat)

            if kwargs["parent_id"]:
                parent = fetch_row(Category, kwargs["parent_id"])
                if parent is not cat and cat not in parent.ancestors():
                    cat.parent = parent
            else:
                cat.parent = None

            DBSession.add(cat)
            DBSession.flush()

            data = dict(
                success=True,
                id=cat.id,
                name=cat.name,
                slug=cat.slug,
                parent_id=cat.parent_id,
                parent_options=unicode(category_form.c["parent_id"].display()),
                depth=cat.depth(),
                row=unicode(
                    category_row_form.display(
                        action=url_for(id=cat.id), category=cat, depth=cat.depth(), first_child=True
                    )
                ),
            )

        if request.is_xhr:
            return data
        else:
            redirect(action="index", id=None)
开发者ID:GitReadysoft,项目名称:mediadrop,代码行数:59,代码来源:categories.py

示例11: post_login

 def post_login(self, came_from=None, **kwargs):
     if not request.identity:
         # The FriendlyForm plugin will always issue a redirect to 
         # /login/continue (post login url) even for failed logins.
         # If 'came_from' is a protected page (i.e. /admin) we could just 
         # redirect there and the login form will be displayed again with
         # our login error message.
         # However if the user tried to login from the front page, this 
         # mechanism doesn't work so go to the login method directly here.
         self._increase_number_of_failed_logins()
         return self.login(came_from=came_from)
     if came_from:
         redirect(came_from)
     # It is important to return absolute URLs (if app mounted in subdirectory)
     if request.perm.contains_permission(u'edit') or request.perm.contains_permission(u'admin'):
         redirect(url_for('/admin', qualified=True))
     redirect(url_for('/', qualified=True))
开发者ID:GitReadysoft,项目名称:mediadrop,代码行数:17,代码来源:login.py

示例12: google

    def google(self, page=None, limit=10000, **kwargs):
        """Generate a sitemap which contains googles Video Sitemap information.

        This action may return a <sitemapindex> or a <urlset>, depending
        on how many media items are in the database, and the values of the
        page and limit params.

        :param page: Page number, defaults to 1.
        :type page: int
        :param page: max records to display on page, defaults to 10000.
        :type page: int

        """
        if request.settings['sitemaps_display'] != 'True':
            abort(404)

        response.content_type = \
            content_type_for_response(['application/xml', 'text/xml'])

        media = viewable_media(Media.query.published())

        if page is None:
            if media.count() > limit:
                return dict(pages=math.ceil(media.count() / float(limit)))
        else:
            page = int(page)
            media = media.offset(page * limit).limit(limit)

        if page:
            links = []
        else:
            links = [
                url_for(controller='/', qualified=True),
                url_for(controller='/media', show='popular', qualified=True),
                url_for(controller='/media', show='latest', qualified=True),
                url_for(controller='/categories', qualified=True),
            ]

        return dict(
            media = media,
            page = page,
            links = links,
        )
开发者ID:JaydenChou,项目名称:mediadrop,代码行数:43,代码来源:sitemaps.py

示例13: update_status

    def update_status(self, id, status=None, publish_on=None, publish_until=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:`~mediadrop.model.media.Media.status` should change.
        :type update_status: ``unicode`` or ``None``
        :param publish_on: A date to set to
            :attr:`~mediadrop.model.media.Media.publish_on`
        :type publish_on: :class:`datetime.datetime` or ``None``
        :param publish_until: A date to set to
            :attr:`~mediadrop.model.media.Media.publish_until`
        :type publish_until: :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 status == 'unreviewed':
            media.reviewed = True
        elif status == 'draft':
            self._publish_media(media, publish_on)
        elif publish_on:
            media.publish_on = publish_on
            media.update_popularity()
        elif publish_until:
            media.publish_until = publish_until

        # 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:knyar,项目名称:mediadrop,代码行数:54,代码来源:media.py

示例14: edit

    def edit(self, id, name=None, **kwargs):
        """Display the :class:`~mediadrop.model.players.PlayerPrefs` for editing or adding.

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

        """
        playerp = fetch_row(PlayerPrefs, id)

        return {
            'player': playerp,
            'form': playerp.settings_form,
            'form_action': url_for(action='save'),
            'form_values': kwargs,
        }
开发者ID:FelixSchwarz,项目名称:mediadrop-test-renames,代码行数:17,代码来源:players.py

示例15: edit

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

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

        """
        engine = self.fetch_engine(id, engine_type)

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


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