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


Python url.URL类代码示例

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


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


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