How to use Jupyter notebooks with Flask app

The strong part of Python and other interpreted languages is an interactive shell. But there is an even more powerful tool - Jupyter notebook.

In a simple case it allows to:

  • verify how some code works
  • check hypothesis
  • save these experiments and continue to work on them later
  • share them with the colleagues

Here is an example how to run and use it with a Flask project. Suppose that Flask app is in Docker container and there is a docker-compose file to run it.
Add to your pip requirements notebook.
Create a directory to store Jupyter notebooks, like jupyter_notebooks.

To run jupyter

docker-compose run --rm -p 8888:8888 backend sh -c 'jupyter notebook --ip=* --notebook-dir=jupyter_notebooks'

It will print something like this

[I 11:25:50.687 NotebookApp] The Jupyter Notebook is running at: http://[all ip addresses on your system]:8888/?token=f08640004cc4cd6a1fd110db3753c4965b892c0c86fdfa4a

Go to this url, create a new notebook and add autoreload instruction.

%load_ext autoreload
%autoreload 2

Import path of your application

import sys
sys.path.append('..')

Run your functions. If you need an application context, use app_context method.

from application.main import app
with app.app_context():
    rest.post(str(banner.id), client=user.client, user=user)
comments powered by Disqus