本文整理汇总了Python中notebook.utils.url_escape函数的典型用法代码示例。如果您正苦于以下问题:Python url_escape函数的具体用法?Python url_escape怎么用?Python url_escape使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了url_escape函数的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: get
def get(self, path):
"""
Inject the user's KBase cookie before trying to look up a file.
One of our big use cases bypasses the typical Jupyter login mechanism.
"""
cookie_regex = re.compile('([^ =|]+)=([^\|]*)')
client_ip = self.request.remote_ip
http_headers = self.request.headers
ua = http_headers.get('User-Agent', 'unknown')
found_cookies = [self.cookies[c] for c in all_cookies if c in self.cookies]
if found_cookies:
cookie_val = urllib.unquote(found_cookies[0].value)
cookie_obj = {
k: v.replace('EQUALSSIGN', '=').replace('PIPESIGN', '|')
for k, v in cookie_regex.findall(cookie_val)
}
# if app_log.isEnabledFor(logging.DEBUG):
# app_log.debug("kbase cookie = {}".format(cookie_val))
# app_log.debug("KBaseLoginHandler.get: user_id={uid} token={tok}"
# .format(uid=sess.get('token', 'none'),
# tok=sess.get('token', 'none')))
biokbase.auth.set_environ_token(cookie_obj.get('token', None))
kbase_env.session = cookie_obj.get('kbase_sessionid', '')
kbase_env.client_ip = client_ip
kbase_env.user = cookie_obj.get('user_id', '')
log_event(g_log, 'session_start', {'user': kbase_env.user, 'user_agent': ua})
"""get renders the notebook template if a name is given, or
redirects to the '/files/' handler if the name is not given."""
path = path.strip('/')
cm = self.contents_manager
# will raise 404 on not found
try:
model = cm.get(path, content=False)
except web.HTTPError as e:
raise
# if e.status_code == 404 and 'files' in path.split('/'):
# # 404, but '/files/' in URL, let FilesRedirect take care of it
# return FilesRedirectHandler.redirect_to_files(self, path)
# else:
# raise
if model['type'] != 'notebook':
# not a notebook, redirect to files
return FilesRedirectHandler.redirect_to_files(self, path)
name = url_escape(path.rsplit('/', 1)[-1])
path = url_escape(path)
self.write(self.render_template('notebook.html',
notebook_path=path,
notebook_name=path,
kill_kernel=False,
mathjax_url=self.mathjax_url,
)
)
开发者ID:danielolson5,项目名称:narrative,代码行数:60,代码来源:narrativehandler.py
示例2: 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
示例3: get
def get(self, path):
"""
Inject the user's KBase cookie before trying to look up a file.
One of our big use cases bypasses the typical Jupyter login mechanism.
"""
cookie_regex = re.compile('([^ =|]+)=([^\|]*)')
client_ip = self.request.remote_ip
http_headers = self.request.headers
ua = http_headers.get('User-Agent', 'unknown')
auth_cookie = self.cookies.get(auth_cookie_name, None)
if auth_cookie:
cookie_val = urllib.unquote(auth_cookie.value)
cookie_obj = {
k: v.replace('EQUALSSIGN', '=').replace('PIPESIGN', '|')
for k, v in cookie_regex.findall(cookie_val)
}
else:
raise web.HTTPError(status_code=401, log_message='No auth cookie, denying access', reason='Authorization required for Narrative access')
biokbase.auth.set_environ_token(cookie_obj.get('token', None))
kbase_env.session = cookie_obj.get('kbase_sessionid', '')
kbase_env.client_ip = client_ip
kbase_env.user = cookie_obj.get('user_id', '')
log_event(g_log, 'session_start', {'user': kbase_env.user, 'user_agent': ua})
"""get renders the notebook template if a name is given, or
redirects to the '/files/' handler if the name is not given."""
path = path.strip('/')
cm = self.contents_manager
# will raise 404 on not found
try:
model = cm.get(path, content=False)
except web.HTTPError as e:
raise
# if e.status_code == 404 and 'files' in path.split('/'):
# # 404, but '/files/' in URL, let FilesRedirect take care of it
# return FilesRedirectHandler.redirect_to_files(self, path)
# else:
# raise
if model['type'] != 'notebook':
# not a notebook, redirect to files
return FilesRedirectHandler.redirect_to_files(self, path)
name = url_escape(path.rsplit('/', 1)[-1])
path = url_escape(path)
self.write(self.render_template('notebook.html',
notebook_path=path,
notebook_name=path,
kill_kernel=False,
mathjax_url=self.mathjax_url,
)
)
开发者ID:mlhenderson,项目名称:narrative,代码行数:57,代码来源:narrativehandler.py
示例4: post
def post(self, path=''):
"""post creates a new checkpoint"""
cm = self.contents_manager
checkpoint = yield maybe_future(cm.create_checkpoint(path))
data = json.dumps(checkpoint, default=date_default)
location = url_path_join(self.base_url, 'api/contents',
url_escape(path), 'checkpoints', url_escape(checkpoint['id']))
self.set_header('Location', location)
self.set_status(201)
self.finish(data)
开发者ID:ian-r-rose,项目名称:notebook,代码行数:10,代码来源:handlers.py
示例5: post
def post(self, path=''):
"""post creates a new checkpoint"""
# grab the commit message from the posted data
commit_message = json.loads(self.request.body.decode('utf-8')).get('commit_message', None)
# print("CREATING NEW CHECKPOINT WITH MESSAGE: " + str(commit_message))
cm = self.contents_manager
checkpoint = yield gen.maybe_future(cm.create_checkpoint(path, commit_message=commit_message))
data = json.dumps(checkpoint, default=date_default)
location = url_path_join(self.base_url, 'api/contents',
url_escape(path), 'checkpoints', url_escape(checkpoint['id']))
self.set_header('Location', location)
self.set_status(201)
self.finish(data)
开发者ID:datascienceinc,项目名称:jupyter-notebook,代码行数:14,代码来源:handlers.py
示例6: test_url_escape
def test_url_escape():
# changes path or notebook name with special characters to url encoding
# these tests specifically encode paths with spaces
path = url_escape('/this is a test/for spaces/')
nt.assert_equal(path, '/this%20is%20a%20test/for%20spaces/')
path = url_escape('notebook with space.ipynb')
nt.assert_equal(path, 'notebook%20with%20space.ipynb')
path = url_escape('/path with a/notebook and space.ipynb')
nt.assert_equal(path, '/path%20with%20a/notebook%20and%20space.ipynb')
path = url_escape('/ [email protected]$#%^&* / test %^ notebook @#$ name.ipynb')
nt.assert_equal(path,
'/%20%21%40%24%23%25%5E%26%2A%20/%20test%20%25%5E%20notebook%20%40%23%24%20name.ipynb')
开发者ID:Carreau,项目名称:jupyter_notebook,代码行数:16,代码来源:test_utils.py
示例7: _check_created
def _check_created(self, resp, path, type='notebook'):
self.assertEqual(resp.status_code, 201)
location_header = py3compat.str_to_unicode(resp.headers['Location'])
self.assertEqual(location_header, url_escape(url_path_join(u'/api/contents', path)))
rjson = resp.json()
self.assertEqual(rjson['name'], path.rsplit('/', 1)[-1])
self.assertEqual(rjson['path'], path)
self.assertEqual(rjson['type'], type)
isright = self.isdir if type == 'directory' else self.isfile
assert isright(path)
开发者ID:AFJay,项目名称:notebook,代码行数:10,代码来源:test_contents_api.py
示例8: location_url
def location_url(self, path):
"""Return the full URL location of a file.
Parameters
----------
path : unicode
The API path of the file, such as "foo/bar.txt".
"""
return url_escape(url_path_join(
self.base_url, 'api', 'contents', path
))
开发者ID:techtonik,项目名称:notebook,代码行数:11,代码来源:handlers.py
示例9: set_attachment_header
def set_attachment_header(self, filename):
"""Set Content-Disposition: attachment header
As a method to ensure handling of filename encoding
"""
escaped_filename = url_escape(filename)
self.set_header('Content-Disposition',
'attachment;'
" filename*=utf-8''{utf8}"
.format(
utf8=escaped_filename,
)
)
开发者ID:SylvainCorlay,项目名称:notebook,代码行数:13,代码来源:handlers.py
示例10: post
def post(self):
km = self.kernel_manager
model = self.get_json_body()
if model is None:
model = {
'name': km.default_kernel_name
}
else:
model.setdefault('name', km.default_kernel_name)
kernel_id = km.start_kernel(kernel_name=model['name'])
model = km.kernel_model(kernel_id)
location = url_path_join(self.base_url, 'api', 'kernels', kernel_id)
self.set_header('Location', url_escape(location))
self.set_status(201)
self.finish(json.dumps(model))
开发者ID:kmatzen,项目名称:notebook,代码行数:16,代码来源:handlers.py
示例11: nbopen
def nbopen(filename, profile='default'):
filename = os.path.abspath(filename)
home_dir = os.path.expanduser('~')
server_inf = find_best_server(filename, profile)
if server_inf is not None:
print("Using existing server at", server_inf['notebook_dir'])
path = os.path.relpath(filename, start=server_inf['notebook_dir'])
url = url_path_join(server_inf['url'], 'notebooks', url_escape(path))
webbrowser.open(url, new=2)
else:
if filename.startswith(home_dir):
nbdir = home_dir
else:
nbdir = os.path.dirname(filename)
print("Starting new server")
notebookapp.launch_new_instance(file_to_run=os.path.abspath(filename),
notebook_dir=nbdir,
open_browser=True,
argv=[], # Avoid it seeing our own argv
)
开发者ID:ajasja,项目名称:nbopen,代码行数:21,代码来源:nbopen.py
示例12: load_jupyter_server_extension
def load_jupyter_server_extension(nbapp):
"""Load the JupyterLab server extension.
"""
# Delay imports to speed up jlpmapp
from json import dumps
from jupyterlab_launcher import add_handlers, LabConfig
from notebook.utils import url_path_join as ujoin, url_escape
from notebook._version import version_info
from tornado.ioloop import IOLoop
from markupsafe import Markup
from .build_handler import build_path, Builder, BuildHandler
from .commands import (
get_app_dir, get_user_settings_dir, watch, ensure_dev, watch_dev,
pjoin, DEV_DIR, HERE, get_app_info, ensure_core, get_workspaces_dir
)
web_app = nbapp.web_app
logger = nbapp.log
config = LabConfig()
app_dir = getattr(nbapp, 'app_dir', get_app_dir())
user_settings_dir = getattr(
nbapp, 'user_settings_dir', get_user_settings_dir()
)
workspaces_dir = getattr(
nbapp, 'workspaces_dir', get_workspaces_dir()
)
# Print messages.
logger.info('JupyterLab beta preview extension loaded from %s' % HERE)
logger.info('JupyterLab application directory is %s' % app_dir)
config.app_name = 'JupyterLab Beta'
config.app_namespace = 'jupyterlab'
config.page_url = '/lab'
config.cache_files = True
# Check for core mode.
core_mode = False
if getattr(nbapp, 'core_mode', False) or app_dir.startswith(HERE):
core_mode = True
logger.info('Running JupyterLab in core mode')
# Check for dev mode.
dev_mode = False
if getattr(nbapp, 'dev_mode', False) or app_dir.startswith(DEV_DIR):
dev_mode = True
logger.info('Running JupyterLab in dev mode')
# Check for watch.
watch_mode = getattr(nbapp, 'watch', False)
if watch_mode and core_mode:
logger.warn('Cannot watch in core mode, did you mean --dev-mode?')
watch_mode = False
if core_mode and dev_mode:
logger.warn('Conflicting modes, choosing dev_mode over core_mode')
core_mode = False
page_config = web_app.settings.setdefault('page_config_data', dict())
page_config['buildAvailable'] = not core_mode and not dev_mode
page_config['buildCheck'] = not core_mode and not dev_mode
page_config['token'] = nbapp.token
page_config['devMode'] = dev_mode
# Export the version info tuple to a JSON array. This get's printed
# inside double quote marks, so we render it to a JSON string of the
# JSON data (so that we can call JSON.parse on the frontend on it).
# We also have to wrap it in `Markup` so that it isn't escaped
# by Jinja. Otherwise, if the version has string parts these will be
# escaped and then will have to be unescaped on the frontend.
page_config['notebookVersion'] = Markup(dumps(dumps(version_info))[1:-1])
if nbapp.file_to_run and type(nbapp).__name__ == "LabApp":
relpath = os.path.relpath(nbapp.file_to_run, nbapp.notebook_dir)
uri = url_escape(ujoin('/lab/tree', *relpath.split(os.sep)))
nbapp.default_url = uri
nbapp.file_to_run = ''
if core_mode:
app_dir = HERE
logger.info(CORE_NOTE.strip())
ensure_core(logger)
elif dev_mode:
app_dir = DEV_DIR
ensure_dev(logger)
if not watch_mode:
logger.info(DEV_NOTE)
config.app_settings_dir = pjoin(app_dir, 'settings')
config.schemas_dir = pjoin(app_dir, 'schemas')
config.themes_dir = pjoin(app_dir, 'themes')
config.workspaces_dir = workspaces_dir
info = get_app_info(app_dir)
config.app_version = info['version']
public_url = info['publicUrl']
if public_url:
config.public_url = public_url
else:
config.static_dir = pjoin(app_dir, 'static')
#.........这里部分代码省略.........
开发者ID:groutr,项目名称:jupyterlab,代码行数:101,代码来源:extension.py
示例13: load_jupyter_server_extension
def load_jupyter_server_extension(nbapp):
"""Load the JupyterLab server extension.
"""
# Delay imports to speed up jlpmapp
from json import dumps
from jupyterlab_server import add_handlers
from notebook.utils import url_path_join as ujoin, url_escape
from notebook._version import version_info
from tornado.ioloop import IOLoop
from markupsafe import Markup
from .build_handler import build_path, Builder, BuildHandler
from .extension_manager_handler import (
extensions_handler_path, ExtensionManager, ExtensionHandler
)
from .commands import (
DEV_DIR, HERE, ensure_core, ensure_dev, watch, watch_dev, get_app_dir
)
web_app = nbapp.web_app
logger = nbapp.log
# Handle the app_dir
app_dir = getattr(nbapp, 'app_dir', get_app_dir())
# Check for core mode.
core_mode = False
if getattr(nbapp, 'core_mode', False) or app_dir.startswith(HERE):
app_dir = HERE
core_mode = True
logger.info('Running JupyterLab in core mode')
# Check for dev mode.
dev_mode = False
if getattr(nbapp, 'dev_mode', False) or app_dir.startswith(DEV_DIR):
app_dir = DEV_DIR
dev_mode = True
logger.info('Running JupyterLab in dev mode')
# Set the value on nbapp so it will get picked up in load_config
nbapp.app_dir = app_dir
config = load_config(nbapp)
config.app_name = 'JupyterLab'
config.app_namespace = 'jupyterlab'
config.page_url = '/lab'
config.cache_files = True
# Check for watch.
watch_mode = getattr(nbapp, 'watch', False)
if watch_mode and core_mode:
logger.warn('Cannot watch in core mode, did you mean --dev-mode?')
watch_mode = False
if core_mode and dev_mode:
logger.warn('Conflicting modes, choosing dev_mode over core_mode')
core_mode = False
page_config = web_app.settings.setdefault('page_config_data', dict())
page_config['buildAvailable'] = not core_mode and not dev_mode
page_config['buildCheck'] = not core_mode and not dev_mode
page_config['token'] = nbapp.token
page_config['devMode'] = dev_mode
# Handle bundle url
bundle_url = config.public_url
if bundle_url.startswith(config.page_url):
bundle_url = ujoin(nbapp.base_url, bundle_url)
page_config['bundleUrl'] = bundle_url
# Export the version info tuple to a JSON array. This gets printed
# inside double quote marks, so we render it to a JSON string of the
# JSON data (so that we can call JSON.parse on the frontend on it).
# We also have to wrap it in `Markup` so that it isn't escaped
# by Jinja. Otherwise, if the version has string parts these will be
# escaped and then will have to be unescaped on the frontend.
page_config['notebookVersion'] = Markup(dumps(dumps(version_info))[1:-1])
if nbapp.file_to_run and type(nbapp).__name__ == "LabApp":
relpath = os.path.relpath(nbapp.file_to_run, nbapp.notebook_dir)
uri = url_escape(ujoin('/lab/tree', *relpath.split(os.sep)))
nbapp.default_url = uri
nbapp.file_to_run = ''
if core_mode:
logger.info(CORE_NOTE.strip())
ensure_core(logger)
elif dev_mode:
ensure_dev(logger)
if not watch_mode:
logger.info(DEV_NOTE)
# Print messages.
logger.info('JupyterLab extension loaded from %s' % HERE)
logger.info('JupyterLab application directory is %s' % app_dir)
if watch_mode:
logger.info('Starting JupyterLab watch mode...')
#.........这里部分代码省略.........
开发者ID:AlbertHilb,项目名称:jupyterlab,代码行数:101,代码来源:extension.py
注:本文中的notebook.utils.url_escape函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论