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()
🌐
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
If you want to run Jupyter notebook file in terminal, you can. (just you should install ipython library : pip install ipython)
Starred by 13 users
Forked by 5 users
Languages   Jupyter Notebook
🌐
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. Before we embark on this journey, make sure you have the following prerequisites installed on your system:
🌐
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
🌐
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 ...
🌐
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.
🌐
Bogotobogo
bogotobogo.com › python › Flask › Python_Flask_Embedding_Machine_Learning_2.php
Flask with Embedded Machine Learning II : Basic Flask App - 2020
Simple tool - Concatenating slides using FFmpeg ... iPython - Signal Processing with NumPy iPython and Jupyter - Install Jupyter, iPython Notebook, drawing with Matplotlib, and publishing it to Github iPython and Jupyter Notebook with Embedded D3.js Downloading YouTube videos using youtube-dl embedded with Python Machine Learning : scikit-learn ...
Find elsewhere
🌐
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 ...
🌐
Stack Overflow
stackoverflow.com › questions › 52457582 › flask-application-inside-jupyter-notebook
python - Flask application inside Jupyter Notebook - Stack Overflow
The fact that it uses ipython could lead to memory issues too. ... Have you tried a different port for your app? Since (1) it’s working without jupyter and (2) jupyter relies heavily on zmq but Flask doesn’t, I assume this is some incompatibility between your app and Jupyter (not a networking or firewall problem).
🌐
GitHub
github.com › azocher › flask-jupyter
GitHub - azocher/flask-jupyter: So you want to include 👾Jupyter written scripts in your 🍸Flask project, huh?
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%
🌐
Finxter
blog.finxter.com › home › learn python blog › how to install flask in python?
How to Install flask in Python? - Be on the Right Side of Change
September 28, 2021 - Make sure to select only “flask” ... any package in a Jupyter notebook, you can prefix the !pip install my_package statement with the exclamation mark "!"....
🌐
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 - ... Within seconds of arriving to their web page, you can have a basic app up and running. Simply copy the python code you see and save as ‘hello.py’, pip install flask from your terminal, and run your ‘hello’ flask app!
🌐
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
🌐
AiHints
aihints.com › home › how to install flask in jupyter notebook
How to install flask in Jupyter Notebook - AiHints
July 6, 2022 - You can install the flask in the Jupyter Notebook with the following code. After installation, you can import the flask library.
🌐
GitHub
github.com › topics › flask-application
flask-application · GitHub Topics · GitHub
The notebook also contains other approaches for POC including SVD. Backend APIs are based on Flask, Android appl… · python flask-application decision-trees knn android-java tf-idf-vectorizer skincare-recommendation ... This project utilizes deep learning to detect pneumonia from chest X-ray images, offering both model training and real-time inference through Jupyter Notebooks and a Flask web application.
🌐
Anvil
anvil.works › learn › tutorials › jupyter-notebook-to-web-app
Turning a Jupyter Notebook into a Web App - Anvil
We use the Anvil Uplink to connect a Jupyter Notebook to Anvil. It’s a library you can pip install on your computer or wherever your Notebook is running. ... It works for any Python process - this happens to be a Jupyter Notebook, but it could be an ordinary Python script, a Flask app, even the Python REPL!
🌐
Medium
danny.fyi › embedding-jupyter-notebooks-into-your-python-application-bfee5d50e4f8
Embedding Jupyter Notebooks into your Python application | by Danial Chowdhury | danny.fyi
January 16, 2017 - Embedding Jupyter Notebooks into your Python application Getting my Machine Learning models running on a Flask API server When building (Python) Machine Learning models, I’m convinced there’s no …
🌐
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
Bring the best of human thought and AI automation together at your work. Explore Stack Internal ... I want to Run a Flask Server inside a jupyter notebook for specific test and QA scenarios.