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

Python url.URL类代码示例

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

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



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

示例1: test_url

    def test_url(self):
        """
        An L{URL} object is flattened to the appropriate representation of
        itself, whether it is the child of a tag or the value of a tag
        attribute.
        """
        link = URL.fromString("http://foo/fu?bar=baz&bar=baz#quux%2f")
        self.assertStringEqual(
            self.flatten(link),
            "http://foo/fu?bar=baz&bar=baz#quux%2F")
        self.assertStringEqual(
            self.flatten(div[link]),
            '<div>http://foo/fu?bar=baz&amp;bar=baz#quux%2F</div>')
        self.assertStringEqual(
            self.flatten(div(foo=link)),
            '<div foo="http://foo/fu?bar=baz&amp;bar=baz#quux%2F"></div>')
        self.assertStringEqual(
            self.flatten(div[div(foo=link)]),
            '<div><div foo="http://foo/fu?bar=baz&amp;bar=baz#quux%2F"></div>'
            '</div>')

        link = URL.fromString("http://foo/fu?%2f=%7f")
        self.assertStringEqual(
            self.flatten(link),
            "http://foo/fu?%2F=%7F")
        self.assertStringEqual(
            self.flatten(div[link]),
            '<div>http://foo/fu?%2F=%7F</div>')
        self.assertStringEqual(
            self.flatten(div(foo=link)),
            '<div foo="http://foo/fu?%2F=%7F"></div>')
开发者ID:UstadMobile,项目名称:exelearning-ustadmobile-work,代码行数:31,代码来源:test_newflat.py


示例2: test_getSelectedTabExactMatch

    def test_getSelectedTabExactMatch(self):
        """
        Check that L{webnav.getSelectedTab} returns the tab whose C{linkURL}
        attribute exactly matches the path of the L{nevow.url.URL} it is passed
        """

        tabs = list(webnav.Tab(str(i), None, 0, linkURL="/" + str(i)) for i in xrange(5))

        for (i, tab) in enumerate(tabs):
            selected = webnav.getSelectedTab(tabs, URL.fromString(tab.linkURL))
            self.assertIdentical(selected, tab)

        selected = webnav.getSelectedTab(tabs, URL.fromString("/XYZ"))
        self.failIf(selected)
开发者ID:fusionapp,项目名称:mantissa,代码行数:14,代码来源:test_webnav.py


示例3: locateChild

    def locateChild(self, ctx, segments):
        """
        Look up children in the normal manner, but then customize them for the
        authenticated user if they support the L{ICustomizable} interface.  If
        the user is attempting to access a private URL, redirect them.
        """
        result = self._getAppStoreResource(ctx, segments[0])
        if result is not None:
            child, segments = result, segments[1:]
            return child, segments

        if segments[0] == '':
            result = self.child_(ctx)
            if result is not None:
                child, segments = result, segments[1:]
                return child, segments

        # If the user is trying to access /private/*, then his session has
        # expired or he is otherwise not logged in. Redirect him to /login,
        # preserving the URL segments, rather than giving him an obscure 404.
        if segments[0] == 'private':
            u = URL.fromContext(ctx).click('/').child('login')
            for seg in segments:
                u = u.child(seg)
            return u, ()

        return rend.NotFound
开发者ID:rcarmo,项目名称:divmod.org,代码行数:27,代码来源:publicweb.py


示例4: test_finish

    def test_finish(self):
        """
        L{StylesheetRewritingRequestWrapper.finish} causes all written bytes to
        be translated with C{_replace} written to the wrapped request.
        """
        stylesheetFormat = """
            .foo {
                background-image: url(%s)
            }
        """
        originalStylesheet = stylesheetFormat % ("/Foo/bar",)
        expectedStylesheet = stylesheetFormat % ("/bar/Foo/bar",)

        request = FakeRequest()
        roots = {request: URL.fromString('/bar/')}
        wrapper = website.StylesheetRewritingRequestWrapper(
            request, [], roots.get)
        wrapper.write(originalStylesheet)
        wrapper.finish()
        # Parse and serialize both versions to normalize whitespace so we can
        # make a comparison.
        parser = CSSParser()
        self.assertEqual(
            parser.parseString(request.accumulator).cssText,
            parser.parseString(expectedStylesheet).cssText)
开发者ID:twisted,项目名称:mantissa,代码行数:25,代码来源:test_website.py


示例5: __init__

    def __init__(self, url, tries=10, timeout=defaultTimeout, *a, **kw):
        """
        Prepare the download information.

        Any additional positional or keyword arguments are passed on to
        C{twisted.web.client.HTTPPageGetter}.

        @type url: C{nevow.url.URL} or C{unicode} or C{str}
        @param url: The HTTP URL to attempt to download

        @type tries: C{int}
        @param tries: The maximum number of retry attempts before giving up

        @type timeout: C{float}
        @param timeout: Timeout value, in seconds, for the page fetch;
            defaults to L{defaultTimeout}
        """
        if isinstance(url, unicode):
            url = url.encode('utf-8')
        if isinstance(url, str):
            url = URL.fromString(url)

        self.url = url.anchor(None)
        self.args = a
        self.kwargs = kw
        self.delay = self.initialDelay
        self.tries = tries
        self.timeout = timeout
开发者ID:mithrandi,项目名称:eridanus,代码行数:28,代码来源:util.py


示例6: checkid_setup

def checkid_setup(registry, requestData, user=None):
	"""
	This method will validate and redirect a successful request to its
	return_to param. If the user isn't logged in, or doesn't have an account,
	we'll redirect to an internal page.
	
	@param registry: the current OpenID registry
	@type registry: L{OpenIDRegistry}
	
	@param requestData: the current request data
	@type requestData: L{OpenIDRequest}
	
	@param user: the current user
	@type user: L{txopenid.user.User}
	
	@return: association response
	@rtype: L{nevow.url.URL}
	"""
	if(user is not None):
		def _identity_state():
			return user.hasIdentity(requestData['openid.identity'])
		
		def _trust_state():
			 return user.trustsRoot(requestData['openid.trust_root'])
		
		if not(yield maybeDeferred(_identity_state)):
			return_to = util.appendQuery(OPENID_IDENTITY_URL, requestData)
		elif not(yield maybeDeferred(_trust_state)):
			return_to = util.appendQuery(OPENID_TRUST_URL, requestData)
		else:
			return_to = get_login_response(registry, requestData)
	else:
		return_to = util.appendQuery(OPENID_LOGIN_URL, requestData)
	
	returnValue(URL.fromString(return_to))
开发者ID:iffy,项目名称:txOpenID,代码行数:35,代码来源:protocol.py


示例7: rendered

    def rendered(request):
        if request.redirected_to is None:
            result.callback(request)
        else:
            visited.append(request.redirected_to)

            if visited.index(request.redirected_to) != len(visited) - 1:
                visited.append(request.redirected_to)
                result.errback(Exception("Redirect loop: %r" % (visited,)))
            elif len(visited) > redirectLimit:
                result.errback(Exception("Too many redirects: %r" % (visited,)))
            else:
                newHeaders = headers.copy()

                # Respect redirects
                location = URL.fromString(request.redirected_to)
                newHeaders['host'] = location.netloc

                # Respect cookies
                cookies.update(request.cookies)

                # str(URL) shouldn't really do what it does.
                page = getResource(
                    site, str(location), newHeaders, cookies)
                page.addCallbacks(rendered, result.errback)
开发者ID:fusionapp,项目名称:mantissa,代码行数:25,代码来源:test_web.py


示例8: test_getJSModuleURL

    def test_getJSModuleURL(self):
        """
        L{MantissaLivePage.getJSModuleURL} should return a child of its
        C{_moduleRoot} attribute of the form::

            _moduleRoot/<SHA1 digest of module contents>/Package.ModuleName
        """
        module = 'Mantissa'
        url = URL(scheme='https', netloc='example.com', pathsegs=['foo'])
        page = MantissaLivePage(None)
        page._moduleRoot = url
        jsDir = FilePath(__file__).parent().parent().child("js")
        modulePath = jsDir.child(module).child("__init__.js")
        moduleContents = modulePath.open().read()
        expect = sha1(moduleContents).hexdigest()
        self.assertEqual(page.getJSModuleURL(module),
                         url.child(expect).child(module))
开发者ID:twisted,项目名称:mantissa,代码行数:17,代码来源:test_website.py


示例9: test_beforeRenderSetsModuleRoot

 def test_beforeRenderSetsModuleRoot(self):
     """
     L{MantissaLivePage.beforeRender} should set I{_moduleRoot} to the
     C{__jsmodule__} child of the URL returned by the I{rootURL}
     method of the L{WebSite} it wraps.
     """
     receivedRequests = []
     root = URL(netloc='example.com', pathsegs=['a', 'b'])
     class FakeWebSite(object):
         def rootURL(self, request):
             receivedRequests.append(request)
             return root
     request = FakeRequest()
     page = MantissaLivePage(FakeWebSite())
     page.beforeRender(request)
     self.assertEqual(receivedRequests, [request])
     self.assertEqual(page._moduleRoot, root.child('__jsmodule__'))
开发者ID:twisted,项目名称:mantissa,代码行数:17,代码来源:test_website.py


示例10: test_parseURLs

 def test_parseURLs(self):
     """
     L{eridanus.iriparse.parseURL} extracts and parses (as a
     L{nevow.url.URL}) all URIs in a string.
     """
     self.assertEquals(
         list(iriparse.parseURLs(u'http://google.com/')),
         [URL.fromString(u'http://google.com/')])
开发者ID:mithrandi,项目名称:eridanus,代码行数:8,代码来源:test_iriparse.py


示例11: test_parseURL

 def test_parseURL(self):
     """
     L{eridanus.iriparse.parseURL} extracts and parses (as a
     L{nevow.url.URL}) the first URI in a string.
     """
     self.assertEquals(
         iriparse.parseURL(
             u'http://google.com/ http://foo.bar/ world'),
         URL.fromString(u'http://google.com/'))
开发者ID:mithrandi,项目名称:eridanus,代码行数:9,代码来源:test_iriparse.py


示例12: evaluate

 def evaluate(self, expn):
     """
     Evaluate an expression.
     """
     url = URL.fromString('http://www.google.com/search?')
     url = url.add('q', expn + '=')
     url = url.add('num', '1')
     d = self._fetch(url)
     d.addCallback(self._extractResult, expn)
     return d
开发者ID:mithrandi,项目名称:eridanus,代码行数:10,代码来源:google.py


示例13: renderHTTP

    def renderHTTP(self, ctx):
        """
        Handle the password reset form.

        The following exchange describes the process:

            S: Render C{reset}
            C: POST C{username} or C{email}
            S: L{handleRequestForUser}, render C{reset-check-email}

            (User follows the emailed reset link)

            S: Render C{reset-step-two}
            C: POST C{password1}
            S: L{resetPassword}, render C{reset-done}
        """
        req = inevow.IRequest(ctx)

        if req.method == 'POST':
            if req.args.get('username', [''])[0]:
                user = unicode(usernameFromRequest(req), 'ascii')
                self.handleRequestForUser(user, URL.fromContext(ctx))
                self.fragment = self.templateResolver.getDocFactory(
                    'reset-check-email')
            elif req.args.get('email', [''])[0]:
                email = req.args['email'][0].decode('ascii')
                acct = self.accountByAddress(email)
                if acct is not None:
                    username = '@'.join(
                        userbase.getAccountNames(acct.avatars.open()).next())
                    self.handleRequestForUser(username, URL.fromContext(ctx))
                self.fragment = self.templateResolver.getDocFactory('reset-check-email')
            elif 'password1' in req.args:
                (password,) = req.args['password1']
                self.resetPassword(self.attempt, unicode(password))
                self.fragment = self.templateResolver.getDocFactory('reset-done')
            else:
                # Empty submit;  redirect back to self
                return URL.fromContext(ctx)
        elif self.attempt:
            self.fragment = self.templateResolver.getDocFactory('reset-step-two')

        return PublicPage.renderHTTP(self, ctx)
开发者ID:fusionapp,项目名称:mantissa,代码行数:43,代码来源:signup.py


示例14: childFactory

 def childFactory(self, ctx, name):
     for T in self.original.store.query(
         Ticket,
         AND(Ticket.booth == self.original,
             Ticket.nonce == unicode(name, 'ascii'))):
         something = T.claim()
         res = IResource(something)
         lgo = getattr(res, 'logout', lambda : None)
         ISession(ctx).setDefaultResource(res, lgo)
         return URL.fromContext(ctx).click("/private")
     return None
开发者ID:fusionapp,项目名称:mantissa,代码行数:11,代码来源:signup.py


示例15: test_replaceMantissa

 def test_replaceMantissa(self):
     """
     L{StylesheetRewritingRequestWrapper._replace} changes URLs of the form
     I{/Mantissa/foo} to I{<rootURL>/static/mantissa-base/foo}.
     """
     request = object()
     roots = {request: URL.fromString('/bar/')}
     wrapper = website.StylesheetRewritingRequestWrapper(request, [], roots.get)
     self.assertEqual(
         wrapper._replace('/Mantissa/foo.png'),
         '/bar/static/mantissa-base/foo.png')
开发者ID:twisted,项目名称:mantissa,代码行数:11,代码来源:test_website.py


示例16: test_replaceOtherOffering

 def test_replaceOtherOffering(self):
     """
     L{StylesheetRewritingRequestWrapper._replace} changes URLs of the form
     I{/Something/foo} to I{<rootURL>/static/Something/foo} if C{Something}
     gives the name of an installed offering with a static content path.
     """
     request = object()
     roots = {request: URL.fromString('/bar/')}
     wrapper = website.StylesheetRewritingRequestWrapper(request, ['OfferingName'], roots.get)
     self.assertEqual(
         wrapper._replace('/OfferingName/foo.png'),
         '/bar/static/OfferingName/foo.png')
开发者ID:twisted,项目名称:mantissa,代码行数:12,代码来源:test_website.py


示例17: rootChild_resetPassword

    def rootChild_resetPassword(self, req, webViewer):
        """
        Redirect authenticated users to their settings page (hopefully they
        have one) when they try to reset their password.

        This is the wrong way for this functionality to be implemented.  See
        #2524.
        """
        from xmantissa.ixmantissa import IWebTranslator, IPreferenceAggregator
        return URL.fromString(
            IWebTranslator(self.store).linkTo(
                IPreferenceAggregator(self.store).storeID))
开发者ID:rcarmo,项目名称:divmod.org,代码行数:12,代码来源:website.py


示例18: test_shortURL

 def test_shortURL(self):
     """
     L{StylesheetRewritingRequestWrapper._replace} changes URLs with only
     one segment so they are beneath the root URL.
     """
     request = object()
     roots = {request: URL.fromString('/bar/')}
     wrapper = website.StylesheetRewritingRequestWrapper(
         request, [], roots.get)
     self.assertEqual(
         wrapper._replace('/'),
         '/bar/')
开发者ID:twisted,项目名称:mantissa,代码行数:12,代码来源:test_website.py


示例19: test_nonOfferingOnlyGivenPrefix

 def test_nonOfferingOnlyGivenPrefix(self):
     """
     L{StylesheetRewritingRequestWrapper._replace} only changes URLs of the
     form I{/Something/foo} so they are beneath the root URL if C{Something}
     does not give the name of an installed offering.
     """
     request = object()
     roots = {request: URL.fromString('/bar/')}
     wrapper = website.StylesheetRewritingRequestWrapper(
         request, ['Foo'], roots.get)
     self.assertEqual(
         wrapper._replace('/OfferingName/foo.png'),
         '/bar/OfferingName/foo.png')
开发者ID:twisted,项目名称:mantissa,代码行数:13,代码来源:test_website.py


示例20: test_segments

 def test_segments(self):
     """
     L{LoginPage.beforeRender} should fill the I{login-action} slot with an
     L{URL} which includes all the segments given to the L{LoginPage}.
     """
     segments = ('foo', 'bar')
     page = LoginPage(self.siteStore, segments)
     page.beforeRender(self.context)
     loginAction = self.context.locateSlotData('login-action')
     expectedLocation = URL.fromString('/')
     for segment in (LOGIN_AVATAR,) + segments:
         expectedLocation = expectedLocation.child(segment)
     self.assertEqual(loginAction, expectedLocation)
开发者ID:twisted,项目名称:mantissa,代码行数:13,代码来源:test_website.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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