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

Python utils.url_path_join函数代码示例

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

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



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

示例1: load_jupyter_server_extension

def load_jupyter_server_extension(nb_app):
    global logger
    global widgets_dir

    logger = nb_app.log
    logger.info('Loading urth_import server extension.')

    web_app = nb_app.web_app
    widgets_dir = get_nbextension_path()

    # Write out a .bowerrc file to configure bower installs to
    # not be interactive and not to prompt for analytics
    bowerrc = os.path.join(widgets_dir, '.bowerrc')
    if os.access(bowerrc, os.F_OK) is not True:
        logger.debug('Writing .bowerrc at {0}'.format(bowerrc))
        with open(bowerrc, 'a') as f:
            f.write("""{
            "analytics": false,
            "interactive": false,
            "directory": "urth_components"
            }""")

    # The import handler serves from /urth_import and any requests
    # containing /urth_components/ will get served from the actual
    # urth_components directory.
    import_route_pattern = url_path_join(web_app.settings['base_url'], '/urth_import')
    components_route_pattern = url_path_join(web_app.settings['base_url'], '/urth_components/(.*)')
    components_path = os.path.join(widgets_dir, 'urth_components/')

    # Register the Urth import handler and static file handler.
    logger.debug('Adding handlers for {0} and {1}'.format(import_route_pattern, components_route_pattern))
    web_app.add_handlers('.*$', [
        (import_route_pattern, UrthImportHandler, dict(executor=ThreadPoolExecutor(max_workers=1))),
        (components_route_pattern, FileFindHandler, {'path': [components_path]})
    ])
开发者ID:ankostis,项目名称:declarativewidgets,代码行数:35,代码来源:urth_import.py


示例2: load_jupyter_server_extension

def load_jupyter_server_extension(nb_server_app):

    # Extract our gist client details from the config:
    cfg = nb_server_app.config["NotebookApp"]
    BaseHandler.client_id = cfg["oauth_client_id"]
    BaseHandler.client_secret = cfg["oauth_client_secret"]

    web_app = nb_server_app.web_app
    host_pattern = '.*$'

    route_pattern = url_path_join(web_app.settings['base_url'], '/create_gist')

    download_notebook_route_pattern = url_path_join(
                                        web_app.settings['base_url'],
                                        '/download_notebook')

    load_user_gists_route_pattern = url_path_join(
                                        web_app.settings['base_url'],
                                        'load_user_gists')

    web_app.add_handlers(host_pattern,
                         [(route_pattern,
                           GistHandler),
                          (download_notebook_route_pattern,
                           DownloadNotebookHandler),
                          (load_user_gists_route_pattern,
                           LoadGistHandler)])
开发者ID:agjwong,项目名称:jupyter-notebook-gist,代码行数:27,代码来源:create_gist.py


示例3: create_request_handlers

 def create_request_handlers(self):
     """Create default Jupyter handlers and redefine them off of the
     base_url path. Assumes init_configurables() has already been called.
     """
     handlers = []
     # append the activity monitor for websocket mode
     handlers.append((
         url_path_join('/', self.parent.base_url, r'/_api/activity'),
         ActivityHandler,
         {}
     ))
     # append tuples for the standard kernel gateway endpoints
     for handler in (
         default_api_handlers +
         default_kernel_handlers +
         default_kernelspec_handlers +
         default_session_handlers +
         default_base_handlers
     ):
         # Create a new handler pattern rooted at the base_url
         pattern = url_path_join('/', self.parent.base_url, handler[0])
         # Some handlers take args, so retain those in addition to the
         # handler class ref
         new_handler = tuple([pattern] + list(handler[1:]))
         handlers.append(new_handler)
     return handlers
开发者ID:Lomascolo,项目名称:kernel_gateway,代码行数:26,代码来源:__init__.py


示例4: test_old_files_redirect

    def test_old_files_redirect(self):
        """pre-2.0 'files/' prefixed links are properly redirected"""
        nbdir = self.notebook_dir
        
        os.mkdir(pjoin(nbdir, 'files'))
        os.makedirs(pjoin(nbdir, 'sub', 'files'))
        
        for prefix in ('', 'sub'):
            with open(pjoin(nbdir, prefix, 'files', 'f1.txt'), 'w') as f:
                f.write(prefix + '/files/f1')
            with open(pjoin(nbdir, prefix, 'files', 'f2.txt'), 'w') as f:
                f.write(prefix + '/files/f2')
            with open(pjoin(nbdir, prefix, 'f2.txt'), 'w') as f:
                f.write(prefix + '/f2')
            with open(pjoin(nbdir, prefix, 'f3.txt'), 'w') as f:
                f.write(prefix + '/f3')

            url = url_path_join('notebooks', prefix, 'files', 'f1.txt')
            r = self.request('GET', url)
            self.assertEqual(r.status_code, 200)
            self.assertEqual(r.text, prefix + '/files/f1')

            url = url_path_join('notebooks', prefix, 'files', 'f2.txt')
            r = self.request('GET', url)
            self.assertEqual(r.status_code, 200)
            self.assertEqual(r.text, prefix + '/files/f2')

            url = url_path_join('notebooks', prefix, 'files', 'f3.txt')
            r = self.request('GET', url)
            self.assertEqual(r.status_code, 200)
            self.assertEqual(r.text, prefix + '/f3')
开发者ID:drastorguev,项目名称:pythondojo,代码行数:31,代码来源:test_files.py


示例5: test_hidden_files

 def test_hidden_files(self):
     not_hidden = [
         u'å b',
         u'å b/ç. d',
     ]
     hidden = [
         u'.å b',
         u'å b/.ç d',
     ]
     dirs = not_hidden + hidden
     
     nbdir = self.notebook_dir
     for d in dirs:
         path = pjoin(nbdir, d.replace('/', os.sep))
         if not os.path.exists(path):
             os.mkdir(path)
         with open(pjoin(path, 'foo'), 'w') as f:
             f.write('foo')
         with open(pjoin(path, '.foo'), 'w') as f:
             f.write('.foo')
     
     for d in not_hidden:
         path = pjoin(nbdir, d.replace('/', os.sep))
         r = self.request('GET', url_path_join('files', d, 'foo'))
         r.raise_for_status()
         self.assertEqual(r.text, 'foo')
         r = self.request('GET', url_path_join('files', d, '.foo'))
         self.assertEqual(r.status_code, 404)
         
     for d in hidden:
         path = pjoin(nbdir, d.replace('/', os.sep))
         for foo in ('foo', '.foo'):
             r = self.request('GET', url_path_join('files', d, foo))
             self.assertEqual(r.status_code, 404)
开发者ID:drastorguev,项目名称:pythondojo,代码行数:34,代码来源:test_files.py


示例6: create_request_handlers

    def create_request_handlers(self):
        """Create handlers and redefine them off of the base_url path. Assumes
        init_configurables() has already been called, and that the seed source
        was available there.
        """
        handlers = []
        # Register the NotebookDownloadHandler if configuration allows
        if self.allow_notebook_download:
            path = url_path_join("/", self.parent.base_url, r"/_api/source")
            self.log.info("Registering resource: {}, methods: (GET)".format(path))
            handlers.append((path, NotebookDownloadHandler, {"path": self.parent.seed_uri}))

        # Register a static path handler if configuration allows
        if self.static_path is not None:
            path = url_path_join("/", self.parent.base_url, r"/public/(.*)")
            self.log.info("Registering resource: {}, methods: (GET)".format(path))
            handlers.append((path, tornado.web.StaticFileHandler, {"path": self.static_path}))

        # Discover the notebook endpoints and their implementations
        endpoints = self.api_parser.endpoints(self.parent.kernel_manager.seed_source)
        response_sources = self.api_parser.endpoint_responses(self.parent.kernel_manager.seed_source)
        if len(endpoints) == 0:
            raise RuntimeError(
                "No endpoints were discovered. Check your notebook to make sure your cells are annotated correctly."
            )

        # Cycle through the (endpoint_path, source) tuples and register their handlers
        for endpoint_path, verb_source_map in endpoints:
            parameterized_path = parameterize_path(endpoint_path)
            parameterized_path = url_path_join("/", self.parent.base_url, parameterized_path)
            self.log.info(
                "Registering resource: {}, methods: ({})".format(parameterized_path, list(verb_source_map.keys()))
            )
            response_source_map = response_sources[endpoint_path] if endpoint_path in response_sources else {}
            handler_args = {
                "sources": verb_source_map,
                "response_sources": response_source_map,
                "kernel_pool": self.kernel_pool,
                "kernel_name": self.parent.kernel_manager.seed_kernelspec,
            }
            handlers.append((parameterized_path, NotebookAPIHandler, handler_args))

        # Register the swagger API spec handler
        path = url_path_join("/", self.parent.base_url, r"/_api/spec/swagger.json")
        handlers.append(
            (
                path,
                SwaggerSpecHandler,
                {
                    "notebook_path": self.parent.seed_uri,
                    "source_cells": self.parent.seed_notebook.cells,
                    "cell_parser": self.api_parser,
                },
            )
        )
        self.log.info("Registering resource: {}, methods: (GET)".format(path))

        # Add the 404 catch-all last
        handlers.append(default_base_handlers[-1])
        return handlers
开发者ID:nitind,项目名称:kernel_gateway,代码行数:60,代码来源:__init__.py


示例7: get

    def get(self):
        query_string = self.get_query_argument('qs')
        reindex = bool(self.get_query_argument('reindex', 'true') == 'true')

        if reindex:
            self.index.update_index()

        results, total = self.index.search(query_string)

        for result in results:
            rel_path = result['path'][self.work_dir_len:]
            if rel_path.endswith('.ipynb'):
                # take it at face value that the extension implies notebook
                url = url_path_join(self.base_url, 'notebooks', rel_path)
            else:
                url = url_path_join(self.base_url, 'edit', rel_path)
            # Add URLs
            result['url'] = url
            result['tree_url'] = url_path_join(self.base_url, 'tree', os.path.dirname(rel_path))
            # Add relative paths
            result['rel_dirname'] = os.path.dirname(rel_path)
            result['rel_path'] = rel_path
        
        self.write(dict(results=results, total=total))
        self.finish()
开发者ID:FeiXiang-Chen,项目名称:contentmanagement,代码行数:25,代码来源:search.py


示例8: get

    def get(self):
        if not self.request.uri.startswith(EXTENSION_URL):
            raise_error("URI did not start with " + EXTENSION_URL)
        spark_request = self.spark_host + self.request.uri[len(EXTENSION_URL):]

        try:
            spark_response = requests.get(spark_request)

            content_type = spark_response.headers['content-type']
            self.set_header("Content-Type", content_type)

            if "text" in content_type:
                # Replace all the relative links with our proxy links
                soup = BeautifulSoup(spark_response.text, "html.parser")

                for has_href in ['a', 'link']:
                    for a in soup.find_all(has_href):
                        if "href" in a.attrs:
                            a['href'] = url_path_join(self.web_app, a['href'])

                for has_src in ['img', 'script']:
                    for a in soup.find_all(has_src):
                        if "src" in a.attrs:
                            a['src'] = url_path_join(self.web_app, a['src'])

                client_response = str(soup)
            else:
                # Probably binary response, send it directly.
                client_response = spark_response.content

        except requests.exceptions.RequestException:
            client_response = json.dumps({"error": "SPARK_NOT_RUNNING"})

        self.write(client_response)
        self.flush()
开发者ID:jezdez,项目名称:jupyter-spark,代码行数:35,代码来源:spark.py


示例9: redirect_to_files

    def redirect_to_files(self, path):
        """make redirect logic a reusable static method
        
        so it can be called from other handlers.
        """
        cm = self.contents_manager
        if cm.dir_exists(path):
            # it's a *directory*, redirect to /tree
            url = url_path_join(self.base_url, 'tree', url_escape(path))
        else:
            orig_path = path
            # otherwise, redirect to /files
            parts = path.split('/')

            if not cm.file_exists(path=path) and 'files' in parts:
                # redirect without files/ iff it would 404
                # this preserves pre-2.0-style 'files/' links
                self.log.warning("Deprecated files/ URL: %s", orig_path)
                parts.remove('files')
                path = '/'.join(parts)

            if not cm.file_exists(path=path):
                raise web.HTTPError(404)

            url = url_path_join(self.base_url, 'files', url_escape(path))
        self.log.debug("Redirecting %s to %s", self.request.path, url)
        self.redirect(url)
开发者ID:AndrewLngdn,项目名称:notebook,代码行数:27,代码来源:handlers.py


示例10: load_jupyter_server_extension

def load_jupyter_server_extension(nb_app):
    """Load the nb anaconda client extension"""
    webapp = nb_app.web_app
    base_url = webapp.settings['base_url']
    webapp.add_handlers(".*$", [
        (url_path_join(base_url, r"/ac-publish"), PublishHandler),
        (url_path_join(base_url, r"/ac-login"), WhoAmIHandler)
    ])
    nb_app.log.info("Enabling nb_anacondanotebook")
开发者ID:bollwyvl,项目名称:nb_anacondacloud,代码行数:9,代码来源:handlers.py


示例11: load_jupyter_server_extension

def load_jupyter_server_extension(nb_app):
    """Load the nb_anacondacloud client extension"""
    webapp = nb_app.web_app
    base_url = webapp.settings['base_url']
    ns = r'anaconda-cloud'
    webapp.add_handlers(".*$", [
        (url_path_join(base_url, ns, r"publish"), PublishHandler),
        (url_path_join(base_url, ns, r"login"), WhoAmIHandler)
    ])
    nb_app.log.info("[nb_anacondacloud] enabled")
开发者ID:Anaconda-Platform,项目名称:nb_anacondacloud,代码行数:10,代码来源:handlers.py


示例12: send_file

def send_file(file_path, dashboard_name, handler):
    '''
    Posts a file to the Jupyter Dashboards Server to be served as a dashboard
    :param file_path: The path of the file to send
    :param dashboard_name: The dashboard name under which it should be made
        available
    '''
    # Make information about the request Host header available for use in
    # constructing the urls
    segs = handler.request.host.split(':')
    hostname = segs[0]
    if len(segs) > 1:
        port = segs[1]
    else:
        port = ''
    protocol = handler.request.protocol

    # Treat empty as undefined
    dashboard_server = os.getenv('DASHBOARD_SERVER_URL')
    if dashboard_server:
        dashboard_server = dashboard_server.format(protocol=protocol,
            hostname=hostname, port=port)
        upload_url = url_path_join(dashboard_server, UPLOAD_ENDPOINT,
            escape.url_escape(dashboard_name, False))
        with open(file_path, 'rb') as file_content:
            headers = {}
            token = os.getenv('DASHBOARD_SERVER_AUTH_TOKEN')
            if token:
                headers['Authorization'] = 'token {}'.format(token)
            result = requests.post(upload_url, files={'file': file_content},
                headers=headers, timeout=60, 
                verify=not skip_ssl_verification())
            if result.status_code >= 400:
                raise web.HTTPError(result.status_code)

        # Redirect to link specified in response body
        res_body = result.json()
        if 'link' in res_body:
            redirect_link = res_body['link']
        else:
            # Compute redirect link using environment variables
            # First try redirect URL as it might be different from internal upload URL
            redirect_server = os.getenv('DASHBOARD_REDIRECT_URL')
            if redirect_server:
                redirect_root = redirect_server.format(hostname=hostname,
                    port=port, protocol=protocol)
            else:
                redirect_root = dashboard_server

            redirect_link = url_path_join(redirect_root, VIEW_ENDPOINT, escape.url_escape(dashboard_name, False))
        handler.redirect(redirect_link)
    else:
        access_log.debug('Can not deploy, DASHBOARD_SERVER_URL not set')
        raise web.HTTPError(500, log_message='No dashboard server configured')
开发者ID:jupyter-incubator,项目名称:dashboards_bundlers,代码行数:54,代码来源:__init__.py


示例13: load_jupyter_server_extension

def load_jupyter_server_extension(nbapp):
    web_app = nbapp.web_app
    host_pattern = '.*$'
    version_route_pattern = url_path_join(web_app.settings['base_url'], '/version')
    listfolder_route_pattern = url_path_join(web_app.settings['base_url'], '/listfolder')
    getfile_route_pattern = url_path_join(web_app.settings['base_url'], '/getfile')

    web_app.add_handlers(host_pattern, [(version_route_pattern, VersionHandler)])
    web_app.add_handlers(host_pattern, [(listfolder_route_pattern, ListFolderHandler)])
    web_app.add_handlers(host_pattern, [(getfile_route_pattern, GetFileHandler)])
    
    nbapp.log.info("[beakerx_databrowser] enabled")
开发者ID:twosigma,项目名称:beaker-notebook,代码行数:12,代码来源:handlers.py


示例14: load_jupyter_server_extension

def load_jupyter_server_extension(nb_server_app):
    # Extract our Spark server details from the config:
    cfg = nb_server_app.config["NotebookApp"]
    SparkHandler.spark_host = cfg.get("spark_host", "http://localhost:4040")

    web_app = nb_server_app.web_app
    host_pattern = ".*$"
    route_pattern = url_path_join(
        web_app.settings['base_url'], EXTENSION_URL) + ".*"
    web_app.add_handlers(host_pattern, [(route_pattern, SparkHandler)])

    SparkHandler.web_app = url_path_join(
        web_app.settings['base_url'], EXTENSION_URL)
开发者ID:jezdez,项目名称:jupyter-spark,代码行数:13,代码来源:spark.py


示例15: test_default_kernel

    def test_default_kernel(self):
        # POST request
        r = self.kern_api._req('POST', '')
        kern1 = r.json()
        self.assertEqual(r.headers['location'], url_path_join(self.url_prefix, 'api/kernels', kern1['id']))
        self.assertEqual(r.status_code, 201)
        self.assertIsInstance(kern1, dict)

        report_uri = url_path_join(self.url_prefix, 'api/security/csp-report')
        expected_csp = '; '.join([
            "frame-ancestors 'self'",
            'report-uri ' + report_uri,
            "default-src 'none'"
        ])
        self.assertEqual(r.headers['Content-Security-Policy'], expected_csp)
开发者ID:BarnetteME1,项目名称:DnD-stuff,代码行数:15,代码来源:test_kernels_api.py


示例16: _req

 def _req(self, verb, path, body=None, params=None):
     response = self.request(verb,
             url_path_join('api/contents', path),
             data=body, params=params,
     )
     response.raise_for_status()
     return response
开发者ID:drastorguev,项目名称:pythondojo,代码行数:7,代码来源:test_contents_api.py


示例17: get

 def get(self, path):
     self.log.warn("/api/notebooks is deprecated, use /api/contents")
     self.redirect(url_path_join(
         self.base_url,
         'api/contents',
         path
     ))
开发者ID:techtonik,项目名称:notebook,代码行数:7,代码来源:handlers.py


示例18: test_download

    def test_download(self):
        nbdir = self.notebook_dir.name
        base = self.base_url()
        
        text = 'hello'
        with open(pjoin(nbdir, 'test.txt'), 'w') as f:
            f.write(text)
        
        r = requests.get(url_path_join(base, 'files', 'test.txt'))
        disposition = r.headers.get('Content-Disposition', '')
        self.assertNotIn('attachment', disposition)

        r = requests.get(url_path_join(base, 'files', 'test.txt') + '?download=1')
        disposition = r.headers.get('Content-Disposition', '')
        self.assertIn('attachment', disposition)
        self.assertIn('filename="test.txt"', disposition)
开发者ID:ACGC,项目名称:notebook,代码行数:16,代码来源:test_files.py


示例19: _req

 def _req(self, verb, section, body=None):
     response = requests.request(verb,
             url_path_join(self.base_url, 'api/config', section),
             data=body,
     )
     response.raise_for_status()
     return response
开发者ID:ACGC,项目名称:notebook,代码行数:7,代码来源:test_config_api.py


示例20: _req

 def _req(self, verb, path, body=None, params=None):
     response = requests.request(verb,
             url_path_join(self.base_url, 'nbconvert', path),
             data=body, params=params,
     )
     response.raise_for_status()
     return response
开发者ID:ACGC,项目名称:notebook,代码行数:7,代码来源:test_nbconvert_handlers.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python models.create_notice_type函数代码示例发布时间:2022-05-27
下一篇:
Python utils.url_escape函数代码示例发布时间: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