在Jupyter Notebook中调试Flask服务器 [英] debug Flask server inside Jupyter Notebook

查看:362
本文介绍了在Jupyter Notebook中调试Flask服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在jupyter笔记本中调试小型烧瓶服务器以进行演示.

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

我在最新的Ubuntu和Python2上创建了virtualenv(在使用Python3的Mac上也发生了此错误),pip安装flask jupyter.

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

但是,当我使用helloworld脚本创建单元时,它无法在笔记本中运行.

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)

文件 "/home/***/test/local/lib/python2.7/site-packages/ipykernel/kernelapp.py", 第177行,在_bind_socket中 s.bind("tcp://%s:%i"%(self.ip,端口))文件"zmq/backend/cython/socket.pyx",行495,在 zmq.backend.cython.socket.Socket.bind (zmq/backend/cython/socket.c:5653)文件 "zmq/backend/cython/checkrc.pxd",第25行,在 zmq.backend.cython.checkrc._check_rc (zmq/后端/cython/socket.c:10014) 引发ZMQError(errno)ZMQError:地址已在使用中

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-每次失败后,我都要更改端口号.

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

当然,它可以作为独立脚本运行.

Sure, it runs as a standalone script.

无需(debug = True)更新就可以.

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

推荐答案

我安装了Jupyter和Flask,您的原始代码也可以正常工作.

I installed Jupyter and Flask and your original code works.

flask.Flask对象是WSGI应用程序,而不是服务器.当您在Shell中调用python -m flask run时,Flask将Werkzeug的开发服务器用作WSGI服务器.它创建一个新的WSGI服务器,然后将您的应用程序作为参数传递给werkzeug.serving.run_simple.也许您可以尝试手动执行此操作:

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()在内部调用run_simple(),因此此处应该没有区别.

Flask.run() calls run_simple() internally, so there should be no difference here.

这篇关于在Jupyter Notebook中调试Flask服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆