Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Upgrade nbconvert #1015

Merged
merged 42 commits into from
Nov 7, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
42 commits
Select commit Hold shift + click to select a range
091dd3b
Added nbconvert fix for #958 and a small flake8 issue
robindebois Oct 4, 2020
11205bd
Fix typos reported in #947
robindebois Oct 4, 2020
5428e40
have dev requirements requires normal files
Carreau Mar 15, 2022
eaa612d
Merge remote-tracking branch 'origin/pull/959'
Carreau Mar 15, 2022
e0da640
requirements
Carreau Mar 15, 2022
e7cad49
in prorgess
Carreau Mar 15, 2022
aef3d9e
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Mar 15, 2022
14731bc
Upgrade nbconvert
martinRenou Aug 11, 2022
fc413a4
Re-generate requirements
martinRenou Aug 11, 2022
9b2ebeb
restore missing index.html files
minrk Aug 22, 2022
b719c0a
add missing requirements.txt to Dockerfile
minrk Aug 22, 2022
8de92ca
remove outdated slides_reveal template
minrk Aug 22, 2022
76e227b
switch tests to pytest
minrk Aug 22, 2022
5556d13
need libcurl-dev for pycurl
minrk Aug 22, 2022
3a56973
requirements-dev shouldn't depend on pinned requirements.txt
minrk Aug 22, 2022
78c0099
missing raw-string prefix on regex
minrk Aug 22, 2022
ecbf8cf
monor making it work
Carreau Oct 31, 2022
9a49c77
test
Carreau Oct 31, 2022
a4ab0cc
Revert "test"
Carreau Oct 31, 2022
92f0a80
Minimal style update to confirm with previous
Carreau Oct 31, 2022
25d4dbe
bump minimal python version
Carreau Oct 31, 2022
54a9091
bump some version
Carreau Oct 31, 2022
987fb56
fix unbound
Carreau Oct 31, 2022
aa08341
Debug and typing
Carreau Oct 31, 2022
142d690
more fixes
Carreau Oct 31, 2022
23b023a
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Oct 31, 2022
df9154c
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Oct 31, 2022
f3f82d5
debug
Carreau Oct 31, 2022
9251d8a
debug
Carreau Oct 31, 2022
345ec8c
remove assert
Carreau Oct 31, 2022
5ed7c43
debug
Carreau Oct 31, 2022
b22880b
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Oct 31, 2022
1298325
debug log
Carreau Oct 31, 2022
1052ba6
Merge remote-tracking branch 'martinRenou/upgrade-nbconvert' into upg…
Carreau Oct 31, 2022
892cc8f
More cleanup, + mypy
Carreau Oct 31, 2022
f571358
cleanup
Carreau Nov 1, 2022
4545153
reformat with black
Carreau Nov 1, 2022
9fcd1ff
remove reveal block, it now comes from nbconvert directly
Carreau Nov 1, 2022
fc85656
track down test failure
Carreau Nov 1, 2022
f08008d
Autofix is annoying as you can't keep pushing
Carreau Nov 1, 2022
bedbc93
please linter
Carreau Nov 1, 2022
b46085a
Update nbviewer/providers/github/handlers.py
Carreau Nov 1, 2022
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 48 additions & 0 deletions .github/workflows/test.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
name: test

on:
push:
branches:
pull_request:

jobs:
test:
runs-on: ubuntu-20.04
strategy:
matrix:
python:
- "3.8"
- "3.9"
- "3.10"
steps:
- name: Checkout
uses: actions/checkout@v3

- uses: actions/setup-python@v4
with:
python-version: ${{ matrix.python }}

- name: install apt packages
# pycurl build requirements
run: |
sudo apt-get update && sudo apt-get -y install \
libcurl4-gnutls-dev \
libgnutls28-dev

- name: install
run: |
python3 -m pip install -r requirements.in -r requirements-dev.txt
- name: install mypy
run: |
python3 -m pip install mypy types-pycurl types-requests types-Markdown
- name: run mypy
run: |
mypy nbviewer

- name: pip freeze
run: |
python3 -m pip freeze

- name: run tests
run: |
pytest -v nbviewer/tests -s
8 changes: 5 additions & 3 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -4,19 +4,21 @@ repos:
hooks:
- id: reorder-python-imports
- repo: https://github.com/psf/black
rev: "22.1.0"
rev: "22.10.0"
hooks:
- id: black
- repo: https://github.com/PyCQA/flake8
rev: "4.0.1"
rev: "5.0.4"
hooks:
- id: flake8
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.1.0
rev: v4.3.0
hooks:
- id: end-of-file-fixer
- id: check-json
- id: check-yaml
exclude: ^helm-chart/nbviewer/templates/
- id: check-case-conflict
- id: check-executables-have-shebangs
ci:
autofix_prs: false
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ Pass `-d` or `--debug` to `invoke less` to create a CSS sourcemap, useful for de

```shell
$ cd <path to repo>
$ python -m nbviewer --debug --no-cache
$ python -m nbviewer --debug --no-cache --host=127.0.0.1
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think listening on 0.0.0.0 by default is a security problem. Well, here on macos, it present me from doing so without root access so It's ok-ish, but i'd like to fix it.

```

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.
Expand Down
7 changes: 3 additions & 4 deletions nbviewer/_version.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import re
import subprocess
import sys
from typing import Dict


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


LONG_VERSION_PY = {}
LONG_VERSION_PY: Dict[str, str] = {}
HANDLERS = {}


Expand Down Expand Up @@ -93,9 +94,7 @@ def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, env=
if verbose:
print("unable to find command, tried %s" % (commands,))
return None, None
stdout = p.communicate()[0].strip()
if sys.version_info[0] >= 3:
stdout = stdout.decode()
stdout = p.communicate()[0].strip().decode()
if p.returncode != 0:
if verbose:
print("unable to run %s (error)" % dispcmd)
Expand Down
40 changes: 20 additions & 20 deletions nbviewer/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,16 @@
import os
from concurrent.futures import ProcessPoolExecutor
from concurrent.futures import ThreadPoolExecutor
from functools import cached_property
from html import escape
from urllib.parse import urlparse

import markdown
from jinja2 import Environment
from jinja2 import FileSystemLoader
from nbconvert.exporters.export import exporter_map
from jupyter_server.base.handlers import FileFindHandler as StaticFileHandler # type: ignore
Carreau marked this conversation as resolved.
Show resolved Hide resolved
from nbconvert import get_exporter # type: ignore
from nbconvert.exporters.templateexporter import ExtensionTolerantLoader # type: ignore
from tornado import httpserver
from tornado import ioloop
from tornado import web
Expand Down Expand Up @@ -50,13 +53,6 @@
from .utils import jupyter_info
from .utils import url_path_join

try: # Python 3.8
from functools import cached_property
except ImportError:
from .utils import cached_property

from jupyter_server.base.handlers import FileFindHandler as StaticFileHandler

# -----------------------------------------------------------------------------
# Code
# -----------------------------------------------------------------------------
Expand All @@ -67,16 +63,16 @@

def nrhead():
try:
import newrelic.agent
except ImportError:
import newrelic.agent # type: ignore
except ModuleNotFoundError:
return ""
return newrelic.agent.get_browser_timing_header()


def nrfoot():
try:
import newrelic.agent
except ImportError:
except ModuleNotFoundError:
return ""
return newrelic.agent.get_browser_timing_footer()

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

name = Unicode("NBViewer")

aliases = Dict(
aliases = Dict( # type: ignore
{
"base-url": "NBViewer.base_url",
"binder-base-url": "NBViewer.binder_base_url",
Expand Down Expand Up @@ -128,7 +124,7 @@ class NBViewer(Application):
}
)

flags = Dict(
flags = Dict( # type: ignore
{
"debug": (
{"Application": {"log_level": logging.DEBUG}},
Expand Down Expand Up @@ -468,7 +464,11 @@ def default_endpoint(self):

@cached_property
def env(self):
env = Environment(loader=FileSystemLoader(self.template_paths), autoescape=True)
loader = ExtensionTolerantLoader(FileSystemLoader(self.template_paths), ".j2")
env = Environment(
loader=loader,
autoescape=True,
)
env.filters["markdown"] = markdown.markdown
try:
git_data = git_info(here)
Expand Down Expand Up @@ -528,7 +528,7 @@ def frontpage_setup(self):

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

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

# This would be better defined in a class
self.config.HTMLExporter.template_file = "basic"
self.config.SlidesExporter.template_file = "slides_reveal"
# self.config.HTMLExporter.template_file = "base"
# self.config.SlidesExporter.template_file = "slides_reveal"

self.config.TemplateExporter.template_path = [
self.config.TemplateExporter.extra_template_basedirs = [
os.path.join(os.path.dirname(__file__), "templates", "nbconvert")
]

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

http_server = httpserver.HTTPServer(app, xheaders=True, ssl_options=ssl_options)
nbviewer.log.info(
"Listening on %s:%i, path %s",
"Listening on http://%s:%i, path %s",
Carreau marked this conversation as resolved.
Show resolved Hide resolved
nbviewer.host,
nbviewer.port,
app.settings["base_url"],
Expand Down
6 changes: 3 additions & 3 deletions nbviewer/cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,9 @@
from tornado.log import app_log

try:
import pylibmc
except ImportError:
pylibmc = None
import pylibmc # type: ignore
except ModuleNotFoundError:
pylibmc = None # type: ignore

# -----------------------------------------------------------------------------
# Code
Expand Down
4 changes: 2 additions & 2 deletions nbviewer/formats.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,9 +55,9 @@ def test_slides(nb, json):
return False

return {
"html": {"nbconvert_template": "basic", "label": "Notebook", "icon": "book"},
"html": {"nbconvert_template": "lab", "label": "Notebook", "icon": "book"},
"slides": {
"nbconvert_template": "slides_reveal",
# "nbconvert_template": "slides_reveal",
Carreau marked this conversation as resolved.
Show resolved Hide resolved
"label": "Slides",
"icon": "gift",
"test": test_slides,
Expand Down
19 changes: 11 additions & 8 deletions nbviewer/providers/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,16 @@
import time
from contextlib import contextmanager
from datetime import datetime
from functools import wraps
from html import escape
from http.client import responses
from urllib.parse import quote
from urllib.parse import urlencode
from urllib.parse import urlparse
from urllib.parse import urlunparse

import statsd
from nbformat import current_nbformat
import statsd # type: ignore
from nbformat import current_nbformat # type:ignore
from nbformat import reads
from tornado import httpclient
from tornado import web
Expand All @@ -39,10 +40,10 @@
try:
import pycurl
from tornado.curl_httpclient import CurlError
except ImportError:
pycurl = None
except ModuleNotFoundError:
pycurl = None # type: ignore

class CurlError(Exception):
class CurlError(Exception): # type: ignore
pass


Expand Down Expand Up @@ -382,7 +383,7 @@ def reraise_client_error(self, exc):

slim_body = escape(body[:300])

self.log.warn("Fetching %s failed with %s. Body=%s", url, msg, slim_body)
self.log.error("Fetching %s failed with %s. Body=%s", url, msg, slim_body)
raise web.HTTPError(code, msg)

@contextmanager
Expand Down Expand Up @@ -414,11 +415,12 @@ async def fetch(self, url, **overrides):
response = await self.client.fetch(url, **kw)
return response

def write_error(self, status_code, **kwargs):
def write_error(self, status_code: int, **kwargs):
"""render custom error pages"""
exc_info = kwargs.get("exc_info")
message = ""
message: str = ""
status_message = responses.get(status_code, "Unknown")
exception = None
if exc_info:
# get the custom message, if defined
exception = exc_info[1]
Expand Down Expand Up @@ -529,6 +531,7 @@ def cached(method):
Writing to the cache must be handled in the decorated method.
"""

@wraps(method)
async def cached_method(self, *args, **kwargs):
uri = self.request.path
short_url = self.truncate(uri)
Expand Down
1 change: 1 addition & 0 deletions nbviewer/providers/github/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
from ...utils import response_text
from ...utils import url_path_join


# -----------------------------------------------------------------------------
# Async GitHub Client
# -----------------------------------------------------------------------------
Expand Down
Loading