I installed Jupyter and Flask and your original code works.
The flask.Flask object is a WSGI application, not a server. Flask uses Werkzeug's development server as a WSGI server when you call python -m flask run in your shell. It creates a new WSGI server and then passes your app as paremeter to werkzeug.serving.run_simple. Maybe you can try doing that manually:
from werkzeug.wrappers import Request, Response
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello():
return "Hello World!"
if __name__ == '__main__':
from werkzeug.serving import run_simple
run_simple('localhost', 9000, app)
Flask.run() calls run_simple() internally, so there should be no difference here.
I installed Jupyter and Flask and your original code works.
The flask.Flask object is a WSGI application, not a server. Flask uses Werkzeug's development server as a WSGI server when you call python -m flask run in your shell. It creates a new WSGI server and then passes your app as paremeter to werkzeug.serving.run_simple. Maybe you can try doing that manually:
from werkzeug.wrappers import Request, Response
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello():
return "Hello World!"
if __name__ == '__main__':
from werkzeug.serving import run_simple
run_simple('localhost', 9000, app)
Flask.run() calls run_simple() internally, so there should be no difference here.
The trick is to run the Flask server in a separate thread. This code allows registering data providers. The key features are
Find a free port for the server. If you run multiple instances of the server in different notebooks they would compete for the same port.
The
register_datafunction returns the URL of the server so you can use it for whatever you need.The server is started on-demand (when the first data provider is registered)
Note: I added the
@cross_origin()decorator from theflask-corspackage. Else you cannot call the API form within the notebook.Note: there is no way to stop the server in this code...
Note: The code uses typing and python
3.Note: There is no good error handling at the moment
import socket
import threading
import uuid
from typing import Any, Callable, cast, Optional
from flask import Flask, abort, jsonify
from flask_cors import cross_origin
from werkzeug.serving import run_simple
app = Flask('DataServer')
@app.route('/data/<id>')
@cross_origin()
def data(id: str) -> Any:
func = _data.get(id)
if not func:
abort(400)
return jsonify(func())
_data = {}
_port: int = 0
def register_data(f: Callable[[], Any], id: Optional[str] = None) -> str:
"""Sets a callback for data and returns a URL"""
_start_sever()
id = id or str(uuid.uuid4())
_data[id] = f
return f'http://localhost:{_port}/data/{id}'
def _init_port() -> int:
"""Creates a random free port."""
# see https://stackoverflow.com/a/5089963/2297345
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(('localhost', 0))
port = sock.getsockname()[1]
sock.close()
return cast(int, port)
def _start_sever() -> None:
"""Starts a flask server in the background."""
global _port
if _port:
return
_port = _init_port()
thread = threading.Thread(target=lambda: run_simple('localhost', _port, app))
thread.start()
python - How to run Flask inside a Jupyter notebook block for easy testing? - Stack Overflow
Can you put a juypter notebook inside a flask app?
Jupyter server from within a Flask app - anyone?
Why not just
from yourapp import models
you can put that into an ipython profile and have your models available. Or you use an ipython profile and use this part of the flask documentation to build your own ipython shell.
More on reddit.comFlask Replacement for Jupyter Notebook and PostgreSQL
Videos
I am new to juypter notebooks but I have made some basic web apps before using flask.
I want to wrap up an old version of juypter notebook into a flask app. The idea being is that I want to host the notebook online using Azure or Heroku and lock the website using microsoft identity protection msal library for python.
I have been able to containerize my notebook into a docker container and I am about to test a basic deployment to azure, but I don't know how I can write a basic flask app to server the notebook's url.
Infact, is it even possible to have juypter notebook running while flask is running?
Flask is just to make a html template for a login screen to the notebook. if that makes sense.
I'm here with a question, hoping not to be the first one...
I have a large-ish Flask app that already has the shell command for starting an IPython (if available) env... I'd like the same but for Jupyter notebook server - as in any notebooks created with it are within the Flask app env. It's mostly for the SQLAlchemy bindings. App context could be a global (variable), with request contexts on demand (as for testing).
I did google, didn't find anything reasonable unfortunately.
Thank you for all and any solutions/pointers/opinions.
Why not just
from yourapp import models
you can put that into an ipython profile and have your models available. Or you use an ipython profile and use this part of the flask documentation to build your own ipython shell.
You can not connect juypter notebook to a running kernel. But you can connect qtcpnsole or a regular ipython console to a running kernel. Spyder the ide will also connect to a running kernel.
Embed a kernel instance and then connect to it with one of the above I mentioned.