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


Python urls.url_parse函数代码示例

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


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

示例1: test_fileurl_parsing_windows

def test_fileurl_parsing_windows(implicit_format, localhost, monkeypatch):
    if implicit_format:
        pathformat = None
        monkeypatch.setattr('os.name', 'nt')
    else:
        pathformat = 'windows'
        monkeypatch.delattr('os.name')  # just to make sure it won't get used

    url = urls.url_parse('file:///C:/Documents and Settings/Foobar/stuff.txt')
    assert url.netloc == ''
    assert url.scheme == 'file'
    assert url.get_file_location(pathformat) == \
        (None, r'C:\Documents and Settings\Foobar\stuff.txt')

    url = urls.url_parse('file://///server.tld/file.txt')
    assert url.get_file_location(pathformat) == ('server.tld', r'file.txt')

    url = urls.url_parse('file://///server.tld')
    assert url.get_file_location(pathformat) == ('server.tld', '')

    url = urls.url_parse('file://///%s' % localhost)
    assert url.get_file_location(pathformat) == (None, '')

    url = urls.url_parse('file://///%s/file.txt' % localhost)
    assert url.get_file_location(pathformat) == (None, r'file.txt')
开发者ID:2009bpy,项目名称:werkzeug,代码行数:25,代码来源:test_urls.py

示例2: test_fileurl_parsing_windows

def test_fileurl_parsing_windows(implicit_format, localhost, monkeypatch):
    if implicit_format:
        pathformat = None
        monkeypatch.setattr("os.name", "nt")
    else:
        pathformat = "windows"
        monkeypatch.delattr("os.name")  # just to make sure it won't get used

    url = urls.url_parse("file:///C:/Documents and Settings/Foobar/stuff.txt")
    assert url.netloc == ""
    assert url.scheme == "file"
    assert url.get_file_location(pathformat) == (
        None,
        r"C:\Documents and Settings\Foobar\stuff.txt",
    )

    url = urls.url_parse("file://///server.tld/file.txt")
    assert url.get_file_location(pathformat) == ("server.tld", r"file.txt")

    url = urls.url_parse("file://///server.tld")
    assert url.get_file_location(pathformat) == ("server.tld", "")

    url = urls.url_parse("file://///%s" % localhost)
    assert url.get_file_location(pathformat) == (None, "")

    url = urls.url_parse("file://///%s/file.txt" % localhost)
    assert url.get_file_location(pathformat) == (None, r"file.txt")
开发者ID:pallets,项目名称:werkzeug,代码行数:27,代码来源:test_urls.py

示例3: test_redirect_to_records

    def test_redirect_to_records(self):

        self.company_A = self.env['res.company'].create({
            'name': 'Company A',
            'user_ids': [(4, self.ref('base.user_admin'))],
        })

        self.company_B = self.env['res.company'].create({
            'name': 'Company B',
        })

        self.multi_company_record = self.env['mail.test.multi.company'].create({
            'name': 'Multi Company Record',
            'company_id': self.company_A.id,
        })

        # Test Case 0
        # Not logged, redirect to web/login
        response = self.url_open('/mail/view?model=%s&res_id=%s' % (
            self.multi_company_record._name,
            self.multi_company_record.id), timeout=15)

        path = url_parse(response.url).path
        self.assertEqual(path, '/web/login')

        self.authenticate('admin', 'admin')

        # Test Case 1
        # Logged into company 1, try accessing record in company A
        # _redirect_to_record should add company A in allowed_company_ids
        response = self.url_open('/mail/view?model=%s&res_id=%s' % (
            self.multi_company_record._name,
            self.multi_company_record.id), timeout=15)

        self.assertEqual(response.status_code, 200)

        fragment = url_parse(response.url).fragment
        cids = url_decode(fragment)['cids']

        self.assertEqual(cids, '1,%s' % (self.company_A.id))

        # Test Case 2
        # Logged into company 1, try accessing record in company B
        # _redirect_to_record should redirect to messaging as the user
        # doesn't have any access for this company
        self.multi_company_record.company_id = self.company_B

        response = self.url_open('/mail/view?model=%s&res_id=%s' % (
            self.multi_company_record._name,
            self.multi_company_record.id), timeout=15)

        self.assertEqual(response.status_code, 200)

        fragment = url_parse(response.url).fragment
        action = url_decode(fragment)['action']

        self.assertEqual(action, 'mail.action_discuss')
开发者ID:Vauxoo,项目名称:odoo,代码行数:57,代码来源:test_multi_company.py

示例4: test_replace

def test_replace():
    url = urls.url_parse("http://de.wikipedia.org/wiki/Troll")
    strict_eq(
        url.replace(query="foo=bar"),
        urls.url_parse("http://de.wikipedia.org/wiki/Troll?foo=bar"),
    )
    strict_eq(
        url.replace(scheme="https"),
        urls.url_parse("https://de.wikipedia.org/wiki/Troll"),
    )
开发者ID:pallets,项目名称:werkzeug,代码行数:10,代码来源:test_urls.py

示例5: rewrite_static_url

def rewrite_static_url(path):
    """Remove __vxxx prefix from static URLs."""
    plugin_pattern = _plugin_url_pattern.format(url_parse(config.BASE_URL).path)
    static_pattern = _static_url_pattern.format(url_parse(config.BASE_URL).path)
    custom_pattern = _custom_url_pattern.format(url_parse(config.BASE_URL).path)
    if re.match(plugin_pattern, path):
        return re.sub(plugin_pattern, r'static/plugins/\1/\2.\3', path)
    elif re.match(static_pattern, path):
        return re.sub(static_pattern, r'static/\1\2/\3.\4', path)
    else:
        return re.sub(custom_pattern, r'static/custom/\1', path)
开发者ID:jas01,项目名称:indico,代码行数:11,代码来源:util.py

示例6: parse_redirect

 def parse_redirect(self, location, parse_fragment=False):
     from werkzeug.urls import url_parse, url_decode, url_unparse
     scheme, netloc, script_root, qs, anchor = url_parse(location)
     return (
         url_unparse((scheme, netloc, script_root, '', '')),
         url_decode(anchor if parse_fragment else qs)
     )
开发者ID:adsabs,项目名称:adsws,代码行数:7,代码来源:api_base.py

示例7: resolve_redirect

    def resolve_redirect(self, response, new_location, environ, buffered=False):
        """Resolves a single redirect and triggers the request again
        directly on this redirect client.
        """
        scheme, netloc, script_root, qs, anchor = url_parse(new_location)
        base_url = url_unparse((scheme, netloc, "", "", "")).rstrip("/") + "/"

        cur_server_name = netloc.split(":", 1)[0].split(".")
        real_server_name = get_host(environ).rsplit(":", 1)[0].split(".")

        if self.allow_subdomain_redirects:
            allowed = cur_server_name[-len(real_server_name) :] == real_server_name
        else:
            allowed = cur_server_name == real_server_name

        if not allowed:
            raise RuntimeError("%r does not support redirect to " "external targets" % self.__class__)

        # For redirect handling we temporarily disable the response
        # wrapper.  This is not threadsafe but not a real concern
        # since the test client must not be shared anyways.
        old_response_wrapper = self.response_wrapper
        self.response_wrapper = None
        try:
            return self.open(path=script_root, base_url=base_url, query_string=qs, as_tuple=True, buffered=buffered)
        finally:
            self.response_wrapper = old_response_wrapper
开发者ID:forwhat,项目名称:Werkzeug-docs-cn,代码行数:27,代码来源:tests.py

示例8: subscribe

    def subscribe(self, request, writer):
        content_type = request.get('content-type')
        if content_type != 'text/html':
            raise WebsocketBadRequest('unknown content type',
                                      **{'content-type': content_type})
        channel_url = request.get('channel')
        index = request.get('index')
        if not channel_url:
            raise WebsocketBadRequest('no channel specified', index=index)
        url = url_parse(channel_url)
        channel = url.path
        try:
            view = yield from self.root[channel]
        except LookupError:
            raise WebsocketBadRequest('no such channel',
                                      index=index, channel=channel)
        try:
            sub = view.ws_subscribe
        except AttributeError:
            raise WebsocketBadRequest('not a channel',
                                      index=index, channel=channel)
        last_stamp = request.get('last_stamp')

        def send(**data):
            data.setdefault('action', 'push')
            data['index'] = index
            data['channel'] = channel
            writer.send(json.dumps(data))

        task = asyncio.Task(view.ws_subscribe(send, last_stamp,
                                              options=url.decode_query()))
        return index, task.cancel
开发者ID:encukou,项目名称:galerka,代码行数:32,代码来源:websocket_server.py

示例9: _replace_local_links

    def _replace_local_links(self, html):
        """ Post-processing of html content to replace local links to absolute
        links, using web.base.url as base url. """
        if not html:
            return html

        # form a tree
        root = lxml.html.fromstring(html)
        if not len(root) and root.text is None and root.tail is None:
            html = '<div>%s</div>' % html
            root = lxml.html.fromstring(html)

        base_url = self.env['ir.config_parameter'].sudo().get_param('web.base.url')
        base = urls.url_parse(base_url)

        def _process_link(url):
            new_url = urls.url_parse(url)
            if new_url.scheme and new_url.netloc:
                return url
            return new_url.replace(scheme=base.scheme, netloc=base.netloc).to_url()

        # check all nodes, replace :
        # - img src -> check URL
        # - a href -> check URL
        for node in root.iter():
            if node.tag == 'a' and node.get('href'):
                node.set('href', _process_link(node.get('href')))
            elif node.tag == 'img' and not node.get('src', 'data').startswith('data'):
                node.set('src', _process_link(node.get('src')))

        html = lxml.html.tostring(root, pretty_print=False, method='html')
        # this is ugly, but lxml/etree tostring want to put everything in a 'div' that breaks the editor -> remove that
        if html.startswith('<div>') and html.endswith('</div>'):
            html = html[5:-6]
        return html
开发者ID:a8992030,项目名称:odoo,代码行数:35,代码来源:mail_template.py

示例10: route_from

    def route_from(url, method=None):
        appctx = _app_ctx_stack.top
        reqctx = _request_ctx_stack.top
        if appctx is None:
            raise RuntimeError(
                "Attempted to match a URL without the "
                "application context being pushed. This has to be "
                "executed when application context is available."
            )

        if reqctx is not None:
            url_adapter = reqctx.url_adapter
        else:
            url_adapter = appctx.url_adapter
            if url_adapter is None:
                raise RuntimeError(
                    "Application was not able to create a URL "
                    "adapter for request independent URL matching. "
                    "You might be able to fix this by setting "
                    "the SERVER_NAME config variable."
                )
        parsed_url = url_parse(url)
        if parsed_url.netloc is not "" and parsed_url.netloc != url_adapter.server_name:
            raise NotFound()
        return url_adapter.match(parsed_url.path, method)
开发者ID:hvprash,项目名称:Flask-AppBuilder,代码行数:25,代码来源:baseviews.py

示例11: link

 def link(self, link, title, text):
     if self.record is not None:
         url = url_parse(link)
         if not url.scheme:
             link = self.record.url_to('!' + link,
                                       base_url=get_ctx().base_url)
     return mistune.Renderer.link(self, link, title, text)
开发者ID:BogusCurry,项目名称:lektor,代码行数:7,代码来源:markdown.py

示例12: test_link_tracker

    def test_link_tracker(self):
        _url = 'https://www.example.com/foo/bar?baz=qux'
        mailing = self.env['mail.mass_mailing'].create({
            'name': 'TestMailing',
            'medium_id': self.test_medium.id,
            'body_html': '<p>Hello <a role="button" href="%s">${object.name}</a><a role="button" href="/unsubscribe_from_list">Unsubscribe</a></p>' % _url,
            'reply_to_mode': 'email',
            'mailing_model_id': self.ref('test_mass_mailing.model_mass_mail_test_bl'),
            'mailing_domain': [('id', 'in', self.mm_recs.ids)],
        })

        mailing.send_mail()

        # basic test emails are sent
        self.assertEqual(mailing.sent, 5)
        self.assertEqual(mailing.delivered, 5)

        # link trackers
        links = self.env['link.tracker'].sudo().search([('mass_mailing_id', '=', mailing.id)])
        self.assertEqual(len(links), 1)
        self.assertEqual(links.mapped('url'), [_url])
        # check UTMS are correctly set on redirect URL
        redirect_url = urls.url_parse(links.redirected_url)
        redirect_params = redirect_url.decode_query().to_dict(flat=True)
        self.assertEqual(redirect_url.scheme, 'https')
        self.assertEqual(redirect_url.decode_netloc(), 'www.example.com')
        self.assertEqual(redirect_url.path, '/foo/bar')
        self.assertEqual(redirect_params, {
            'utm_source': mailing.name,
            'utm_medium': self.test_medium.name,
            'baz': 'qux',
        })
开发者ID:Gorrice,项目名称:odoo,代码行数:32,代码来源:test_mass_mailing.py

示例13: configure_app

def configure_app(app, set_path=False):
    cfg = Config.getInstance()
    app.config['PROPAGATE_EXCEPTIONS'] = True
    app.config['SESSION_COOKIE_NAME'] = 'indico_session'
    app.config['PERMANENT_SESSION_LIFETIME'] = cfg.getSessionLifetime()
    app.config['INDICO_SESSION_PERMANENT'] = cfg.getSessionLifetime() > 0
    app.config['INDICO_HTDOCS'] = cfg.getHtdocsDir()
    app.config['INDICO_COMPAT_ROUTES'] = cfg.getRouteOldUrls()
    if set_path:
        base = url_parse(cfg.getBaseURL())
        app.config['SERVER_NAME'] = base.netloc
        if base.path:
            app.config['APPLICATION_ROOT'] = base.path
    static_file_method = cfg.getStaticFileMethod()
    if static_file_method:
        app.config['USE_X_SENDFILE'] = True
        method, args = static_file_method
        if method in ('xsendfile', 'lighttpd'):  # apache mod_xsendfile, lighttpd
            pass
        elif method in ('xaccelredirect', 'nginx'):  # nginx
            if not args or not hasattr(args, 'items'):
                raise ValueError('StaticFileMethod args must be a dict containing at least one mapping')
            app.wsgi_app = XAccelMiddleware(app.wsgi_app, args)
        else:
            raise ValueError('Invalid static file method: %s' % method)
开发者ID:Ictp,项目名称:indico,代码行数:25,代码来源:app.py

示例14: match_url

def match_url(url, method=None):
    """Get endpoint and arguments from a url.

    SEE http://stackoverflow.com/questions/19631335/reverting-a-url-in-flask

    Returns:
        endpoint name (str?)
        arguments (dict).
    """
    appctx = _app_ctx_stack.top
    reqctx = _request_ctx_stack.top
    if appctx is None:
        raise RuntimeError('Attempted to match a URL without the '
                           'application context being pushed. This has to be '
                           'executed when application context is available.')

    if reqctx is not None:
        url_adapter = reqctx.url_adapter
    else:
        url_adapter = appctx.url_adapter
        if url_adapter is None:
            raise RuntimeError('Application was not able to create a URL '
                               'adapter for request independent URL matching. '
                               'You might be able to fix this by setting '
                               'the SERVER_NAME config variable.')
    parsed_url = url_parse(url)
    if parsed_url.netloc is not '' and \
            parsed_url.netloc != url_adapter.server_name:
        raise NotFound()
    return url_adapter.match(parsed_url.path, method)
开发者ID:sggaffney,项目名称:pathscore,代码行数:30,代码来源:helpers.py

示例15: _sendReport

    def _sendReport( self ):
        cfg = Config.getInstance()

        # if no e-mail address was specified,
        # add a default one
        if self._userMail:
            fromAddr = self._userMail
        else:
            fromAddr = '[email protected]'

        toAddr = Config.getInstance().getSupportEmail()
        Logger.get('errorReport').debug('mailing %s' % toAddr)
        subject = "[[email protected]{}] Error report".format(url_parse(cfg.getBaseURL()).netloc)

        request_info = self._requestInfo or ''
        if isinstance(request_info, (dict, list)):
            request_info = pformat(request_info)

        # build the message body
        body = [
            "-" * 20,
            "Error details\n",
            self._code,
            self._message,
            "Inner error: " + str(self._inner),
            request_info,
            "-" * 20
        ]
        maildata = {"fromAddr": fromAddr, "toList": [toAddr], "subject": subject, "body": "\n".join(body)}
        GenericMailer.send(GenericNotification(maildata))
开发者ID:OmeGak,项目名称:indico,代码行数:30,代码来源:error.py


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