Skip to content

Commit ae2f358

Browse files
authored
Merge pull request #1015 from martinRenou/upgrade-nbconvert
Upgrade nbconvert
2 parents 8ba1fc3 + b46085a commit ae2f358

27 files changed

+199
-185
lines changed

.github/workflows/test.yaml

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
name: test
2+
3+
on:
4+
push:
5+
branches:
6+
pull_request:
7+
8+
jobs:
9+
test:
10+
runs-on: ubuntu-20.04
11+
strategy:
12+
matrix:
13+
python:
14+
- "3.8"
15+
- "3.9"
16+
- "3.10"
17+
steps:
18+
- name: Checkout
19+
uses: actions/checkout@v3
20+
21+
- uses: actions/setup-python@v4
22+
with:
23+
python-version: ${{ matrix.python }}
24+
25+
- name: install apt packages
26+
# pycurl build requirements
27+
run: |
28+
sudo apt-get update && sudo apt-get -y install \
29+
libcurl4-gnutls-dev \
30+
libgnutls28-dev
31+
32+
- name: install
33+
run: |
34+
python3 -m pip install -r requirements.in -r requirements-dev.txt
35+
- name: install mypy
36+
run: |
37+
python3 -m pip install mypy types-pycurl types-requests types-Markdown
38+
- name: run mypy
39+
run: |
40+
mypy nbviewer
41+
42+
- name: pip freeze
43+
run: |
44+
python3 -m pip freeze
45+
46+
- name: run tests
47+
run: |
48+
pytest -v nbviewer/tests -s

.pre-commit-config.yaml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,3 +20,5 @@ repos:
2020
exclude: ^helm-chart/nbviewer/templates/
2121
- id: check-case-conflict
2222
- id: check-executables-have-shebangs
23+
ci:
24+
autofix_prs: false

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -139,7 +139,7 @@ Pass `-d` or `--debug` to `invoke less` to create a CSS sourcemap, useful for de
139139

140140
```shell
141141
$ cd <path to repo>
142-
$ python -m nbviewer --debug --no-cache
142+
$ python -m nbviewer --debug --no-cache --host=127.0.0.1
143143
```
144144

145145
This will automatically relaunch the server if a change is detected on a python file, and not cache any results. You can then just do the modifications you like to the source code and/or the templates then refresh the pages.

nbviewer/_version.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
import re
1212
import subprocess
1313
import sys
14+
from typing import Dict
1415

1516

1617
def get_keywords():
@@ -48,7 +49,7 @@ class NotThisMethod(Exception):
4849
"""Exception raised if a method is not valid for the current scenario."""
4950

5051

51-
LONG_VERSION_PY = {}
52+
LONG_VERSION_PY: Dict[str, str] = {}
5253
HANDLERS = {}
5354

5455

@@ -93,9 +94,7 @@ def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, env=
9394
if verbose:
9495
print("unable to find command, tried %s" % (commands,))
9596
return None, None
96-
stdout = p.communicate()[0].strip()
97-
if sys.version_info[0] >= 3:
98-
stdout = stdout.decode()
97+
stdout = p.communicate()[0].strip().decode()
9998
if p.returncode != 0:
10099
if verbose:
101100
print("unable to run %s (error)" % dispcmd)

nbviewer/app.py

Lines changed: 20 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -10,13 +10,16 @@
1010
import os
1111
from concurrent.futures import ProcessPoolExecutor
1212
from concurrent.futures import ThreadPoolExecutor
13+
from functools import cached_property
1314
from html import escape
1415
from urllib.parse import urlparse
1516

1617
import markdown
1718
from jinja2 import Environment
1819
from jinja2 import FileSystemLoader
19-
from nbconvert.exporters.export import exporter_map
20+
from jupyter_server.base.handlers import FileFindHandler as StaticFileHandler # type: ignore
21+
from nbconvert import get_exporter # type: ignore
22+
from nbconvert.exporters.templateexporter import ExtensionTolerantLoader # type: ignore
2023
from tornado import httpserver
2124
from tornado import ioloop
2225
from tornado import web
@@ -50,13 +53,6 @@
5053
from .utils import jupyter_info
5154
from .utils import url_path_join
5255

53-
try: # Python 3.8
54-
from functools import cached_property
55-
except ImportError:
56-
from .utils import cached_property
57-
58-
from jupyter_server.base.handlers import FileFindHandler as StaticFileHandler
59-
6056
# -----------------------------------------------------------------------------
6157
# Code
6258
# -----------------------------------------------------------------------------
@@ -67,16 +63,16 @@
6763

6864
def nrhead():
6965
try:
70-
import newrelic.agent
71-
except ImportError:
66+
import newrelic.agent # type: ignore
67+
except ModuleNotFoundError:
7268
return ""
7369
return newrelic.agent.get_browser_timing_header()
7470

7571

7672
def nrfoot():
7773
try:
7874
import newrelic.agent
79-
except ImportError:
75+
except ModuleNotFoundError:
8076
return ""
8177
return newrelic.agent.get_browser_timing_footer()
8278

@@ -89,7 +85,7 @@ class NBViewer(Application):
8985

9086
name = Unicode("NBViewer")
9187

92-
aliases = Dict(
88+
aliases = Dict( # type: ignore
9389
{
9490
"base-url": "NBViewer.base_url",
9591
"binder-base-url": "NBViewer.binder_base_url",
@@ -128,7 +124,7 @@ class NBViewer(Application):
128124
}
129125
)
130126

131-
flags = Dict(
127+
flags = Dict( # type: ignore
132128
{
133129
"debug": (
134130
{"Application": {"log_level": logging.DEBUG}},
@@ -468,7 +464,11 @@ def default_endpoint(self):
468464

469465
@cached_property
470466
def env(self):
471-
env = Environment(loader=FileSystemLoader(self.template_paths), autoescape=True)
467+
loader = ExtensionTolerantLoader(FileSystemLoader(self.template_paths), ".j2")
468+
env = Environment(
469+
loader=loader,
470+
autoescape=True,
471+
)
472472
env.filters["markdown"] = markdown.markdown
473473
try:
474474
git_data = git_info(here)
@@ -528,7 +528,7 @@ def frontpage_setup(self):
528528

529529
# Attribute inherited from traitlets.config.Application, automatically used to style logs
530530
# https://github.com/ipython/traitlets/blob/master/traitlets/config/application.py#L191
531-
_log_formatter_cls = LogFormatter
531+
_log_formatter_cls = LogFormatter # type: ignore
532532
# Need Tornado LogFormatter for color logs, keys 'color' and 'end_color' in log_format
533533

534534
# Observed traitlet inherited again from traitlets.config.Application
@@ -594,15 +594,15 @@ def configure_formats(self, formats=None):
594594
formats = default_formats()
595595

596596
# This would be better defined in a class
597-
self.config.HTMLExporter.template_file = "basic"
598-
self.config.SlidesExporter.template_file = "slides_reveal"
597+
# self.config.HTMLExporter.template_file = "base"
598+
# self.config.SlidesExporter.template_file = "slides_reveal"
599599

600-
self.config.TemplateExporter.template_path = [
600+
self.config.TemplateExporter.extra_template_basedirs = [
601601
os.path.join(os.path.dirname(__file__), "templates", "nbconvert")
602602
]
603603

604604
for key, format in formats.items():
605-
exporter_cls = format.get("exporter", exporter_map[key])
605+
exporter_cls = format.get("exporter", get_exporter(key))
606606
if self.processes:
607607
# can't pickle exporter instances,
608608
formats[key]["exporter"] = exporter_cls
@@ -793,7 +793,7 @@ def main(argv=None):
793793

794794
http_server = httpserver.HTTPServer(app, xheaders=True, ssl_options=ssl_options)
795795
nbviewer.log.info(
796-
"Listening on %s:%i, path %s",
796+
"Listening on http://%s:%i, path %s",
797797
nbviewer.host,
798798
nbviewer.port,
799799
app.settings["base_url"],

nbviewer/cache.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,9 +13,9 @@
1313
from tornado.log import app_log
1414

1515
try:
16-
import pylibmc
17-
except ImportError:
18-
pylibmc = None
16+
import pylibmc # type: ignore
17+
except ModuleNotFoundError:
18+
pylibmc = None # type: ignore
1919

2020
# -----------------------------------------------------------------------------
2121
# Code

nbviewer/formats.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -55,9 +55,9 @@ def test_slides(nb, json):
5555
return False
5656

5757
return {
58-
"html": {"nbconvert_template": "basic", "label": "Notebook", "icon": "book"},
58+
"html": {"nbconvert_template": "lab", "label": "Notebook", "icon": "book"},
5959
"slides": {
60-
"nbconvert_template": "slides_reveal",
60+
# "nbconvert_template": "slides_reveal",
6161
"label": "Slides",
6262
"icon": "gift",
6363
"test": test_slides,

nbviewer/providers/base.py

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -11,15 +11,16 @@
1111
import time
1212
from contextlib import contextmanager
1313
from datetime import datetime
14+
from functools import wraps
1415
from html import escape
1516
from http.client import responses
1617
from urllib.parse import quote
1718
from urllib.parse import urlencode
1819
from urllib.parse import urlparse
1920
from urllib.parse import urlunparse
2021

21-
import statsd
22-
from nbformat import current_nbformat
22+
import statsd # type: ignore
23+
from nbformat import current_nbformat # type:ignore
2324
from nbformat import reads
2425
from tornado import httpclient
2526
from tornado import web
@@ -39,10 +40,10 @@
3940
try:
4041
import pycurl
4142
from tornado.curl_httpclient import CurlError
42-
except ImportError:
43-
pycurl = None
43+
except ModuleNotFoundError:
44+
pycurl = None # type: ignore
4445

45-
class CurlError(Exception):
46+
class CurlError(Exception): # type: ignore
4647
pass
4748

4849

@@ -382,7 +383,7 @@ def reraise_client_error(self, exc):
382383

383384
slim_body = escape(body[:300])
384385

385-
self.log.warn("Fetching %s failed with %s. Body=%s", url, msg, slim_body)
386+
self.log.error("Fetching %s failed with %s. Body=%s", url, msg, slim_body)
386387
raise web.HTTPError(code, msg)
387388

388389
@contextmanager
@@ -414,11 +415,12 @@ async def fetch(self, url, **overrides):
414415
response = await self.client.fetch(url, **kw)
415416
return response
416417

417-
def write_error(self, status_code, **kwargs):
418+
def write_error(self, status_code: int, **kwargs):
418419
"""render custom error pages"""
419420
exc_info = kwargs.get("exc_info")
420-
message = ""
421+
message: str = ""
421422
status_message = responses.get(status_code, "Unknown")
423+
exception = None
422424
if exc_info:
423425
# get the custom message, if defined
424426
exception = exc_info[1]
@@ -529,6 +531,7 @@ def cached(method):
529531
Writing to the cache must be handled in the decorated method.
530532
"""
531533

534+
@wraps(method)
532535
async def cached_method(self, *args, **kwargs):
533536
uri = self.request.path
534537
short_url = self.truncate(uri)

nbviewer/providers/github/client.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
from ...utils import response_text
1717
from ...utils import url_path_join
1818

19+
1920
# -----------------------------------------------------------------------------
2021
# Async GitHub Client
2122
# -----------------------------------------------------------------------------

0 commit comments

Comments
 (0)