Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

debug Flask server inside Jupyter Notebook

I want to debug small flask server inside jupyter notebook for demo.

I created virtualenv on latest Ubuntu and Python2 (on Mac with Python3 this error occurs as well), pip install flask jupyter.

However, when I create a cell with helloworld script it does not run inside notebook.

from flask import Flask
app = Flask(__name__)

@app.route("/")
def hello():
    return "Hello World!"

if __name__ == "__main__":
    app.run(debug=True,port=1234)

File "/home/***/test/local/lib/python2.7/site-packages/ipykernel/kernelapp.py", line 177, in _bind_socket s.bind("tcp://%s:%i" % (self.ip, port)) File "zmq/backend/cython/socket.pyx", line 495, in zmq.backend.cython.socket.Socket.bind (zmq/backend/cython/socket.c:5653) File "zmq/backend/cython/checkrc.pxd", line 25, in zmq.backend.cython.checkrc._check_rc (zmq/backend/cython/socket.c:10014) raise ZMQError(errno) ZMQError: Address already in use

NB - I change the port number after each time it fails.

Sure, it runs as a standalone script.

update without (debug=True) it's ok.

like image 726
chro Avatar asked Jan 24 '17 15:01

chro


People also ask

How do you debug a Flask server?

To enable the debugger, run the development server with the FLASK_ENV environment variable set to development . This puts Flask in debug mode, which changes how it handles some errors, and enables the debugger and reloader. FLASK_ENV can only be set as an environment variable.

Can I run Flask app in Jupyter Notebook?

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!

Is debugging possible in Jupyter Notebook?

Debug code in Jupyter notebooks The Jupyter Notebook Debugger tool window opens. Debugging is performed within a single code cell. However, if your code cell calls a function from any cell that has been already debugged, you can step into it. The related breakpoints will also work.


1 Answers

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.

like image 118
yorodm Avatar answered Oct 04 '22 17:10

yorodm