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.

Answer from yorodm on Stack Overflow
Top answer
1 of 4
30

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.

2 of 4
4

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_data function 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 the flask-cors package. 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()
🌐
Stack Overflow
stackoverflow.com › questions › 52457582 › flask-application-inside-jupyter-notebook
python - Flask application inside Jupyter Notebook - Stack Overflow
If I try the same application from outside notebook everything works. Is there any configuration that I need to make inside Jupyter? from flask import Flask app = Flask(__name__) @app.route("/") def hello(): return "Hello World" if __name__ == "__main__": app.debug = True app.run(host='0.0.0.0',port=5005) * Running on http://0.0.0.0:5005/ (Press CTRL+C to quit)
Discussions

python - How to run Flask inside a Jupyter notebook block for easy testing? - Stack Overflow
I want to Run a Flask Server inside a jupyter notebook for specific test and QA scenarios. I do understand that it is not wise to run a server inside notebook(As mentioned in the comments of this More on stackoverflow.com
🌐 stackoverflow.com
Can you put a juypter notebook inside a flask app?
Is it an option to ditch flask entirely and host the notebook on Google Collab or binder ? That likely is the easiest to get the code to run online in a public space (an free) More on reddit.com
🌐 r/flask
8
7
July 2, 2022
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.com
🌐 r/Python
2
6
January 31, 2016
Flask Replacement for Jupyter Notebook and PostgreSQL
I have switched to VSCode exclusively for development. I install some of the Python plugins for convenience. Just a thought: if the point is for people to use a Jupyter Lab-style environment, why not use that? The project is built around client/server. See the docs here: https://jupyter-notebook.readthedocs.io/en/stable/public_server.html . Looks like you can set up a server for others to connect to and use. I have only used the library locally so I can't really speak to how it works. Alternatively, you could use something like Streamlit, or Pywebio as a middle-ground for learning Python, but also having some of the building blocks already there for you. I believe flask can integrate with both. Not to try to deter you from using Flask. I love this framework, and it can support just about any project you can think up. Whatever you decide to do it sounds like a fun project! Good luck! More on reddit.com
🌐 r/flask
16
11
November 2, 2022
🌐
GitHub
github.com › orhannurkan › Flask_server_in_Jupyter
GitHub - orhannurkan/Flask_server_in_Jupyter: Flask API in Jupyter Notebook runs as a Service 1 · GitHub
Flask API in Jupyter Notebook runs as a Service 1. Contribute to orhannurkan/Flask_server_in_Jupyter development by creating an account on GitHub.
Starred by 13 users
Forked by 5 users
Languages   Jupyter Notebook
🌐
YouTube
youtube.com › probhakar sarkar
Create your own Jupyter Notebook using Python Flask - YouTube
AboutPressCopyrightContact usCreatorsAdvertiseDevelopersTermsPrivacyPolicy & SafetyHow YouTube worksTest new featuresNFL Sunday Ticket · © 2024 Google LLC
Published   May 8, 2021
Views   2K
🌐
Sneawo
blog.sneawo.com › blog › 2017 › 06 › 27 › how-to-use-jupyter-notebooks-with-flask-app
How to use Jupyter notebooks with Flask app - Andrey Zhukov's Tech Blog
The strong part of Python and other interpreted languages is an interactive shell. But there is an even more powerful tool - Jupyter notebook. ... 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 ...
🌐
DevOps.dev
blog.devops.dev › mastering-web-services-with-jupyter-notebook-and-flask-a-comprehensive-guide-with-postman-15d6a2f18d62
Mastering Web Services with Jupyter Notebook and Flask: A Comprehensive Guide with Postman Integration | by Rajdeep Sarkar. | DevOps.dev
September 4, 2023 - In this comprehensive guide, we’ll explore how to add web services to your Jupyter Notebook using Flask, a popular Python web framework. We’ll also delve into Postman, a vital tool for testing APIs, and demonstrate how to configure and run your web service from the command prompt.
🌐
Stack Overflow
stackoverflow.com › questions › 75081962 › how-to-run-flask-inside-a-jupyter-notebook-block-for-easy-testing
python - How to run Flask inside a Jupyter notebook block for easy testing? - Stack Overflow
I do understand that it is not wise to run a server inside notebook(As mentioned in the comments of this question). However, I want to test a specific function that both requires a flask AppContext and a running server. It is a third-party API webhook handler and the third party does not have method to generate fake webhooks.
Find elsewhere
🌐
YouTube
youtube.com › watch
Deploying Python, Jupyter Notebook & Flask Apps in the Cloud in Real-Time - YouTube
This brief tutorial shows how to create a DigitalOcean Droplet and how to easily and quickly deploy Python, Jupyter Notebook and a Flask application on it.Th...
Published   July 30, 2015
🌐
GitHub
github.com › azocher › flask-jupyter
GitHub - azocher/flask-jupyter: So you want to include 👾Jupyter written scripts in your 🍸Flask project, huh?
In order to run our scripts we need the data source or file our data scientist originally refered to, and the scripts they wrote in their Jupyter Notebook. Get a local or remote link to the data file (ideally a .csv or JSON file, depending on what type of data science is being done). Receive the relevant Jupyter Notebook file, and make sure both are in your project folder. We are going to setup a default Flask server instance to run our script from.
Forked by 2 users
Languages   Jupyter Notebook 98.8% | Jupyter Notebook 98.8%
🌐
Better Programming
betterprogramming.pub › setting-up-a-simple-api-b3b00bc026b4
Using Flask to Build a Simple API | by Samantha Jackson | Better Programming
May 30, 2019 - Since both were already fit to my data, I simply call .transform() on the input features for each, just as I would have done after I trained them in my Jupyter notebook. As for my model, once the pickled model is loaded, I just call .predict() on my encoded features and it will return a prediction. The code below shows how I set up an API server to produce a prediction based on animal features. As you can see, it has the same basic features as my ‘hello.py’ file — the decorators tell Flask the URL where it can be accessed, the types of requests it will accept, and how to respond to those requests.
🌐
freeCodeCamp
freecodecamp.org › news › machine-learning-web-app-with-flask
How to Turn Your Jupyter Notebook into a User-Friendly Web App
October 3, 2022 - In this article, we will go through the process of building and deploying a machine learning web app using Flask and PythonAnywhere.
🌐
Google Groups
groups.google.com › g › jupyter › c › GRx3AnzlRlQ
Flask application problem on Jupyter notebook installed through Anaconda
I have a python application using Flask. It runs fine from command prompt on Windows 10. But when I try to run the same application from Jupyter Notebook (from Anaconda), I get following error for the ... UnsupportedOperation Traceback (most recent call last) <ipython-input-13-b728e01956cc> in <module>() ----> 1 app.run(debug=True, port=8000) ~\AppData\Local\conda\conda\envs\deeplearning\lib\site-packages\flask\app.py in run(self, host, port, debug, load_dotenv, **options) 936 options.setdefault('threaded', True) 937 --> 938 cli.show_server_banner(self.env, self.debug, self.name, False) 939 94
🌐
Bogotobogo
bogotobogo.com › python › Flask › Python_Flask_Embedding_Machine_Learning_2.php
Flask with Embedded Machine Learning II : Basic Flask App - 2020
The templates directory is the directory where Flask will look for static HTML files to render. ... We run our application as a single module and initializes a new Flask instance with the argument __name__ to let Flask know that it can find the HTML template folder, templates, in the same directory where our module (app.py) is located:
🌐
Medium
medium.com › techcrush › how-to-deploy-your-ml-model-in-jupyter-notebook-to-your-flask-app-d1c4933b29b5
How to deploy your ML model in Jupyter Notebook to your Flask App? | by jaseem CK | TechCrush | Medium
April 27, 2020 - We have to take the model.pkl file that we got from the notebook output to the project directory so that we can use that. Then, in the app.py file insert these code. import os import pandas as pd import numpy as np import flask import pickle ...
🌐
Reddit
reddit.com › r/flask › can you put a juypter notebook inside a flask app?
r/flask on Reddit: Can you put a juypter notebook inside a flask app?
July 2, 2022 -

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.

🌐
Teacher 2.0
nighthawkcoders.github.io › teacher_portfolio › c4.0 › 2023 › 09 › 06 › python-flask_in_jupyter_IPYNB_2_.html
Python/Flask in Jupyter | Teacher 2.0 - GitHub Pages
September 6, 2023 - Learn how to stop the Python/Flask process gracefully. Note: Jupyter magic commmand %%python --bg that follows runs the server in background. This enables us to continue interacting with the subsequent Notebook cells.
🌐
Kaggle
kaggle.com › code › gajjadarahul › access-flask-api-from-anywhere-jupyter-colab
Access Flask API from anywhere Jupyter / Colab
Checking your browser before accessing www.kaggle.com · Click here if you are not automatically redirected after 5 seconds
🌐
GitHub
github.com › iiSeymour › Flasked-Notebooks
GitHub - iiSeymour/Flasked-Notebooks: Rendering IPython Notebooks using Flask
Proof of concept for dynamically rendering IPython Notebooks using Flask: Unlike nbviewer each code cell in a notebook is executed on request. Input variables can be injected to a notebook before executed it. Running app.py starts the flask site which renders the markdown and updated code output cells.
Starred by 65 users
Forked by 18 users
Languages   Python 96.1% | CSS 3.9% | Python 96.1% | CSS 3.9%
🌐
Reddit
reddit.com › r/python › jupyter server from within a flask app - anyone?
r/Python on Reddit: Jupyter server from within a Flask app - anyone?
January 31, 2016 -

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.